diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8f608db6..5a3606eb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -753,6 +753,14 @@ jobs: fi echo "VERSION=$GOT" >> "$GITHUB_ENV" + - name: A published release has an English summary + if: github.ref_type == 'tag' + run: | + if [ ! -f "release-notes/$VERSION.md" ]; then + echo "缺少英文发布说明:release-notes/$VERSION.md" >&2 + exit 1 + fi + # 清单向 GitHub 要:和它在发布页上「自动生成」的是同一份。演练时这个 tag # 可能还不存在,那就算到这次的 commit 为止(tag 存在时 target_commitish 不起作用) - name: Write it @@ -790,9 +798,8 @@ jobs: - run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" - # tag 上那段话写进 latest.json,是给已经装上的应用的发布说明(2026.9.13 - # 之前的版本在更新窗口里显示它)—— 自动生成的提交清单在那个位置对用户 - # 没有意义。发布页上的正文是另一份,见 `release-body`。 + # tag 注解给应用的更新窗口提供中文说明。manifest.py 也会从 + # release-notes/<版本>.md 读出英文摘要,供英文界面使用。 # # **不从工作区的 git 里读。**`actions/checkout` 取 tag 时建的是一个 # 直接指向 commit 的轻量引用,注解对象根本不在这个克隆里; @@ -806,7 +813,7 @@ jobs: set -euo pipefail : > notes.txt REF="repos/$GITHUB_REPOSITORY/git/ref/tags/$GITHUB_REF_NAME" - # 轻量 tag 指向的是 commit,没有正文可取 —— 那就不写发布说明。 + # 轻量 tag 取不到注解,manifest.py 会报缺少中文发布说明。 if [ "$(gh api "$REF" --jq .object.type)" = tag ]; then SHA=$(gh api "$REF" --jq .object.sha) gh api "repos/$GITHUB_REPOSITORY/git/tags/$SHA" --jq .message \ @@ -825,7 +832,7 @@ jobs: - name: One manifest for every platform run: | set -euo pipefail - python3 scripts/manifest.py "$VERSION" notes.txt \ + python3 -B scripts/manifest.py "$VERSION" notes.txt \ "darwin-aarch64=dist/ThinkWatch-Lite-$VERSION-darwin-arm64.dmg" \ "windows-x86_64=dist/ThinkWatch-Lite-$VERSION-windows-x64-setup.exe" \ "windows-aarch64=dist/ThinkWatch-Lite-$VERSION-windows-arm64-setup.exe" \ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4cf0559c..b535f44e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -129,6 +129,14 @@ Warnings are errors. The toolchain is `stable`, so a newer stable than your local one can surface lints you cannot see — `rustup update stable` before blaming CI. +## Translating protection rules + +When updating the Core pin, update `src/i18n/guard.zh.json` for any +added or changed security rules. Use the guard and rule ID for a rule, +or the guard and slug for a group. The security UI, messages and native +notifications share this catalog. Core supplies the English fallback, +and prefix descriptions are rendered from the live matcher. + ## Things this UI must not do These are load-bearing and a PR that breaks one will be asked to change: @@ -201,28 +209,26 @@ change to `release.yml`, push the branch as `rehearse/`: every job runs and the installers are kept as the run's artifacts, but nothing is published. -A release has two texts: - -- **The tag message.** Its first line is `ThinkWatch Lite `; the - rest becomes the `notes` of `latest.json`, the manifest for in-app - updates. It is not shown on the release page. -- **The release page**, titled `ThinkWatch Lite ` and written in - English by `scripts/release_notes.py`, in this order: - 1. `release-notes/.md`, when that file exists: a summary of the - release in paragraphs or lists, without a top-level heading. Add it in - the pull request that bumps the version, because the tag fixes what - the tree contains. - 2. A table of the file for each platform, and the Homebrew and Linux - install commands. - 3. How to verify a download against its `.sha256`. - 4. GitHub's list of the pull requests merged since the previous release. - - The text is written when the release is created. A release that already - exists keeps its text, so a correction after publishing is made on the - release page itself. CI runs `python3 scripts/release_notes_test.py`, - which checks the script against `release.yml` and renders every file in - `release-notes/`; a rehearsal shows the complete text in the summary of - its run. +Each published release needs two Markdown summaries for the in-app update window. + +- Write the **Chinese summary** in the annotated tag message after the + `ThinkWatch Lite ` title and a blank line. It becomes `notes` + in `latest.json`. +- Add the **English summary** at `release-notes/.md` in the pull + request that bumps the version. Use paragraphs or lists and start any + headings at level two. It becomes `notes_en` in `latest.json` and the + first section of the GitHub release page. + +The release page is titled `ThinkWatch Lite ` and generated by +`scripts/release_notes.py`. After the English summary, it lists the +downloads and install commands, explains how to verify the downloads, +and includes GitHub's list of pull requests merged since the previous release. + +The text is written when the release is created. To correct it after +publication, edit the release page directly. CI runs +`python3 scripts/release_notes_test.py` to check the release scripts and +every file in `release-notes/`. A rehearsal shows the release page text +in the run summary and can run before the English summary is written. ## Product screenshots diff --git a/package.json b/package.json index 15a1e3df..218e64ba 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "thinkwatch-lite", "private": true, "description": "Desktop app for a local AI API gateway on macOS, Windows and Linux", - "version": "2026.11.20", + "version": "2026.11.22", "type": "module", "packageManager": "pnpm@11.13.1", "scripts": { diff --git a/release-notes/2026.11.22.md b/release-notes/2026.11.22.md new file mode 100644 index 00000000..761d995e --- /dev/null +++ b/release-notes/2026.11.22.md @@ -0,0 +1,2 @@ +- Added Japanese, Traditional Chinese, Korean, and Spanish to the app. ThinkWatch Lite follows the system's preferred language at startup. You can also switch languages in Settings. +- The update window now shows release notes when available, with support for Markdown, wrapping, and scrolling. Chinese interfaces show the Chinese summary, and other interfaces show the English summary. diff --git a/scripts/manifest.py b/scripts/manifest.py index a69abc6d..8fb4436f 100755 --- a/scripts/manifest.py +++ b/scripts/manifest.py @@ -8,7 +8,9 @@ Linux 上只发 AppImage,它原地换掉自己(见 `src-tauri/src/update.rs`); `scripts/install.sh` 也从这一份里找本架构的 AppImage。 -用法:manifest.py <版本> <发布说明文件> <平台>=<文件> [<平台>=<文件> ...] +用法:manifest.py <版本> <中文发布说明文件> <平台>=<文件> [<平台>=<文件> ...] + +中文说明沿用 Tauri 的 notes 字段;英文说明取 release-notes/<版本>.md,写在 notes_en。 清单里的 URL 必须和最终挂在 release 上的文件名一字不差,所以文件名不在 这里拼:文件的路径由调用方传进来,URL 用的就是它的名字。两处各拼一遍的 @@ -26,6 +28,8 @@ import pathlib import sys +from release_notes import NOTES_DIR, NotesError, summary + REPO = "ThinkWatchProject/ThinkWatch-Lite" # 平台键由更新器自己拼:目标系统 + 架构(macOS 上叫 darwin)。**只收这几个** # —— 拼错一个字母,那个平台的用户就永远问不到新版本,而清单看起来完好。 @@ -88,10 +92,25 @@ def entry(path: pathlib.Path, version: str, want: bytes) -> dict: } +def update_notes(version: str, chinese_file: pathlib.Path, notes_dir: pathlib.Path = NOTES_DIR) -> dict[str, str]: + """老版本仍从 notes 读中文,新版本按语言读对应的一份。""" + chinese = chinese_file.read_text(encoding="utf-8").strip() + if not chinese: + raise NotesError(f"v{version} 的 tag 注解缺少中文发布说明:在标题和空行之后填写正文") + english = summary(version, notes_dir) + if english is None: + raise NotesError(f"缺少英文发布说明:release-notes/{version}.md") + return {"notes": chinese, "notes_en": english} + + def main() -> None: if len(sys.argv) < 4: - sys.exit("用法:manifest.py <版本> <发布说明文件> <平台>=<文件> [...]") + sys.exit("用法:manifest.py <版本> <中文发布说明文件> <平台>=<文件> [...]") version, notes_file, pairs = sys.argv[1], sys.argv[2], sys.argv[3:] + try: + notes = update_notes(version, pathlib.Path(notes_file)) + except NotesError as e: + sys.exit(str(e)) root = pathlib.Path(__file__).resolve().parent.parent conf = json.loads((root / "src-tauri/tauri.conf.json").read_text(encoding="utf-8")) @@ -121,10 +140,8 @@ def main() -> None: .isoformat() .replace("+00:00", "Z"), "platforms": platforms, + **notes, } - notes = pathlib.Path(notes_file).read_text(encoding="utf-8").strip() - if notes: - manifest["notes"] = notes out = pathlib.Path(pairs[0].partition("=")[2]).parent / "latest.json" out.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") diff --git a/scripts/release_notes.py b/scripts/release_notes.py index 18dd02a8..ba5cf64d 100755 --- a/scripts/release_notes.py +++ b/scripts/release_notes.py @@ -5,7 +5,7 @@ 正文是英文的,依次是: -1. `release-notes/<版本>.md`:这一版的说明。**可以没有**,没有就从下载表开始。 +1. `release-notes/<版本>.md`:这一版的英文说明。正式发版时必须提供,演练时可省略。 2. 下载表:每个文件一行(Windows 每个架构两行:安装程序、绿色版 zip),文件名和 release.yml 挂上去的一字不差;再给 Homebrew 和 Linux 安装脚本的命令、绿色版的 用法。 @@ -14,8 +14,8 @@ 调用方用 `gh api repos/<仓库>/releases/generate-notes` 取来。拆成参数传进来, 这个脚本就不碰网络,测试可以直接喂它。 -**tag 的注解不在这里。**那段中文写进 latest.json(见 manifest.py),是给已经装上 -的应用的;发布页面向从网页来下载的人。 +应用的英文更新说明也取这份摘要。tag 注解里的中文说明和英文摘要一起写进 +latest.json(见 manifest.py)。 说明文件写坏了(有中文、有一级标题、是空的)就不写正文 —— 发版流水线在这一步 停下,比发出去再改好。CI 在每个 PR 上把 `release-notes/` 下的每一份都过一遍 @@ -68,7 +68,7 @@ def summary(version: str, notes_dir: pathlib.Path = NOTES_DIR) -> str | None: text = path.read_text(encoding="utf-8").strip() name = f"release-notes/{path.name}" if not text: - raise NotesError(f"{name} 是空的:没有要说的就删掉这个文件") + raise NotesError(f"{name} 是空的:请填写英文发布说明") for n, line in enumerate(text.splitlines(), 1): if CJK.search(line): raise NotesError( diff --git a/scripts/release_notes_test.py b/scripts/release_notes_test.py index 4ca6d034..eff480a7 100755 --- a/scripts/release_notes_test.py +++ b/scripts/release_notes_test.py @@ -164,6 +164,27 @@ def test_the_portable_build_has_its_own_keys(self): self.assertEqual(manifest.PLATFORMS["windows-x86_64-portable"], "-windows-x64-portable.zip") self.assertEqual(manifest.PLATFORMS["windows-aarch64-portable"], "-windows-arm64-portable.zip") + def test_update_notes_keep_the_legacy_field_and_add_english(self): + d = notes_dir(self, { + "tag.txt": " \n- 修复路由\n", + "2026.9.16.md": "\n- Fixed routing\n", + }) + self.assertEqual( + manifest.update_notes("2026.9.16", d / "tag.txt", d), + {"notes": "- 修复路由", "notes_en": "- Fixed routing"}, + ) + + def test_publishing_requires_both_summaries_for_the_same_release(self): + d = notes_dir(self, { + "tag.txt": "修复路由", + "empty-tag.txt": "\n ", + "2026.9.15.md": "Previous release", + }) + with self.assertRaisesRegex(rn.NotesError, r"release-notes/2026\.9\.16\.md"): + manifest.update_notes("2026.9.16", d / "tag.txt", d) + with self.assertRaisesRegex(rn.NotesError, "缺少中文发布说明"): + manifest.update_notes("2026.9.15", d / "empty-tag.txt", d) + class Summary(unittest.TestCase): def test_absent_is_none(self): diff --git a/scripts/shots/boot.ts b/scripts/shots/boot.ts index 2889140d..4be4a964 100644 --- a/scripts/shots/boot.ts +++ b/scripts/shots/boot.ts @@ -6,7 +6,9 @@ // 文案写成「这台电脑」。所以这里不 import 任何东西。 const q = new URLSearchParams(location.search); -const lang = q.get("lang") === "en" ? "en" : "zh"; +const wanted = q.get("lang"); +export const lang = wanted === "en" || wanted === "ja" || wanted === "zh-Hant" || wanted === "ko" || wanted === "es" + ? wanted : "zh"; window.__TW_LANG__ = lang; window.__TW_PLATFORM__ = "macos"; @@ -14,7 +16,7 @@ window.__TW_PLATFORM__ = "macos"; // 不设它,侧栏按实色画,和别的平台一样 // 热启动:core 已经在跑,窗口取好首屏的数才露面,没有启动画面 (window as { __TW_WARM__?: boolean }).__TW_WARM__ = true; -document.documentElement.lang = lang === "en" ? "en" : "zh-CN"; +document.documentElement.lang = lang === "zh" ? "zh-CN" : lang; /** * 定住的时钟:2026-09-25(周五)16:42:07,**本地时间**。 diff --git a/scripts/shots/mock/config.ts b/scripts/shots/mock/config.ts index b9a2ad8a..a809b935 100644 --- a/scripts/shots/mock/config.ts +++ b/scripts/shots/mock/config.ts @@ -36,7 +36,7 @@ import REQUESTS from "../core/requests.json"; import { P } from "./params"; import { HOUR, MIN, NOW, clone, msg } from "./util"; -const en = P.lang === "en"; +const en = P.lang !== "zh" && P.lang !== "zh-Hant"; /** 一个类型「放宽」之后的样子:`"free" | "per-token"` 这类取值放宽成 string,结构不变 */ type Widen = T extends string diff --git a/scripts/shots/mock/params.ts b/scripts/shots/mock/params.ts index 92240d21..744a9ab3 100644 --- a/scripts/shots/mock/params.ts +++ b/scripts/shots/mock/params.ts @@ -1,11 +1,12 @@ // 这一张图是哪个场景、哪种语言。mock 的数据按它摆(连着远程时列表里当前的是哪一条……) import { sceneOf } from "../scenes"; +import { lang } from "../boot"; const q = new URLSearchParams(location.search); export const P = { scene: sceneOf(q.get("scene")), - lang: (q.get("lang") === "en" ? "en" : "zh") as "zh" | "en", + lang, /** 打开哪一页 */ page: sceneOf(q.get("scene"))?.page ?? null, /** 连着远程 core(`homelab`) */ diff --git a/scripts/shots/mock/util.ts b/scripts/shots/mock/util.ts index 1dc3ac44..7315791e 100644 --- a/scripts/shots/mock/util.ts +++ b/scripts/shots/mock/util.ts @@ -29,7 +29,7 @@ export function rng(seed: number) { export const msg = (code: string, text: string, args: Record = {}): Msg => ({ code, args, text }); /** 本来就是一句话的示例数据(用户起的名字、对话内容):按界面语言二选一 */ -export const L = (zh: A, en: A): A => (P.lang === "en" ? en : zh); +export const L = (zh: A, en: A): A => (P.lang === "zh" || P.lang === "zh-Hant" ? zh : en); export const clone = (x: T): T => structuredClone(x); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 2c0017bd..55f3417b 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4950,7 +4950,7 @@ dependencies = [ [[package]] name = "thinkwatch-lite" -version = "2026.11.20" +version = "2026.11.22" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index e5ccc5d4..a9d4a34b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "thinkwatch-lite" -version = "2026.11.20" +version = "2026.11.22" edition = "2024" # **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust # 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和 diff --git a/src-tauri/src/autostart/linux.rs b/src-tauri/src/autostart/linux.rs index b87e89d6..9a9e43ce 100644 --- a/src-tauri/src/autostart/linux.rs +++ b/src-tauri/src/autostart/linux.rs @@ -79,13 +79,15 @@ impl Autostart { format!("路径中含有 % 时无法开机启动:{program}。请将应用移到不含 % 的目录。"), format!( "Launch at login does not work when the path contains %: {program}. Move the app to a directory without % in its path." - ) + ); + format!("路徑中含有 % 時無法開機啟動:{program}。請將應用移到不含 % 的目錄。"), ))); } if self.file.as_os_str().is_empty() || !self.file.is_absolute() { return Err(io::Error::other(tr!( "未能确定自启目录(HOME 未设置)", - "The autostart directory could not be determined (HOME is not set)" + "The autostart directory could not be determined (HOME is not set)"; + "未能確定自啟目錄(HOME 未設定)", ))); } let dir = self.file.parent().expect("the entry is inside a directory"); @@ -94,7 +96,8 @@ impl Autostart { e.kind(), tr!( format!("无法创建目录 {}:{e}", dir.display()), - format!("The directory {} could not be created: {e}", dir.display()) + format!("The directory {} could not be created: {e}", dir.display()); + format!("無法建立目錄 {}:{e}", dir.display()), ), ) })?; @@ -189,7 +192,8 @@ fn program( .ok_or_else(|| { tr!( "未能确定应用程序的位置", - "The location of the application could not be determined" + "The location of the application could not be determined"; + "未能確定應用程式的位置", ) .to_string() })?; @@ -199,7 +203,8 @@ fn program( format!( "The application path is not valid UTF-8: {}", p.to_string_lossy() - ) + ); + format!("應用程式路徑不是有效的 UTF-8:{}", p.to_string_lossy()), ) }) } diff --git a/src-tauri/src/chatgpt.rs b/src-tauri/src/chatgpt.rs index f7dbe131..31c025cb 100644 --- a/src-tauri/src/chatgpt.rs +++ b/src-tauri/src/chatgpt.rs @@ -137,7 +137,8 @@ fn pending(id: &str, get: impl Fn(&Pending) -> Option) -> Result Result<(), String> if !is_web_page(url) { return Err(tr!( format!("登录页地址不是 https 网页:{url}"), - format!("The sign-in address is not an https web page: {url}") + format!("The sign-in address is not an https web page: {url}"); + format!("登入頁地址不是 https 網頁:{url}"), ) .to_string()); } app.opener().open_url(url, None::<&str>).map_err(|e| { tr!( format!("无法打开浏览器:{e}"), - format!("The browser could not be opened: {e}") + format!("The browser could not be opened: {e}"); + format!("無法開啟瀏覽器:{e}"), ) }) } diff --git a/src-tauri/src/cleanup.rs b/src-tauri/src/cleanup.rs index 838675e7..7c3d1dca 100644 --- a/src-tauri/src/cleanup.rs +++ b/src-tauri/src/cleanup.rs @@ -71,7 +71,8 @@ fn run(req: &Request) -> Vec { format!("未能确定程序位置,注册项未清理({e})"), format!( "The program location could not be determined, so its registry entries were left in place ({e})" - ) + ); + format!("未能確定程式位置,註冊項未清理({e})"), ))), } // 卸载程序接着要删 twcore.exe,数据目录也要等它放手:不等它走,那个文件删不掉、 diff --git a/src-tauri/src/clients/network.rs b/src-tauri/src/clients/network.rs index 0e76203e..bf7a6009 100644 --- a/src-tauri/src/clients/network.rs +++ b/src-tauri/src/clients/network.rs @@ -532,8 +532,13 @@ async fn release_at(control: Option<&ControlClient>, owner: &str, path: &Path) - // retain baseline/expected separately so a later explicit adoption can clean up. save_at(path, &j)?; if let (Some(expected), Some(_)) = (&j.expected, &j.baseline) { - let control = control - .ok_or_else(|| failed(tr!("本机网关不可用", "The local gateway is unavailable")))?; + let control = control.ok_or_else(|| { + failed(tr!( + "本机网关不可用", + "The local gateway is unavailable"; + "本機閘道器不可用", + )) + })?; let ov = control .call::(&[], &()) .await @@ -651,9 +656,16 @@ pub fn watch(handle: &tauri::AppHandle, notices: std::sync::Arc Result<(), String> { } else { Err(tr!( format!("无法在访达中显示 {path}"), - format!("{path} could not be shown in Finder") + format!("{path} could not be shown in Finder"); + format!("無法在訪達中顯示 {path}"), ) .to_string()) } @@ -41,7 +42,8 @@ pub fn reveal(path: &str) -> Result<(), String> { .map_err(|e| { tr!( format!("无法在文件资源管理器中显示 {path}:{e}"), - format!("{path} could not be shown in File Explorer: {e}") + format!("{path} could not be shown in File Explorer: {e}"); + format!("無法在檔案資源管理器中顯示 {path}:{e}"), ) .to_string() }) @@ -73,7 +75,8 @@ fn absolute(path: &str) -> Result<(), String> { } else { Err(tr!( format!("配置文件的路径不是绝对路径:{path}"), - format!("The configuration file path is not absolute: {path}") + format!("The configuration file path is not absolute: {path}"); + format!("配置檔案的路徑不是絕對路徑:{path}"), ) .to_string()) } @@ -109,7 +112,8 @@ pub fn reveal(path: &str) -> Result<(), String> { .map_err(|e| { tr!( format!("无法在文件管理器中显示 {path}:{e}"), - format!("{path} could not be shown in the file manager: {e}") + format!("{path} could not be shown in the file manager: {e}"); + format!("無法在檔案管理器中顯示 {path}:{e}"), ) .to_string() }) @@ -119,7 +123,8 @@ pub fn reveal(path: &str) -> Result<(), String> { pub fn reveal(path: &str) -> Result<(), String> { Err(tr!( format!("这个平台上还不能打开文件管理器:{path}"), - format!("Opening a file manager is not supported on this platform yet: {path}") + format!("Opening a file manager is not supported on this platform yet: {path}"); + format!("這個平臺上還不能開啟檔案管理器:{path}"), ) .to_string()) } diff --git a/src-tauri/src/connection/connector.rs b/src-tauri/src/connection/connector.rs index 36515fa5..fe108e79 100644 --- a/src-tauri/src/connection/connector.rs +++ b/src-tauri/src/connection/connector.rs @@ -82,21 +82,30 @@ impl std::fmt::Display for ConnectError { ConnectError::Unreachable { addr } => { tr!( format!("无法连接到 {addr}"), - format!("Cannot connect to {addr}") + format!("Cannot connect to {addr}"); + format!("無法連線到 {addr}"), ) } ConnectError::Closed { addr } => tr!( format!("{addr} 关闭了连接"), - format!("{addr} closed the connection") + format!("{addr} closed the connection"); + format!("{addr} 關閉了連線"), ), - ConnectError::WrongKey => tr!("密钥不正确", "The key is not correct").into(), + ConnectError::WrongKey => tr!( + "密钥不正确", + "The key is not correct"; + "金鑰不正確", + ) + .into(), ConnectError::VersionMismatch { ours, theirs } => tr!( format!("版本不一致:服务器 core {theirs},本应用需要 {ours}"), - format!("Version mismatch: the server runs core {theirs}; this app needs {ours}") + format!("Version mismatch: the server runs core {theirs}; this app needs {ours}"); + format!("版本不一致:伺服器 core {theirs},本應用需要 {ours}"), ), ConnectError::Timeout { addr } => tr!( format!("连接 {addr} 超时"), - format!("Connecting to {addr} timed out") + format!("Connecting to {addr} timed out"); + format!("連線 {addr} 超時"), ), }; f.write_str(&s) @@ -232,7 +241,8 @@ fn link_error(e: tw_link::LinkError, addr: &str) -> ConnectError { let with_proto = |v: &str, p: u32| -> String { tr!( format!("{v}(控制面协议 {p})"), - format!("{v} (control protocol {p})") + format!("{v} (control protocol {p})"); + format!("{v}(控制面協議 {p})"), ) }; if peer_version == REQUIRED_CORE { diff --git a/src-tauri/src/connection/mod.rs b/src-tauri/src/connection/mod.rs index 4db73b16..5f55bee4 100644 --- a/src-tauri/src/connection/mod.rs +++ b/src-tauri/src/connection/mod.rs @@ -745,7 +745,11 @@ pub fn delete_connection(app: tauri::AppHandle, id: String) -> Out { if id == LOCAL || st.link.current().id() == id { return Err(CmdError::plain(tr!( "当前连接不能删除,请先切换到其他连接。", - "The current connection cannot be deleted. Switch to another connection first." + "The current connection cannot be deleted. Switch to another connection first.", + "現在の接続は削除できません。先に別の接続に切り替えてください。"; + "當前連線不能刪除,請先切換到其他連線。", + "The current connection cannot be deleted. Switch to another connection first.", + "La conexión actual no se puede borrar. Cambiar a otra conexión primero.", ))); } store::update(&data_dir(), |c| { @@ -799,14 +803,22 @@ pub fn retry_connection(state: tauri::State<'_, AppState>) { fn saving(e: anyhow::Error) -> CmdError { CmdError::plain(tr!( format!("无法保存连接列表:{e:#}"), - format!("The connection list could not be saved: {e:#}") + format!("The connection list could not be saved: {e:#}"), + format!("接続一覧を保存できませんでした:{e:#}"); + format!("無法儲存連線列表:{e:#}"), + format!("The connection list could not be saved: {e:#}"), + format!("La lista de conexiones no se pudo guardar: {e:#}"), )) } fn key_error(e: &anyhow::Error) -> CmdError { CmdError::plain(tr!( format!("无法读写保存的密钥:{e:#}"), - format!("The saved key could not be read or written: {e:#}") + format!("The saved key could not be read or written: {e:#}"), + format!("保存されたキーを読み書きできませんでした:{e:#}"); + format!("無法讀寫儲存的金鑰:{e:#}"), + format!("The saved key could not be read or written: {e:#}"), + format!("La llave guardada no se pudo leer ni escribir: {e:#}"), )) } @@ -822,7 +834,14 @@ pub fn show_picker(app: &tauri::AppHandle, why: launch::Why) -> tauri::Result<() launch::Why::Unfinished => "unfinished", }; let b = tauri::WebviewWindowBuilder::new(app, PICKER_WINDOW, tauri::WebviewUrl::default()) - .title(tr!("选择连接", "Choose a Connection")) + .title(tr!( + "选择连接", + "Choose a Connection", + "接続を選択"; + "選擇連線", + "연결 선택", + "Elegir una conexión", + )) .initialization_script(format!( "{} window.__TW_PICK__ = {:?};", crate::i18n::init_script(), diff --git a/src-tauri/src/connection/store.rs b/src-tauri/src/connection/store.rs index 00c9ceb4..d5c2fb53 100644 --- a/src-tauri/src/connection/store.rs +++ b/src-tauri/src/connection/store.rs @@ -27,7 +27,23 @@ pub fn local_name() -> &'static str { "This Mac" } else { "This computer" - } + }, + if cfg!(target_os = "macos") { + "この Mac" + } else { + "この端末" + }; + "本機", + if cfg!(target_os = "macos") { + "이 Mac" + } else { + "이 컴퓨터" + }, + if cfg!(target_os = "macos") { + "Este Mac" + } else { + "Este equipo" + }, ) } diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 83bb98f4..5836921b 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -49,7 +49,8 @@ fn not_running(e: &dyn std::fmt::Display) -> anyhow::Error { tracing::debug!("控制面连不上:{e}"); anyhow::anyhow!(tr!( "core 未在运行,或尚未启动完成", - "core is not running, or has not finished starting" + "core is not running, or has not finished starting", + "core が停止しているか、起動が完了していません" )) } @@ -69,7 +70,8 @@ fn local_key(config: &Path) -> Result { tracing::warn!("本机配置里的控制面钥匙读不出来:{other}"); anyhow::anyhow!(tr!( "配置文件中的控制面密钥(listen.control.key)无效", - "The control key in the config file (listen.control.key) is not valid" + "The control key in the config file (listen.control.key) is not valid", + "設定ファイルの制御キー(listen.control.key)が無効です" )) } }) @@ -134,7 +136,8 @@ fn link_failed(e: tw_link::LinkError) -> anyhow::Error { match e { LinkError::WrongKey => anyhow::anyhow!(tr!( "控制面密钥不匹配:core 拒绝了配置文件中的密钥", - "The control key does not match: core rejected the key in the config file" + "The control key does not match: core rejected the key in the config file", + "制御キーが一致しません。core が設定ファイルのキーを拒否しました" )), LinkError::VersionMismatch { ours, @@ -174,7 +177,8 @@ fn refused(status: hyper::StatusCode, body: &[u8]) -> anyhow::Error { Ok(m) => Refused(m).into(), Err(_) => anyhow::anyhow!(tr!( format!("控制面返回 {status}"), - format!("The control plane returned {status}") + format!("The control plane returned {status}"), + format!("制御インターフェイスが {status} を返しました") )), } } diff --git a/src-tauri/src/core_text.rs b/src-tauri/src/core_text.rs index 606309fb..6c26e266 100644 --- a/src-tauri/src/core_text.rs +++ b/src-tauri/src/core_text.rs @@ -1,7 +1,6 @@ -//! core 的消息按码说中文 —— 系统通知、菜单栏用。 +//! 系统通知和菜单栏使用的 core 消息翻译。 //! -//! **表只有一张,在 `src/i18n/core.zh.json`**,界面和这里读的是同一份(这里 -//! `include_str!`)。以前这边没有表,通知只好把 core 的英文原句嵌进中文句子里。 +//! 界面和 Rust 共用 `src/i18n/core.*.json`。 //! 句子的写法(参数、查词表、可有可无的一段)和界面 `src/i18n/template.ts` 是 //! 同一套,两边跑同一份用例(`src/i18n/core.zh.cases.json`)。 //! @@ -14,11 +13,14 @@ use std::sync::OnceLock; use serde::Deserialize; use tw_api::Msg; +use crate::i18n::Lang; + type Tables = HashMap>; #[derive(Deserialize)] struct Table { tables: Tables, + #[serde(default)] contexts: Vec, messages: HashMap, } @@ -28,25 +30,96 @@ struct Table { struct Context { arg: String, en: String, - zh: String, + #[serde(flatten)] + copy: HashMap, } const SOURCE: &str = include_str!("../../src/i18n/core.zh.json"); +#[derive(Deserialize)] +struct GuardCopy { + rules: HashMap, + // Only needed to check coverage against the pinned Core catalog. + #[cfg(test)] + kinds: HashMap, +} + +#[derive(Deserialize)] +struct RuleCopy { + name: String, + why: Option, + #[cfg(test)] + about: Option, +} + +fn guards(lang: Lang) -> Option<&'static HashMap> { + static ZH: OnceLock> = OnceLock::new(); + static HANT: OnceLock> = OnceLock::new(); + let (cell, source) = match lang { + Lang::Zh => (&ZH, include_str!("../../src/i18n/guard.zh.json")), + Lang::ZhHant => (&HANT, include_str!("../../src/i18n/guard.zh-Hant.json")), + _ => return None, + }; + Some(cell.get_or_init(|| serde_json::from_str(source).expect("guard catalog is valid"))) +} + +pub fn rule_name(lang: Lang, guard: &str, id: &str) -> Option<&'static str> { + Some(&guards(lang)?.get(guard)?.rules.get(id)?.name) +} + fn table() -> &'static Table { - static T: OnceLock = OnceLock::new(); - // 表随代码一起编进来,读不出来是开发时的错,测试会先挂 - T.get_or_init(|| serde_json::from_str(SOURCE).expect("core.zh.json 读不出来")) + catalog(Lang::Zh).expect("Chinese catalog is available") +} + +fn catalog(lang: Lang) -> Option<&'static Table> { + static ZH: OnceLock
= OnceLock::new(); + static HANT: OnceLock
= OnceLock::new(); + static JA: OnceLock
= OnceLock::new(); + static KO: OnceLock
= OnceLock::new(); + static ES: OnceLock
= OnceLock::new(); + let (cell, source) = match lang { + Lang::Zh => (&ZH, SOURCE), + Lang::ZhHant => (&HANT, include_str!("../../src/i18n/core.zh-Hant.json")), + Lang::Ja => (&JA, include_str!("../../src/i18n/core.ja.json")), + Lang::Ko => (&KO, include_str!("../../src/i18n/core.ko.json")), + Lang::Es => (&ES, include_str!("../../src/i18n/core.es.json")), + Lang::En => return None, + }; + Some(cell.get_or_init(|| { + let mut table: Table = serde_json::from_str(source).expect("Core message catalog is valid"); + let Some(guards) = guards(lang) else { + return table; + }; + for (key, guard) in [("scan_rule", "inspect_tools"), ("content_rule", "content")] { + table.tables.insert( + key.into(), + guards[guard] + .rules + .iter() + .map(|(id, copy)| (id.clone(), copy.name.clone())) + .collect(), + ); + } + table.tables.insert( + "rule_why".into(), + guards["inspect_tools"] + .rules + .iter() + .filter_map(|(id, copy)| Some((id.clone(), copy.why.clone()?))) + .collect(), + ); + table + })) } /// 一条 core 消息在当前语言下怎么说 pub fn text(m: &Msg) -> String { - tr!(zh(m).unwrap_or_else(|| m.text.clone()), m.text.clone()) + localized(m, crate::i18n::current()).unwrap_or_else(|| m.text.clone()) } /// 词表里的一项(`guard`、`content_rule`…),中文。表或项不在是 `None` -pub fn table_zh(table: &str, key: &str) -> Option { - self::table().tables.get(table)?.get(key).cloned() +pub fn table_word(lang: Lang, table: &str, key: &str) -> Option { + catalog(lang)?.tables.get(table)?.get(key).cloned() } /// 同 [`text`],去掉句末的句号:后面还要接自己的一句时用 @@ -62,25 +135,30 @@ pub fn clause(m: &Msg) -> String { /// /// **插件名按中文说**:`{plugin}` 是默认插件 core 发的英文名时,换成它的中文名(和插件页上 /// 一样,见 `plugins::defaults::name_in`)。消息里只有名字,按名字认 -pub fn zh(m: &Msg) -> Option { - let t = table(); +#[cfg(test)] +fn zh(m: &Msg) -> Option { + localized(m, Lang::Zh) +} + +fn localized(m: &Msg, lang: Lang) -> Option { + let t = catalog(lang)?; if m.code.starts_with("//") { return None; } let say = t.messages.get(&m.code)?; - // 填进中文句子的参数。认场合比的是英文原句,那边照旧用原样的参数 - let mut zh_args = m.args.clone(); - if let Some(p) = zh_args.get_mut("plugin") { - *p = crate::plugins::defaults::name_in(crate::i18n::Lang::Zh, None, p); + // 识别场合时仍使用英文原句及其参数。 + let mut local_args = m.args.clone(); + if let Some(p) = local_args.get_mut("plugin") { + *p = crate::plugins::defaults::name_in(lang, None, p); } let mut leads = String::new(); let mut rest = m.text.as_str(); 'peel: loop { - for c in &t.contexts { + for c in &table().contexts { if !m.args.contains_key(&c.arg) { continue; } - let Some(en) = render(&c.en, &m.args, &t.tables) else { + let Some(en) = render(&c.en, &m.args, &table().tables) else { continue; }; let Some(after) = rest @@ -89,14 +167,15 @@ pub fn zh(m: &Msg) -> Option { else { continue; }; - leads.push_str(&render(&c.zh, &zh_args, &t.tables)?); + let copy = c.copy.get(lang.as_str())?; + leads.push_str(&render(copy, &local_args, &t.tables)?); leads.push(':'); rest = after; continue 'peel; } break; } - Some(leads + &render(say, &zh_args, &t.tables)?) + Some(leads + &render(say, &local_args, &t.tables)?) } // ------------------------------------------------------------ 写法 @@ -311,41 +390,70 @@ fn render(src: &str, args: &BTreeMap, tables: &Tables) -> Option mod tests { use super::*; - /// 消息里规则名、理由的中文(`{rule:scan_rule}`、`{rule:rule_why}`、`{rule:content_rule}`) - /// 查的是表里的这三张;**规则的中文本身由 core 写**(tw-guard 的规则目录,安全页显示的 - /// 就是它)。这里钉着两边一字不差:core 改了措辞,消息里不能还是旧的那句 #[test] - fn rule_tables_match_the_core_catalog() { - let t = &table().tables; - let f = tw_guard::tools::rules::builtin(); - let tools: Vec<_> = f.injection.iter().chain(&f.dangerous).collect(); - let names: HashMap = tools - .iter() - .map(|r| (r.id.clone(), r.name_zh.clone())) - .collect(); - let whys: HashMap = tools - .iter() - .map(|r| (r.id.clone(), r.why_zh.clone())) - .collect(); - let content: HashMap = tw_guard::content::builtins() - .iter() - .map(|b| (b.id.clone(), b.name_zh.clone())) - .collect(); - assert_eq!(t["scan_rule"], names); - assert_eq!(t["rule_why"], whys); - assert_eq!(t["content_rule"], content); + fn every_pinned_core_rule_and_group_has_client_copy() { + let view = tw_guard::view::detail(&Default::default()); + for (guard, detail) in [ + ("redact", view.redact), + ("inspect_tools", view.inspect_tools), + ("content", view.content), + ] { + let copy = &guards(Lang::Zh).unwrap()[guard]; + for rule in &detail.rules { + let r = copy + .rules + .get(&rule.id) + .unwrap_or_else(|| panic!("{guard}: {}", rule.id)); + assert!(!r.name.is_empty(), "{guard}: {}", rule.id); + assert!( + rule.why.is_empty() || r.why.as_ref().is_some_and(|s| !s.is_empty()), + "{guard}: {} why", + rule.id + ); + if !rule.about.is_empty() + && !matches!( + rule.matcher, + tw_guard::view::Matcher::Prefix { .. } + | tw_guard::view::Matcher::Prefixes { .. } + ) + { + assert!( + r.about.as_ref().is_some_and(|s| !s.is_empty()), + "{guard}: {} about", + rule.id + ); + } + } + for kind in &detail.kinds { + assert!( + copy.kinds.get(&kind.slug).is_some_and(|k| !k.is_empty()), + "{guard}: {}", + kind.slug + ); + } + } + for rule in &tw_guard::tools::rules::builtin().injection { + assert!( + rule_name(Lang::Zh, "inspect_tools", &rule.id).is_some(), + "{}", + rule.id + ); + } } /// 表里每一句、每一层场合都写得对:写坏了的那句会悄悄退回英文 #[test] fn every_template_in_the_table_parses() { - let t = table(); - for (code, s) in &t.messages { - compile(s).unwrap_or_else(|e| panic!("{code}: {e}")); + for lang in [Lang::Zh, Lang::ZhHant, Lang::Ja, Lang::Ko, Lang::Es] { + for (code, s) in &catalog(lang).unwrap().messages { + compile(s).unwrap_or_else(|e| panic!("{lang:?} {code}: {e}")); + } } - for c in &t.contexts { + for c in &table().contexts { compile(&c.en).unwrap(); - compile(&c.zh).unwrap(); + for copy in c.copy.values() { + compile(copy).unwrap(); + } } } @@ -399,4 +507,27 @@ mod tests { ); } } + + #[test] + fn japanese_renders_a_common_error_with_context_and_falls_back_to_english() { + let mut message = Msg { + code: "gw.oauth.unreachable".into(), + text: "the credential of upstream `example`: Cannot reach https://example.com: timeout" + .into(), + args: BTreeMap::from([ + ("upstream".into(), "example".into()), + ("endpoint".into(), "https://example.com".into()), + ("detail".into(), "timeout".into()), + ]), + }; + crate::i18n::with_lang(Lang::Ja, || { + assert_eq!( + text(&message), + "アップストリーム「example」の認証情報:トークンエンドポイント https://example.com に接続できません:timeout" + ); + message.code = "l1.tcp.refused".into(); + message.text = "Connection refused".into(); + assert_eq!(text(&message), "Connection refused"); + }); + } } diff --git a/src-tauri/src/desktop_entry.rs b/src-tauri/src/desktop_entry.rs index 4eb40931..2cd81f68 100644 --- a/src-tauri/src/desktop_entry.rs +++ b/src-tauri/src/desktop_entry.rs @@ -235,7 +235,8 @@ impl Files { Err(e) if e.kind() == io::ErrorKind::NotFound => {} Err(e) => log.push(UninstallStep::failed(tr!( format!("未能删除 {}({e})", path.display()), - format!("{} could not be deleted ({e})", path.display()) + format!("{} could not be deleted ({e})", path.display()); + format!("未能刪除 {}({e})", path.display()), ))), } } @@ -246,7 +247,8 @@ impl Files { if log.is_empty() { log.push(UninstallStep::done(tr!( "已移除应用菜单中的条目", - "The application menu entry was removed" + "The application menu entry was removed"; + "已移除應用選單中的條目", ))); } } diff --git a/src-tauri/src/diagnostics.rs b/src-tauri/src/diagnostics.rs index 0280abf4..3dcb5745 100644 --- a/src-tauri/src/diagnostics.rs +++ b/src-tauri/src/diagnostics.rs @@ -22,7 +22,8 @@ pub async fn save_diagnostics(state: tauri::State<'_, AppState>) -> Out std::fs::create_dir_all(&dir).map_err(|e| { tr!( format!("无法创建目录 {}:{e}", dir.display()), - format!("The directory {} could not be created: {e}", dir.display()) + format!("The directory {} could not be created: {e}", dir.display()); + format!("無法建立目錄 {}:{e}", dir.display()), ) })?; let at = std::time::SystemTime::now() @@ -32,12 +33,14 @@ pub async fn save_diagnostics(state: tauri::State<'_, AppState>) -> Out // 文件名界面上看得见(「已生成:…」),所以也跟着语言走 let path = dir.join(tr!( format!("诊断包-{at}.md"), - format!("diagnostics-{at}.md") + format!("diagnostics-{at}.md"); + format!("診斷包-{at}.md"), )); write_private(&path, text.as_bytes()).map_err(|e| { tr!( format!("无法写入文件 {}:{e}", path.display()), - format!("The file {} could not be written: {e}", path.display()) + format!("The file {} could not be written: {e}", path.display()); + format!("無法寫入檔案 {}:{e}", path.display()), ) })?; Ok(path.display().to_string()) diff --git a/src-tauri/src/dialog.rs b/src-tauri/src/dialog.rs index f87c83e3..a47c1df2 100644 --- a/src-tauri/src/dialog.rs +++ b/src-tauri/src/dialog.rs @@ -206,7 +206,14 @@ mod imp { let title_w = wide(title); let instruction_w = wide(instruction); let content_w = wide(content); - let cancel = wide(tr!("取消", "Cancel")); + let cancel = wide(tr!( + "取消", + "Cancel", + "キャンセル"; + "取消", + "취소", + "Cancelar", + )); let button = TASKDIALOG_BUTTON { nButtonID: WAIT_BUTTON, pszButtonText: cancel.as_ptr(), diff --git a/src-tauri/src/dmg.rs b/src-tauri/src/dmg.rs index 4b3a8d0d..e04941c6 100644 --- a/src-tauri/src/dmg.rs +++ b/src-tauri/src/dmg.rs @@ -90,10 +90,16 @@ fn find_app(volume: &Path) -> Result { .collect(); match apps.as_slice() { [app] => Ok(app.clone()), - [] => Err(tr!("更新包里没有应用", "The update contains no app").into()), + [] => Err(tr!( + "更新包里没有应用", + "The update contains no app"; + "更新包裡沒有應用", + ) + .into()), _ => Err(tr!( "更新包里有不止一个应用", - "The update contains more than one app" + "The update contains more than one app"; + "更新包裡有不止一個應用", ) .into()), } diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs index 136d5fc1..bed1f97a 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -72,7 +72,8 @@ pub async fn save_export( let picked = rx.await.map_err(|_| { tr!( "无法打开存储对话框。", - "The save dialog could not be opened." + "The save dialog could not be opened."; + "無法開啟儲存對話方塊。", ) })?; let Some(picked) = picked else { @@ -81,13 +82,15 @@ pub async fn save_export( let path = picked.into_path().map_err(|e| { tr!( format!("无法使用所选的位置:{e}"), - format!("The chosen location cannot be used: {e}") + format!("The chosen location cannot be used: {e}"); + format!("無法使用所選的位置:{e}"), ) })?; crate::atomic_file::write(&path, &bytes).map_err(|e| { tr!( format!("无法写入文件 {}:{e}", path.display()), - format!("The file {} could not be written: {e}", path.display()) + format!("The file {} could not be written: {e}", path.display()); + format!("無法寫入檔案 {}:{e}", path.display()), ) })?; Ok(Some(path.display().to_string())) @@ -100,25 +103,29 @@ pub fn read_pack(path: &Path) -> Result { let meta = std::fs::metadata(path).map_err(|e| { tr!( format!("无法读取 {shown}:{e}"), - format!("{shown} could not be read: {e}") + format!("{shown} could not be read: {e}"); + format!("無法讀取 {shown}:{e}"), ) })?; if !meta.is_file() { return Err(tr!( format!("{shown} 不是文件。"), - format!("{shown} is not a file.") + format!("{shown} is not a file."); + format!("{shown} 不是檔案。"), )); } if meta.len() > MAX_PACK { return Err(tr!( format!("{shown} 超过 16 MiB,不是配置包。"), - format!("{shown} is larger than 16 MiB and is not a config pack.") + format!("{shown} is larger than 16 MiB and is not a config pack."); + format!("{shown} 超過 16 MiB,不是配置包。"), )); } let bytes = std::fs::read(path).map_err(|e| { tr!( format!("无法读取 {shown}:{e}"), - format!("{shown} could not be read: {e}") + format!("{shown} could not be read: {e}"); + format!("無法讀取 {shown}:{e}"), ) })?; let name = path @@ -158,7 +165,8 @@ pub async fn open_import( let picked = rx.await.map_err(|_| { tr!( "无法打开「打开」对话框。", - "The open dialog could not be opened." + "The open dialog could not be opened."; + "無法開啟「開啟」對話方塊。", ) })?; let Some(picked) = picked else { @@ -167,7 +175,8 @@ pub async fn open_import( let path = picked.into_path().map_err(|e| { tr!( format!("无法使用所选的文件:{e}"), - format!("The chosen file cannot be used: {e}") + format!("The chosen file cannot be used: {e}"); + format!("無法使用所選的檔案:{e}"), ) })?; tokio::task::spawn_blocking(move || read_pack(&path)) diff --git a/src-tauri/src/i18n.rs b/src-tauri/src/i18n.rs index 085bf166..7554dc1e 100644 --- a/src-tauri/src/i18n.rs +++ b/src-tauri/src/i18n.rs @@ -1,7 +1,7 @@ -//! 界面语言:简体中文或英文。 +//! 选择 Lite 的界面语言,并注入各窗口。 //! //! **语言由这里决定,界面只是照着用。**设置里选过的优先,没选过就看系统 -//! 的首选语言:中文(`zh-*`)用中文,其余一律英文。托盘菜单和系统通知 +//! 的首选语言列表,找不到支持的语言时用英文。托盘菜单和系统通知 //! 在没有窗口的时候也要说话,所以这个判断不能放在网页里。 //! //! 网页拿到的是加载之前注入的 `window.__TW_LANG__`(见 [`init_script`]), @@ -9,35 +9,36 @@ //! //! **core 不做翻译,只说英文。**它发来的每一句给人看的话都是一条 //! `tw_api::Msg`:一个稳定的码、填进句子的参数,以及英文原句。界面拿码去 -//! `src/i18n/core.i18n.ts` 里找中文;码不在表里就显示那句英文 —— 一句英文 -//! 总好过一个码。 +//! `src/i18n/core.i18n.ts` 里找翻译;码不在表里就显示英文原句。 //! -//! 这个模块只管 Rust 这一侧(托盘、系统通知)自己要说的话。core 的码在 -//! 这里只翻一处:通知里「卡在哪一步」那几个词(见 `notices::rules`)。 +//! Rust 自己的文案用 `tr!`,Core 的消息交给 `core_text`。 use std::sync::atomic::{AtomicU8, Ordering}; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "lowercase")] +#[repr(u8)] pub enum Lang { #[default] Zh, En, + Ja, + #[serde(rename = "zh-Hant")] + ZhHant, + Ko, + Es, } impl Lang { - fn code(self) -> u8 { - match self { - Lang::Zh => 0, - Lang::En => 1, - } - } - /// 网页和设置文件里用的写法 pub fn as_str(self) -> &'static str { match self { Lang::Zh => "zh", Lang::En => "en", + Lang::Ja => "ja", + Lang::ZhHant => "zh-Hant", + Lang::Ko => "ko", + Lang::Es => "es", } } } @@ -59,6 +60,10 @@ pub fn current() -> Lang { } match CURRENT.load(Ordering::Relaxed) { 1 => Lang::En, + 2 => Lang::Ja, + 3 => Lang::ZhHant, + 4 => Lang::Ko, + 5 => Lang::Es, _ => Lang::Zh, } } @@ -73,7 +78,7 @@ pub fn with_lang(lang: Lang, f: impl FnOnce() -> R) -> R { } pub fn set(lang: Lang) { - CURRENT.store(lang.code(), Ordering::Relaxed); + CURRENT.store(lang as u8, Ordering::Relaxed); } /// 设置里的选择落到实际用哪种语言。 @@ -83,17 +88,27 @@ pub fn effective(setting: Option) -> Lang { /// 按一个语言标签(`zh-Hans-CN`、`en-US`、`zh_TW.UTF-8`)挑语言。 /// -/// **繁体也归中文。**界面只有简体一种中文,而读繁体的人读简体,比读英文 -/// 近得多。 -pub fn from_tag(tag: &str) -> Lang { +fn from_tag(tag: &str) -> Option { let tag = tag.trim().to_ascii_lowercase(); - if tag == "zh" || tag.starts_with("zh-") || tag.starts_with("zh_") { - Lang::Zh - } else { - Lang::En + let mut parts = tag.split(['-', '_', '.', '@']); + match parts.next()? { + "zh" if matches!(parts.next(), Some("hant" | "tw" | "hk" | "mo")) => Some(Lang::ZhHant), + "zh" => Some(Lang::Zh), + "en" => Some(Lang::En), + "ja" => Some(Lang::Ja), + "ko" => Some(Lang::Ko), + "es" => Some(Lang::Es), + _ => None, } } +#[cfg(any(target_os = "macos", windows, test))] +fn preferred_language>(tags: impl IntoIterator) -> Lang { + tags.into_iter() + .find_map(|tag| from_tag(tag.as_ref())) + .unwrap_or(Lang::En) +} + /// 系统的首选语言。 /// /// **读 `NSLocale.preferredLanguages`,不读网页的 `navigator.language`。** @@ -101,18 +116,16 @@ pub fn from_tag(tag: &str) -> Lang { /// 本地化 —— 中文系统上网页里拿到的也可能是 `en-US`。 pub fn system() -> Lang { #[cfg(target_os = "macos")] - { - use objc2_foundation::NSLocale; - if let Some(first) = NSLocale::preferredLanguages().firstObject() { - return from_tag(&first.to_string()); - } - } + use objc2_foundation::NSLocale; + #[cfg(target_os = "macos")] + return preferred_language( + NSLocale::preferredLanguages() + .iter() + .map(|tag| tag.to_string()), + ); #[cfg(windows)] - if let Some(tag) = user_locale() { - return from_tag(&tag); - } - // **这几个变量是 unix 的东西。**Windows 上它们通常根本不存在,上面那一支 - // 答不出来时落到这里,而那时英文是唯一诚实的默认。 + return preferred_language(user_ui_languages()); + #[cfg(not(any(target_os = "macos", windows)))] from_env(|k| std::env::var(k).ok()) } @@ -122,40 +135,46 @@ pub fn system() -> Lang { /// /// `C` / `POSIX` 是「不要本地化」的那一档:直接英文,不再往下找 —— 用户在 /// 前面那一级明确关掉了语言,不该再去 `LANG` 里翻出一个中文来。 +#[cfg(any(not(any(target_os = "macos", windows)), test))] fn from_env(var: impl Fn(&str) -> Option) -> Lang { - let Some(tag) = ["LC_ALL", "LC_MESSAGES", "LANG"] + ["LC_ALL", "LC_MESSAGES", "LANG"] .into_iter() .find_map(|k| var(k).filter(|v| !v.is_empty())) - else { - return Lang::En; - }; - // `C.UTF-8` 也是它 - let base = tag.split(['.', '@']).next().unwrap_or_default(); - if base == "C" || base == "POSIX" { - Lang::En - } else { - from_tag(&tag) - } + .and_then(|tag| from_tag(&tag)) + .unwrap_or(Lang::En) } -/// 这个用户在 Windows 里选的语言,形如 `zh-CN`。 -/// -/// **问 `GetUserDefaultLocaleName`,不看 `LANG`。**后者在 Windows 上只有装了 -/// Git Bash 之类的机器才有,而它记的是那套工具的偏好,不是用户在系统设置里 -/// 选的那个 —— 照它走的话,一台中文系统会因为装过 Git 而说英文。 +/// Windows 的显示语言和首选语言列表。 #[cfg(windows)] -fn user_locale() -> Option { - use windows_sys::Win32::Globalization::GetUserDefaultLocaleName; +fn user_ui_languages() -> Vec { + use windows_sys::Win32::Globalization::{GetUserPreferredUILanguages, MUI_LANGUAGE_NAME}; - // `LOCALE_NAME_MAX_LENGTH` 是 85,连 NUL 在内。 - let mut buf = [0u16; 85]; - // SAFETY: 缓冲区是本地数组,长度如实告知。 - let n = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) }; - if n <= 0 { - return None; + let mut count = 0; + let mut size = 0; + // SAFETY: A null buffer requests the required size in UTF-16 units. + let ok = unsafe { + GetUserPreferredUILanguages( + MUI_LANGUAGE_NAME, + &mut count, + std::ptr::null_mut(), + &mut size, + ) + }; + if ok == 0 || size == 0 { + return Vec::new(); + } + let mut buf = vec![0u16; size as usize]; + // SAFETY: buf has the capacity given in size and all output pointers are valid. + let ok = unsafe { + GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, buf.as_mut_ptr(), &mut size) + }; + if ok == 0 { + return Vec::new(); } - // 返回的长度**含结尾的 NUL**,所以要去掉一个 - Some(String::from_utf16_lossy(&buf[..(n as usize) - 1])) + buf.split(|unit| *unit == 0) + .take(count as usize) + .map(String::from_utf16_lossy) + .collect() } /// 注进每个窗口的那一行:页面加载之前就知道用哪种语言。 @@ -183,7 +202,7 @@ fn script_for(lang: Lang) -> String { ) } -/// 按当前语言二选一。 +/// 按当前语言选择文案。日文缺失时使用英文。 /// /// **两种说法写在一起。**分开放在两份词表里的话,改了一边忘了另一边是 /// 迟早的事;并排写着,漏一边在代码评审里一眼就能看见。 @@ -191,8 +210,29 @@ fn script_for(lang: Lang) -> String { macro_rules! tr { ($zh:expr, $en:expr $(,)?) => { match $crate::i18n::current() { - $crate::i18n::Lang::Zh => $zh, - $crate::i18n::Lang::En => $en, + $crate::i18n::Lang::Zh | $crate::i18n::Lang::ZhHant => $zh, + _ => $en, + } + }; + ($zh:expr, $en:expr, $ja:expr $(,)?) => { + match $crate::i18n::current() { + $crate::i18n::Lang::Zh | $crate::i18n::Lang::ZhHant => $zh, + $crate::i18n::Lang::Ja => $ja, + _ => $en, + } + }; + ($zh:expr, $en:expr $(, $ja:expr)?; $hant:expr, $ko:expr, $es:expr $(,)?) => { + match $crate::i18n::current() { + $crate::i18n::Lang::ZhHant => $hant, + $crate::i18n::Lang::Ko => $ko, + $crate::i18n::Lang::Es => $es, + _ => $crate::tr!($zh, $en $(, $ja)?), + } + }; + ($zh:expr, $en:expr $(, $ja:expr)?; $hant:expr $(,)?) => { + match $crate::i18n::current() { + $crate::i18n::Lang::ZhHant => $hant, + _ => $crate::tr!($zh, $en $(, $ja)?), } }; } @@ -202,26 +242,29 @@ mod tests { use super::*; #[test] - fn chinese_tags_pick_chinese_and_everything_else_english() { - for tag in [ - "zh", - "zh-Hans", - "zh-Hans-CN", - "zh-Hant-TW", - "zh_CN.UTF-8", - "ZH-hk", - ] { - assert_eq!(from_tag(tag), Lang::Zh, "{tag}"); + fn language_tags_and_preference_order() { + for tag in ["zh", "zh-Hans", "zh-Hans-CN", "zh_CN.UTF-8", "zh-Hans-TW"] { + assert_eq!(from_tag(tag), Some(Lang::Zh), "{tag}"); } - for tag in ["en", "en-US", "ja-JP", "fr_FR.UTF-8", "zhuang", ""] { - assert_eq!(from_tag(tag), Lang::En, "{tag}"); + for tag in ["ja", "ja-JP", " JA_jp.UTF-8 "] { + assert_eq!(from_tag(tag), Some(Lang::Ja), "{tag}"); } + for tag in ["zh-Hant", "zh-Hant-TW", "zh_TW.UTF-8", "ZH-hk", "zh-MO"] { + assert_eq!(from_tag(tag), Some(Lang::ZhHant), "{tag}"); + } + assert_eq!(from_tag("ko_KR.UTF-8"), Some(Lang::Ko)); + assert_eq!(from_tag("es-419"), Some(Lang::Es)); + assert_eq!(from_tag("es-MX"), Some(Lang::Es)); + assert_eq!(preferred_language(["fr-FR", "ja-JP", "en-US"]), Lang::Ja); + assert_eq!(preferred_language(["en-US", "ja-JP"]), Lang::En); + assert_eq!(preferred_language(["fr-FR", "zhuang", ""]), Lang::En); } #[test] fn a_choice_in_settings_wins_over_the_system() { assert_eq!(effective(Some(Lang::En)), Lang::En); assert_eq!(effective(Some(Lang::Zh)), Lang::Zh); + assert_eq!(effective(Some(Lang::Ja)), Lang::Ja); } /// **断言的是「里面有什么」,不是「一字不差是什么」。**这一行还会再长 @@ -229,7 +272,19 @@ mod tests { /// 每次都要跟着改,改的时候没人会重新想一遍它到底在保证什么。 #[test] fn the_injected_line_names_the_language_and_the_platform() { - for (lang, tag) in [(Lang::En, "en"), (Lang::Zh, "zh")] { + for (lang, tag) in [ + (Lang::En, "en"), + (Lang::Zh, "zh"), + (Lang::Ja, "ja"), + (Lang::ZhHant, "zh-Hant"), + (Lang::Ko, "ko"), + (Lang::Es, "es"), + ] { + assert_eq!(serde_json::to_value(lang).unwrap(), tag); + assert_eq!( + serde_json::from_value::(serde_json::json!(tag)).unwrap(), + lang + ); let line = script_for(lang); assert!( line.contains(&format!("window.__TW_LANG__ = \"{tag}\"")), @@ -267,13 +322,14 @@ mod tests { }) } assert_eq!(pick(&[("LANG", "zh_CN.UTF-8")]), Lang::Zh); + assert_eq!(pick(&[("LANG", "ja_JP.UTF-8")]), Lang::Ja); assert_eq!( pick(&[("LC_MESSAGES", "en_US.UTF-8"), ("LANG", "zh_CN.UTF-8")]), Lang::En ); assert_eq!( pick(&[("LC_ALL", "zh_TW.UTF-8"), ("LC_MESSAGES", "en_US.UTF-8")]), - Lang::Zh + Lang::ZhHant ); // 空值等于没设 assert_eq!(pick(&[("LC_ALL", ""), ("LANG", "zh_CN.UTF-8")]), Lang::Zh); @@ -291,5 +347,10 @@ mod tests { fn tr_picks_by_the_language_of_this_thread() { assert_eq!(with_lang(Lang::En, || tr!("关闭", "Close")), "Close"); assert_eq!(with_lang(Lang::Zh, || tr!("关闭", "Close")), "关闭"); + assert_eq!(with_lang(Lang::Ja, || tr!("关闭", "Close")), "Close"); + assert_eq!( + with_lang(Lang::Ja, || tr!("关闭", "Close", "閉じる")), + "閉じる" + ); } } diff --git a/src-tauri/src/menubar/macos.rs b/src-tauri/src/menubar/macos.rs index 1adc6f01..cd964ec1 100644 --- a/src-tauri/src/menubar/macos.rs +++ b/src-tauri/src/menubar/macos.rs @@ -910,11 +910,19 @@ pub fn confirm_quit(mtm: MainThreadMarker, in_flight: usize) -> bool { alert.setAlertStyle(NSAlertStyle::Warning); alert.setMessageText(&NSString::from_str(tr!( "退出 ThinkWatch Lite", - "Quit ThinkWatch Lite" + "Quit ThinkWatch Lite", + "ThinkWatch Lite を終了"; + "退出 ThinkWatch Lite", + "ThinkWatch Lite 종료", + "Salir de ThinkWatch Lite", ))); let mut info = tr!( "退出后网关将停止监听,所有已接管的客户端将立即无法连接。", - "After quitting, the gateway stops listening, and every connected client immediately loses its connection." + "After quitting, the gateway stops listening, and every connected client immediately loses its connection.", + "終了するとゲートウェイが停止し、接続中のすべてのクライアントが切断されます。"; + "退出後閘道器將停止監聽,所有已接管的用戶端將立即無法連線。", + "After quitting, the gateway stops listening, and every connected client immediately loses its connection.", + "Después de dejar de fumar, la puerta de enlace deja de escuchar, y cada cliente conectado inmediatamente pierde su conexión.", ) .to_string(); if in_flight > 0 { @@ -925,15 +933,41 @@ pub fn confirm_quit(mtm: MainThreadMarker, in_flight: usize) -> bool { "1 request in progress will be interrupted.".to_string() } else { format!("{in_flight} requests in progress will be interrupted.") - } + }, + format!("処理中のリクエスト {in_flight} 件が中断されます。"); + format!("{in_flight} 個請求正在進行,將被中斷。"), + if in_flight == 1 { + "1 request in progress will be interrupted.".to_string() + } else { + format!("{in_flight} requests in progress will be interrupted.") + }, + if in_flight == 1 { + "1 request in progress will be interrupted.".to_string() + } else { + format!("{in_flight} las solicitudes en curso serán interrumpidas.") + }, )); } alert.setInformativeText(&NSString::from_str(&info)); // **取消是默认按钮**:回车不该变成一次退出。要明说 —— 标题恰好是英文「Cancel」时, // AppKit 给它配的是 Esc,对话框里就没有默认按钮了 - let cancel = alert.addButtonWithTitle(&NSString::from_str(tr!("取消", "Cancel"))); + let cancel = alert.addButtonWithTitle(&NSString::from_str(tr!( + "取消", + "Cancel", + "キャンセル"; + "取消", + "취소", + "Cancelar", + ))); cancel.setKeyEquivalent(&NSString::from_str("\r")); - let quit = alert.addButtonWithTitle(&NSString::from_str(tr!("退出", "Quit"))); + let quit = alert.addButtonWithTitle(&NSString::from_str(tr!( + "退出", + "Quit", + "終了"; + "退出", + "종료", + "Salir", + ))); quit.setHasDestructiveAction(true); // Esc 也是取消。一个按钮只有一个快捷键,所以在对话框开着的这段时间里单独接住它 let esc = RcBlock::new(move |event: NonNull| -> *mut NSEvent { @@ -965,7 +999,13 @@ pub fn inform(mtm: MainThreadMarker, title: &str, body: &str) { let alert = NSAlert::new(mtm); alert.setMessageText(&NSString::from_str(title)); alert.setInformativeText(&NSString::from_str(body)); - alert.addButtonWithTitle(&NSString::from_str(tr!("好", "OK"))); + alert.addButtonWithTitle(&NSString::from_str(tr!( + "好", + "OK"; + "好", + "OK", + "OK", + ))); alert.runModal(); } diff --git a/src-tauri/src/menubar/mod.rs b/src-tauri/src/menubar/mod.rs index 04704f8a..d533fceb 100644 --- a/src-tauri/src/menubar/mod.rs +++ b/src-tauri/src/menubar/mod.rs @@ -672,7 +672,14 @@ async fn background(app: &tauri::AppHandle, action: Action) { tracing::warn!("菜单里的操作没做成:{e}"); say( app, - tr!("操作未完成", "The Action Did Not Complete"), + tr!( + "操作未完成", + "The Action Did Not Complete", + "操作を完了できませんでした"; + "操作未完成", + "작업을 완료하지 못했습니다", + "No se completó la acción", + ), &why(e), ); } @@ -704,7 +711,15 @@ async fn copy_default_key(app: &tauri::AppHandle, st: &AppState) -> Result<(), C .find(|k| k.default) .or_else(|| keys.first()) .map(|k| k.name.clone()) - .ok_or_else(|| CmdError::plain(tr!("尚无网关密钥。", "There is no gateway key yet.")))?; + .ok_or_else(|| { + CmdError::plain(tr!( + "尚无网关密钥。", + "There is no gateway key yet."; + "尚無閘道器金鑰。", + "There is no gateway key yet.", + "Todavía no hay una llave de entrada.", + )) + })?; let v = st.control.call::(&[&name], &()).await?; app.clipboard() .write_text(v.key) @@ -717,7 +732,14 @@ async fn check_updates(app: &tauri::AppHandle) { Ok(Some(found)) => crate::updater::present_update(app, found), Ok(None) => say( app, - tr!("已是最新版本", "ThinkWatch Lite Is Up to Date"), + tr!( + "已是最新版本", + "ThinkWatch Lite Is Up to Date", + "ThinkWatch Lite は最新です"; + "已是最新版本", + "ThinkWatch Lite는 최신 버전입니다", + "ThinkWatch Lite está al día", + ), &tr!( format!( "ThinkWatch Lite {} 是最新版本。", @@ -726,10 +748,37 @@ async fn check_updates(app: &tauri::AppHandle) { format!( "ThinkWatch Lite {} is the latest version.", app.package_info().version - ) + ), + format!( + "ThinkWatch Lite {} は最新バージョンです。", + app.package_info().version + ); + format!( + "ThinkWatch Lite {} 是最新版本。", + app.package_info().version + ), + format!( + "ThinkWatch Lite {} is the latest version.", + app.package_info().version + ), + format!( + "ThinkWatch Lite {} es la última versión.", + app.package_info().version + ), + ), + ), + Err(e) => say( + app, + tr!( + "无法检查更新", + "Updates Could Not Be Checked", + "更新を確認できませんでした"; + "無法檢查更新", + "업데이트를 확인할 수 없습니다", + "No se pudo buscar actualizaciones", ), + &e, ), - Err(e) => say(app, tr!("无法检查更新", "Updates Could Not Be Checked"), &e), } } diff --git a/src-tauri/src/menubar/model.rs b/src-tauri/src/menubar/model.rs index 64fc58be..88beb527 100644 --- a/src-tauri/src/menubar/model.rs +++ b/src-tauri/src/menubar/model.rs @@ -130,12 +130,20 @@ impl Today { if self.unpriced > 0 { Some(tr!( format!("{} 条无法计价", self.unpriced), - format!("{} unpriced", self.unpriced) + format!("{} unpriced", self.unpriced), + format!("料金不明 {} 件", self.unpriced); + format!("{} 條無法計價", self.unpriced), + format!("{} unpriced", self.unpriced), + format!("{} sin precio", self.unpriced), )) } else if self.no_usage > 0 { Some(tr!( format!("{} 条无用量", self.no_usage), - format!("{} with no usage", self.no_usage) + format!("{} with no usage", self.no_usage), + format!("使用量なし {} 件", self.no_usage); + format!("{} 條無用量", self.no_usage), + format!("{} with no usage", self.no_usage), + format!("{} sin uso", self.no_usage), )) } else { None @@ -366,7 +374,13 @@ impl WindowRow { pub fn line(&self, provider: &str) -> String { let line = format!("{provider} {} {}", self.label, self.right()); match &self.detail { - Some(d) => tr!(format!("{line}({d})"), format!("{line} ({d})")), + Some(d) => tr!( + format!("{line}({d})"), + format!("{line} ({d})"); + format!("{line}({d})"), + format!("{line} ({d})"), + format!("{line} ({d})"), + ), None => line, } } @@ -438,7 +452,13 @@ impl Dash { line.push_str(&self.meta_line()); } match &self.note { - Some(n) => tr!(format!("{line}({n})"), format!("{line} ({n})")), + Some(n) => tr!( + format!("{line}({n})"), + format!("{line} ({n})"); + format!("{line}({n})"), + format!("{line} ({n})"), + format!("{line} ({n})"), + ), None => line, } } @@ -749,7 +769,27 @@ fn tooltip(s: &Snapshot, tight: Option<(&str, &Window)>) -> String { "{} tokens today, {} cost", tokens_short(t.tokens), t.cost(cost_long) - ) + ), + format!( + "今日のトークン {}、費用 {}", + tokens_short(t.tokens), + t.cost(cost_long) + ); + format!( + "今日 {} token,費用 {}", + tokens_short(t.tokens), + t.cost(cost_long) + ), + format!( + "{} tokens today, {} cost", + tokens_short(t.tokens), + t.cost(cost_long) + ), + format!( + "{} fichas hoy, {} costo", + tokens_short(t.tokens), + t.cost(cost_long) + ), )); } if let Some(r) = s.rate { @@ -762,24 +802,86 @@ fn tooltip(s: &Snapshot, tight: Option<(&str, &Window)>) -> String { format!( "{percent}% of the {} limit used on {provider}", window_label(&w.window) - ) + ), + format!( + "{provider} の{}の利用枠を {percent}% 使用", + window_label(&w.window) + ); + format!("{provider} {}額度已用 {percent}%", window_label(&w.window)), + format!( + "{percent}% of the {} limit used on {provider}", + window_label(&w.window) + ), + format!( + "{percent}% del {} límite utilizado el {provider}", + window_label(&w.window) + ), )); } if s.in_progress() > 0 { parts.push(live_count(s.in_progress())); } } - parts.join(tr!(",", ", ")) + parts.join(tr!( + ",", + ", ", + "、"; + ",", + ", ", + ", ", + )) } fn state_text(g: &Gateway) -> &'static str { match g { - Gateway::Starting => tr!("正在启动", "Starting"), - Gateway::Running => tr!("运行中", "Running"), - Gateway::SafeMode => tr!("未在转发", "Not Forwarding"), - Gateway::Failed => tr!("无法启动", "Cannot Start"), - Gateway::Stopped => tr!("未运行", "Not Running"), - Gateway::Unlinked => tr!("未连接", "Not Connected"), + Gateway::Starting => tr!( + "正在启动", + "Starting", + "起動中"; + "正在啟動", + "시작 중", + "Iniciando", + ), + Gateway::Running => tr!( + "运行中", + "Running", + "実行中"; + "執行中", + "실행 중", + "En ejecución", + ), + Gateway::SafeMode => tr!( + "未在转发", + "Not Forwarding", + "転送停止中"; + "未在轉發", + "전달 중지됨", + "Reenvío detenido", + ), + Gateway::Failed => tr!( + "无法启动", + "Cannot Start", + "起動できません"; + "無法啟動", + "시작할 수 없음", + "No se pudo iniciar", + ), + Gateway::Stopped => tr!( + "未运行", + "Not Running", + "停止中"; + "未執行", + "중지됨", + "Detenido", + ), + Gateway::Unlinked => tr!( + "未连接", + "Not Connected", + "未接続"; + "未連線", + "연결 안 됨", + "Sin conexión", + ), } } @@ -790,7 +892,19 @@ fn live_count(n: usize) -> String { "1 request in progress".to_string() } else { format!("{n} requests in progress") - } + }, + format!("処理中のリクエスト {n} 件"); + format!("{n} 個請求進行中"), + if n == 1 { + "1 request in progress".to_string() + } else { + format!("{n} requests in progress") + }, + if n == 1 { + "1 solicitud en curso".to_string() + } else { + format!("{n} solicitudes en curso") + }, ) } @@ -806,7 +920,11 @@ fn rows(s: &Snapshot) -> Vec { ..Item::new( "open", "macwindow", - tr!("打开主界面", "Open ThinkWatch Lite"), + tr!( + "打开主界面", + "Open ThinkWatch Lite", + "ThinkWatch Lite を開く" + ), Action::OpenMain, ) }), @@ -821,13 +939,27 @@ fn rows(s: &Snapshot) -> Vec { out.push(Row::Item(Item::new( "retry", "arrow.clockwise", - tr!("立即重试", "Retry Now"), + tr!( + "立即重试", + "Retry Now", + "今すぐ再試行"; + "立即重試", + "지금 다시 시도", + "Reintentar ahora", + ), Action::RetryConnection, ))); out.push(Row::Item(Item::new( "why", "info.circle", - tr!("查看原因…", "Show Details…"), + tr!( + "查看原因…", + "Show Details…", + "詳細を表示…"; + "檢視原因…", + "세부 정보 보기…", + "Ver detalles…", + ), Action::OpenMain, ))); } @@ -835,13 +967,27 @@ fn rows(s: &Snapshot) -> Vec { out.push(Row::Item(Item::new( "restart", "arrow.clockwise", - tr!("重新启动网关", "Restart Gateway"), + tr!( + "重新启动网关", + "Restart Gateway", + "ゲートウェイを再起動"; + "重新啟動閘道器", + "게이트웨이 다시 시작", + "Reiniciar la puerta de enlace", + ), Action::RestartGateway, ))); out.push(Row::Item(Item::new( "why", "info.circle", - tr!("查看原因…", "Show Details…"), + tr!( + "查看原因…", + "Show Details…", + "詳細を表示…"; + "檢視原因…", + "세부 정보 보기…", + "Ver detalles…", + ), Action::OpenMain, ))); } @@ -852,7 +998,17 @@ fn rows(s: &Snapshot) -> Vec { } if s.notices_on && !s.notices.is_empty() { - out.push(section(tr!("提醒", "Notices"), None)); + out.push(section( + tr!( + "提醒", + "Notices", + "通知"; + "提醒", + "알림", + "Avisos", + ), + None, + )); for n in s.notices.iter().take(MAX_NOTICES) { out.push(Row::Notice { level: n.level, @@ -867,7 +1023,11 @@ fn rows(s: &Snapshot) -> Vec { "bell", tr!( format!("全部提醒({})…", s.notices.len()), - format!("All Notices ({})…", s.notices.len()) + format!("All Notices ({})…", s.notices.len()), + format!("すべての通知({} 件)…", s.notices.len()); + format!("全部提醒({})…", s.notices.len()), + format!("모든 알림({}건)…", s.notices.len()), + format!("Todos los avisos ({})…", s.notices.len()), ), Action::AllNotices, ))); @@ -894,10 +1054,24 @@ fn rows(s: &Snapshot) -> Vec { Item::new( &format!("resets:{}", q.provider), "arrow.counterclockwise.circle", - tr!("额度重置卡…", "Quota Reset Credits…"), + tr!( + "额度重置卡…", + "Quota Reset Credits…", + "利用枠リセットクレジット…"; + "額度重置卡…", + "Quota Reset Credits…", + "Créditos de reinicio de cuotas…", + ), Action::Open("upstreams".into()), ) - .right(tr!(format!("可用 {n} 张"), format!("{n} available"))), + .right(tr!( + format!("可用 {n} 张"), + format!("{n} available"), + format!("{n} 件利用可能"); + format!("可用 {n} 張"), + format!("{n} available"), + format!("{n} disponibles"), + )), )); } } @@ -905,7 +1079,14 @@ fn rows(s: &Snapshot) -> Vec { if s.in_progress() > 0 { out.push(section( - tr!("进行中", "In Progress"), + tr!( + "进行中", + "In Progress", + "処理中"; + "進行中", + "진행 중", + "En curso", + ), Some(s.in_progress().to_string()), )); for l in s.live.iter().take(MAX_LIVE) { @@ -931,7 +1112,14 @@ fn rows(s: &Snapshot) -> Vec { ..Item::new( "live-more", "", - tr!(format!("另有 {more} 个"), format!("{more} more")), + tr!( + format!("另有 {more} 个"), + format!("{more} more"), + format!("他 {more} 件"); + format!("另有 {more} 個"), + format!("{more} more"), + format!("{more} más"), + ), Action::Open("requests".into()), ) })); @@ -967,7 +1155,14 @@ fn rows(s: &Snapshot) -> Vec { let copy = Item::new( "copy-address", "doc.on.doc", - tr!("复制网关地址", "Copy Gateway Address"), + tr!( + "复制网关地址", + "Copy Gateway Address", + "ゲートウェイアドレスをコピー"; + "複製閘道器地址", + "게이트웨이 주소 복사", + "Copiar dirección de la puerta de enlace", + ), Action::CopyAddress, ); out.push(Row::Item(match &s.addr { @@ -977,7 +1172,14 @@ fn rows(s: &Snapshot) -> Vec { out.push(Row::Item(Item::new( "copy-key", "key", - tr!("复制默认密钥", "Copy Default Key"), + tr!( + "复制默认密钥", + "Copy Default Key", + "既定のキーをコピー"; + "複製預設金鑰", + "기본 키 복사", + "Copiar clave predeterminada", + ), Action::CopyKey, ))); out.push(Row::Separator); @@ -993,21 +1195,46 @@ fn status(s: &Snapshot) -> Row { StateTone::Warn, Some(tr!( "已连续启动失败,当前只有配置和历史可用。", - "Startup failed several times in a row. Only configuration and history are available." + "Startup failed several times in a row. Only configuration and history are available.", + "起動に繰り返し失敗しました。設定と履歴は引き続き利用できます。"; + "已連續啟動失敗,當前只有配置和歷史可用。", + "Startup failed several times in a row. Only configuration and history are available.", + "El inicio falló varias veces seguidas. Sólo la configuración y el historial están disponibles.", )), ), Gateway::Failed => ( StateTone::Bad, Some(tr!( "core 程序未能运行,转发已停止。", - "The core program could not run, so forwarding has stopped." + "The core program could not run, so forwarding has stopped.", + "core を実行できなかったため、転送を停止しました。"; + "core 程式未能執行,轉發已停止。", + "core를 실행할 수 없어 요청 전달을 중지했습니다.", + "Se detuvo el reenvío porque no se pudo ejecutar core.", )), ), Gateway::Stopped => ( StateTone::Bad, - Some(tr!("转发已停止。", "Forwarding has stopped.")), + Some(tr!( + "转发已停止。", + "Forwarding has stopped.", + "転送が停止しています。"; + "轉發已停止。", + "요청 전달이 중지되었습니다.", + "Se detuvo el reenvío.", + )), + ), + Gateway::Unlinked => ( + StateTone::Bad, + Some(tr!( + "正在重新连接。", + "Reconnecting.", + "再接続しています。"; + "正在重新連線。", + "Reconnecting.", + "Reconnecting.", + )), ), - Gateway::Unlinked => (StateTone::Bad, Some(tr!("正在重新连接。", "Reconnecting."))), }; Row::Status { state: state_text(&s.gateway).to_string(), @@ -1030,13 +1257,32 @@ fn dash(s: &Snapshot) -> Dash { "1 request".to_string() } else { format!("{n} requests") - } + }, + format!("{n} 件"); + format!("{n} 次"), + if t.requests == 1 { + "1 request".to_string() + } else { + format!("{n} requests") + }, + if t.requests == 1 { + "1 solicitud".to_string() + } else { + format!("{n} solicitudes") + }, ), failed: false, }); if t.failed > 0 { meta.push(Meta { - text: tr!(format!("失败 {}", t.failed), format!("{} failed", t.failed)), + text: tr!( + format!("失败 {}", t.failed), + format!("{} failed", t.failed), + format!("失敗 {} 件", t.failed); + format!("失敗 {}", t.failed), + format!("{} failed", t.failed), + format!("{} falló", t.failed), + ), failed: true, }); } @@ -1046,7 +1292,15 @@ fn dash(s: &Snapshot) -> Dash { }); } Dash { - title: tr!("今日", "Today").to_string(), + title: tr!( + "今日", + "Today", + "今日"; + "今日", + "오늘", + "Hoy", + ) + .to_string(), state: state_text(&s.gateway).to_string(), tone: StateTone::Ok, server: s.remote.clone(), @@ -1058,7 +1312,19 @@ fn dash(s: &Snapshot) -> Dash { "token" } else { "tokens" - } + }, + "トークン"; + "token", + if t.is_some_and(|t| t.tokens == 1) { + "token" + } else { + "tokens" + }, + if t.is_some_and(|t| t.tokens == 1) { + "token" + } else { + "tokens" + }, ) .to_string(), meta, @@ -1079,17 +1345,55 @@ fn dash(s: &Snapshot) -> Dash { } else { "requests" } - ) + ), + format!("今日のトークン {tokens}、リクエスト {requests} 件"); + format!("今日 {tokens} token,{requests} 次請求"), + format!( + "{tokens} {} today, {requests} {}", + if t.tokens == 1 { "token" } else { "tokens" }, + if t.requests == 1 { + "request" + } else { + "requests" + } + ), + format!( + "{tokens} {} hoy, {requests} {}", + if t.tokens == 1 { "token" } else { "tokens" }, + if t.requests == 1 { + "request" + } else { + "requests" + } + ), ); if t.failed > 0 { tip.push_str(&tr!( format!(",失败 {} 次", t.failed), - format!(", {} failed", t.failed) + format!(", {} failed", t.failed), + format!("、失敗 {} 件", t.failed); + format!(",失敗 {} 次", t.failed), + format!(", {} failed", t.failed), + format!(", {} falló", t.failed), )); } - tip.push_str(&tr!(format!(",费用 {cost}"), format!(", {cost} cost"))); + tip.push_str(&tr!( + format!(",费用 {cost}"), + format!(", {cost} cost"), + format!("、費用 {cost}"); + format!(",費用 {cost}"), + format!(", {cost} cost"), + format!(", {cost} costo"), + )); if let Some(note) = t.cost_note() { - tip.push_str(&tr!(format!("({note})"), format!(" ({note})"))); + tip.push_str(&tr!( + format!("({note})"), + format!(" ({note})"), + format!("({note})"); + format!("({note})"), + format!(" ({note})"), + format!(" {note})"), + )); } tip }), @@ -1113,7 +1417,14 @@ fn app_items(s: &Snapshot, out: &mut Vec) { ..Item::new( "update", "arrow.down.circle", - tr!(format!("安装新版本 {v}…"), format!("Install Version {v}…")), + tr!( + format!("安装新版本 {v}…"), + format!("Install Version {v}…"), + format!("バージョン {v} をインストール…"); + format!("安裝新版本 {v}…"), + format!("Install Version {v}…"), + format!("Instalar versión {v}…"), + ), Action::InstallUpdate, ) })); @@ -1122,7 +1433,14 @@ fn app_items(s: &Snapshot, out: &mut Vec) { Item::new( "settings", "gearshape", - tr!("设置…", "Settings…"), + tr!( + "设置…", + "Settings…", + "設定…"; + "設定…", + "설정…", + "Configuración…", + ), Action::Settings, ) .key(","), @@ -1132,7 +1450,14 @@ fn app_items(s: &Snapshot, out: &mut Vec) { out.push(Row::Item(Item::new( "update", "arrow.down.circle", - tr!("检查更新…", "Check for Updates…"), + tr!( + "检查更新…", + "Check for Updates…", + "更新を確認…"; + "檢查更新…", + "업데이트 확인…", + "Buscar actualizaciones…", + ), Action::CheckUpdates, ))); } @@ -1141,7 +1466,14 @@ fn app_items(s: &Snapshot, out: &mut Vec) { Item::new( "quit", "power", - tr!("退出 ThinkWatch Lite…", "Quit ThinkWatch Lite…"), + tr!( + "退出 ThinkWatch Lite…", + "Quit ThinkWatch Lite…", + "ThinkWatch Lite を終了…"; + "退出 ThinkWatch Lite…", + "ThinkWatch Lite 종료…", + "Salir de ThinkWatch Lite…", + ), Action::Quit, ) .key("q"), @@ -1153,7 +1485,14 @@ fn connections(s: &Snapshot) -> Item { let mut item = Item::new( "connections", "network", - tr!("连接", "Connection"), + tr!( + "连接", + "Connection", + "接続"; + "連線", + "연결", + "Conexión", + ), Action::OpenMain, ); item.action = None; @@ -1168,7 +1507,15 @@ fn connections(s: &Snapshot) -> Item { }) .collect(); subs.push(SubItem { - title: tr!("管理连接…", "Manage Connections…").to_string(), + title: tr!( + "管理连接…", + "Manage Connections…", + "接続を管理…"; + "管理連線…", + "Manage Connections…", + "Administrar conexiones…", + ) + .to_string(), checked: false, action: Action::Settings, sep_before: true, @@ -1183,7 +1530,15 @@ fn window_row(w: &Window, now_ms: u64) -> WindowRow { return WindowRow { label: window_label(&w.window), percent: None, - reset: tr!("已重置", "Reset").to_string(), + reset: tr!( + "已重置", + "Reset", + "リセット済み"; + "已重置", + "Reset", + "Reiniciar", + ) + .to_string(), tone: Tone::Normal, detail: None, }; @@ -1204,12 +1559,49 @@ fn window_row(w: &Window, now_ms: u64) -> WindowRow { /// 「45 分钟」),认不出来的原样显示 pub fn window_label(window: &str) -> String { match window { - "5h" => tr!("5 小时", "5h").to_string(), - "weekly" => tr!("每周", "Weekly").to_string(), + "5h" => tr!( + "5 小时", + "5h", + "5 時間"; + "5 小時", + "5h", + "5h", + ) + .to_string(), + "weekly" => tr!( + "每周", + "Weekly", + "毎週"; + "每週", + "Weekly", + "Semanal", + ) + .to_string(), other => match window_span(other) { - Some((n, Span::Days)) => tr!(format!("{n} 天"), english_count(n, "day")), - Some((n, Span::Hours)) => tr!(format!("{n} 小时"), english_count(n, "hour")), - Some((n, Span::Minutes)) => tr!(format!("{n} 分钟"), english_count(n, "minute")), + Some((n, Span::Days)) => tr!( + format!("{n} 天"), + english_count(n, "day"), + format!("{n} 日"); + format!("{n} 天"), + english_count(n, "day"), + english_count(n, "day"), + ), + Some((n, Span::Hours)) => tr!( + format!("{n} 小时"), + english_count(n, "hour"), + format!("{n} 時間"); + format!("{n} 小時"), + english_count(n, "hour"), + english_count(n, "hour"), + ), + Some((n, Span::Minutes)) => tr!( + format!("{n} 分钟"), + english_count(n, "minute"), + format!("{n} 分"); + format!("{n} 分鐘"), + english_count(n, "minute"), + english_count(n, "minute"), + ), None => other.to_string(), }, } @@ -1256,7 +1648,11 @@ fn credits_left(c: QuotaCredits) -> String { let (left, total) = (count(c.remaining), count(c.total)); tr!( format!("剩余 {left} / {total} 积分"), - format!("{left} / {total} credits left") + format!("{left} / {total} credits left"), + format!("残り {left} / {total} クレジット"); + format!("剩餘 {left} / {total} 積分"), + format!("{left} / {total} credits left"), + format!("{left} / {total} créditos restantes"), ) } @@ -1269,14 +1665,26 @@ fn count(n: f64) -> String { /// 不够用,不是为了对表。**取整之后再定单位**:59.5 分钟是「1 小时」,不是「60 分钟」 pub fn resets_in(secs: u64) -> String { let [m, h, d] = [60.0, 3600.0, 86_400.0].map(|unit| (secs as f64 / unit).round() as u64); - let (zh, en) = if secs == 0 { - ("刚刚".to_string(), "now".to_string()) + let (zh, en, ja) = if secs == 0 { + ("刚刚".to_string(), "now".to_string(), "今すぐ".to_string()) } else if secs < 60 { - ("1 分钟内".to_string(), "within 1 min".to_string()) + ( + "1 分钟内".to_string(), + "within 1 min".to_string(), + "1 分以内に".to_string(), + ) } else if m < 60 { - (format!("{m} 分钟后"), format!("in {m} min")) + ( + format!("{m} 分钟后"), + format!("in {m} min"), + format!("{m} 分後に"), + ) } else if h < 24 { - (format!("{h} 小时后"), format!("in {h} h")) + ( + format!("{h} 小时后"), + format!("in {h} h"), + format!("{h} 時間後に"), + ) } else { ( format!("{d} 天后"), @@ -1285,9 +1693,17 @@ pub fn resets_in(secs: u64) -> String { } else { format!("in {d} days") }, + format!("{d} 日後に"), ) }; - tr!(format!("{zh}重置"), format!("Resets {en}")) + tr!( + format!("{zh}重置"), + format!("Resets {en}"), + format!("{ja}リセット"); + format!("{zh}重置"), + format!("Resets {en}"), + format!("Reinicia {en}"), + ) } /// `x` 按 `digits` 位小数写出来。**写出来的数到了 `limit` 就不算**(进位进到了下一档): @@ -1327,7 +1743,14 @@ pub fn rate_short(rate: u32) -> String { /// 菜单和悬停提示里的生成速度:「42 token/秒」 fn rate_long(r: u32) -> String { - tr!(format!("{r} token/秒"), format!("{r} tokens/s")) + tr!( + format!("{r} token/秒"), + format!("{r} tokens/s"), + format!("{r} トークン/秒"); + format!("{r} token/秒"), + format!("{r} tokens/s"), + format!("{r} tokens/s"), + ) } /// 菜单里的费用:地方够,满 $1000 之前都写到分。$999.996 写到分是「$1000.00」,那已经是 diff --git a/src-tauri/src/notices/linux.rs b/src-tauri/src/notices/linux.rs index f80f259a..4cc263af 100644 --- a/src-tauri/src/notices/linux.rs +++ b/src-tauri/src/notices/linux.rs @@ -615,7 +615,12 @@ mod native { // (`crate::desktop_entry`); GNOME attributes notifications by it desktop_entry: app.config().identifier.clone(), icon: write_icon(&dir), - open_label: tr!("打开", "Open").to_string(), + open_label: tr!( + "打开", + "Open"; + "開啟", + ) + .to_string(), store: Some(dir.join(STORE_FILE)), on_click: Box::new(move |key, token| clicked(&a, &key, token)), }); diff --git a/src-tauri/src/notices/mod.rs b/src-tauri/src/notices/mod.rs index a94b8d6d..3d270c6a 100644 --- a/src-tauri/src/notices/mod.rs +++ b/src-tauri/src/notices/mod.rs @@ -891,7 +891,8 @@ impl Notices { level, title: tr!( format!("{} 条安全规则命中", batch.len()), - format!("{} Security Rules Matched", batch.len()) + format!("{} Security Rules Matched", batch.len()); + format!("{} 條安全規則命中", batch.len()), ), body: merged_body(batch.iter().map(|(_, line)| line.as_str()).collect()), count: 1, @@ -944,7 +945,8 @@ impl Notices { level: Level::Info, title: tr!( format!("{}(时断时续)", o.notice.title), - format!("{} (Intermittent)", o.notice.title) + format!("{} (Intermittent)", o.notice.title); + format!("{}(時斷時續)", o.notice.title), ), at_ms, ..o.notice.clone() @@ -976,7 +978,8 @@ impl Notices { level: Level::Info, title: tr!( format!("{}已恢复", was.notice.title), - format!("Resolved: {}", was.notice.title) + format!("Resolved: {}", was.notice.title); + format!("{}已恢復", was.notice.title), ), body: String::new(), view: was.notice.view.clone(), @@ -1041,7 +1044,15 @@ fn merged_body(lines: Vec<&str>) -> String { "{}{more}. All were recorded in the security log.", shown.join("; ") ) - } + }; + { + let more = if rest > 0 { + format!("等 {n} 條") + } else { + String::new() + }; + format!("{}{more}。均已記入安全日誌。", shown.join(";")) + }, ) } @@ -1056,7 +1067,8 @@ fn with_held(body: String, held: usize) -> String { format!("{body} (1 more notice pending)") } else { format!("{body} ({held} more notices pending)") - } + }; + format!("{body}(另有 {held} 項待處理)"), ) } diff --git a/src-tauri/src/notices/rules.rs b/src-tauri/src/notices/rules.rs index b3c03313..bf9e89a4 100644 --- a/src-tauri/src/notices/rules.rs +++ b/src-tauri/src/notices/rules.rs @@ -27,15 +27,57 @@ use super::{Change, Level, Signal}; fn l1_step(s: &tw_api::L1Stage) -> String { use tw_api::{L1Peer, L1Step}; let step: &str = match s.step { - L1Step::Config => tr!("配置", "configuration"), - L1Step::Dns => tr!("DNS 解析", "DNS lookup"), - L1Step::Tcp => tr!("TCP 握手", "TCP handshake"), - L1Step::Tls => tr!("TLS 握手", "TLS handshake"), - L1Step::Handshake => tr!("代理握手", "proxy handshake"), + L1Step::Config => tr!( + "配置", + "configuration", + "設定"; + "配置", + "configuration", + "configuration", + ), + L1Step::Dns => tr!( + "DNS 解析", + "DNS lookup", + "DNS 名前解決"; + "DNS 解析", + "DNS lookup", + "Búsqueda de DNS", + ), + L1Step::Tcp => tr!( + "TCP 握手", + "TCP handshake", + "TCP ハンドシェイク"; + "TCP 握手", + "TCP handshake", + "Apretón de manos TCP", + ), + L1Step::Tls => tr!( + "TLS 握手", + "TLS handshake", + "TLS ハンドシェイク"; + "TLS 握手", + "TLS handshake", + "Apretón de manos TLS", + ), + L1Step::Handshake => tr!( + "代理握手", + "proxy handshake", + "プロキシのハンドシェイク"; + "代理握手", + "proxy handshake", + "apretón de manos proxy", + ), }; // 代理握手本来就只对着代理,再加一句「到代理」是废话 if s.peer == L1Peer::Proxy && s.step != L1Step::Handshake { - tr!(format!("到代理的{step}"), format!("{step} to the proxy")) + tr!( + format!("到代理的{step}"), + format!("{step} to the proxy"), + format!("プロキシへの{step}"); + format!("到代理的{step}"), + format!("{step} to the proxy"), + format!("{step} al proxy"), + ) } else { step.to_string() } @@ -223,7 +265,15 @@ pub fn from_event(ev: &Event) -> Vec { return vec![Signal::cleared(format!("auth:{provider}"))]; } let code = status - .map(|s| tr!(format!("({s})"), format!(" ({s})"))) + .map(|s| { + tr!( + format!("({s})"), + format!(" ({s})"); + format!("({s})"), + format!(" ({s})"), + format!(" ({s})"), + ) + }) .unwrap_or_default(); vec![ Signal::raised( @@ -262,7 +312,10 @@ pub fn from_event(ev: &Event) -> Vec { let step = l1_step(s); tr!( format!("卡在{step}。"), - format!("It got stuck at the {step}. ") + format!("It got stuck at the {step}. "); + format!("卡在{step}。"), + format!("It got stuck at the {step}. "), + format!("Se quedó atascado en el {step}. "), ) }) .unwrap_or_default(); @@ -290,18 +343,32 @@ pub fn from_event(ev: &Event) -> Vec { .. } if origin == "external" => { let at = line - .map(|l| tr!(format!("第 {l} 行:"), format!("Line {l}: "))) + .map(|l| { + tr!( + format!("第 {l} 行:"), + format!("Line {l}: "), + format!("{l} 行目:"); + format!("第 {l} 行:"), + format!("Line {l}: "), + format!("Línea {l}: "), + ) + }) .unwrap_or_default(); let message = core_text::clause(message); vec![ Signal::raised( "config", Level::Warning, - tr!("配置文件未通过校验", "Config File Failed Validation"), + tr!( + "配置文件未通过校验", + "Config File Failed Validation", + "設定ファイルの検証に失敗" + ), ) .body(tr!( format!("{at}{message}。上一版配置仍在服务。"), - format!("{at}{message}. The previous configuration remains in effect.") + format!("{at}{message}. The previous configuration remains in effect."), + format!("{at}{message}。以前の設定で動作を続けています。") )) .view(SETTINGS), ] @@ -320,11 +387,19 @@ pub fn from_event(ev: &Event) -> Vec { Signal::raised( "listen", Level::Warning, - tr!("监听设置未生效", "Listen Settings Not in Effect"), + tr!( + "监听设置未生效", + "Listen Settings Not in Effect", + "リッスン設定が未適用" + ), ) .body(tr!( format!("{}网关仍在 {at} 上监听。", core_text::text(e)), - format!("{} The gateway is still listening on {at}.", e.text) + format!("{} The gateway is still listening on {at}.", e.text), + format!( + "{} ゲートウェイは引き続き {at} でリッスンしています。", + core_text::text(e) + ) )) // 设置页并滚到「网关监听」那一节:未生效的原因也写在那里 .view(LISTEN_SETTINGS), @@ -376,12 +451,18 @@ pub fn from_event(ev: &Event) -> Vec { } if action == "cut" => { let title = tr!( format!("已拦截 {provider} 返回的 {tool} 调用"), - format!("Blocked {tool} Call from “{provider}”") + format!("Blocked {tool} Call from “{provider}”"); + format!("已攔截 {provider} 返回的 {tool} 呼叫"), + format!("Blocked {tool} Call from “{provider}”"), + format!("Bloqueado {tool} Llamada de “{provider}”"), ); let name = tool_rule_name(rule); let body = tr!( format!("命中规则「{name}」,响应已切断。"), - format!("It matched the rule “{name}”, so the response was cut off.") + format!("It matched the rule “{name}”, so the response was cut off."); + format!("命中規則「{name}」,回應已切斷。"), + format!("It matched the rule “{name}”, so the response was cut off."), + format!("Coincidía con la regla “{name}”, por lo que se cortó la respuesta."), ); // **正文不带调用内容**:系统通知在锁屏上也看得见 vec![ @@ -437,14 +518,19 @@ pub fn from_event(ev: &Event) -> Vec { } if *source != "aborted" => { let why = core_text::clause(message); vec![ - Signal::raised("failed", Level::Info, tr!("请求失败", "Request Failed")) - .body(tr!( - format!("「{model}」:{why}。"), - format!("“{model}”: {why}.") - )) - .view(FAILED_REQUESTS) - .event() - .gathered(), + Signal::raised( + "failed", + Level::Info, + tr!("请求失败", "Request Failed", "リクエスト失敗"), + ) + .body(tr!( + format!("「{model}」:{why}。"), + format!("“{model}”: {why}."), + format!("「{model}」:{why}。") + )) + .view(FAILED_REQUESTS) + .event() + .gathered(), ] } Event::PluginFailed { @@ -512,8 +598,20 @@ fn key_limit(ev: &Event) -> Vec { let percent = (used.saturating_mul(100) / max.max(1)).min(99); let n = limit_amount(measure, used); let spent = match measure { - tw_api::LimitMeasure::Requests => tr!(format!("{n} 次"), format!("{n} requests")), - tw_api::LimitMeasure::Tokens => tr!(format!("{n} token"), format!("{n} tokens")), + tw_api::LimitMeasure::Requests => tr!( + format!("{n} 次"), + format!("{n} requests"); + format!("{n} 次"), + format!("{n} requests"), + format!("{n} solicitudes"), + ), + tw_api::LimitMeasure::Tokens => tr!( + format!("{n} token"), + format!("{n} tokens"); + format!("{n} token"), + format!("{n} tokens"), + format!("{n} fichas"), + ), tw_api::LimitMeasure::Cost => n, }; vec![ @@ -559,20 +657,38 @@ fn limit_phrase( match measure { LimitMeasure::Requests => tr!( format!("每{zh} {n} 次请求"), - format!("{n} requests per {en}") + format!("{n} requests per {en}"); + format!("每{zh} {n} 次請求"), + format!("{n} requests per {en}"), + format!("{n} solicitudes por {en}"), ), LimitMeasure::Tokens => { let cache = if cache_reads { - tr!("(含缓存读取)", " (cache reads included)") + tr!( + "(含缓存读取)", + " (cache reads included)"; + "(含快取讀取)", + " (cache reads included)", + " (Caché lee incluido)", + ) } else { "" }; tr!( format!("每{zh} {n} token{cache}"), - format!("{n} tokens per {en}{cache}") + format!("{n} tokens per {en}{cache}"); + format!("每{zh} {n} token{cache}"), + format!("{n} tokens per {en}{cache}"), + format!("{n} fichas por {en} {cache}"), ) } - LimitMeasure::Cost => tr!(format!("每{zh} {n} 费用"), format!("{n} per {en}")), + LimitMeasure::Cost => tr!( + format!("每{zh} {n} 费用"), + format!("{n} per {en}"); + format!("每{zh} {n} 費用"), + format!("{n} per {en}"), + format!("{n} por {en}"), + ), } } @@ -604,30 +720,53 @@ pub fn plugin_failed(id: &str, name: &str, request: Option, why: &tw_api::M Some(r) => ( tr!( format!("插件「{name}」运行出错"), - format!("Plugin “{name}” Failed") + format!("Plugin “{name}” Failed"); + format!("外掛「{name}」執行出錯"), + format!("Plugin “{name}” Failed"), + format!("Falló el complemento “{name}”"), ), match reason { Some(why) => tr!( format!("处理请求 #{r} 时出错:{why}。"), - format!("It failed while handling request #{r}: {why}.") + format!("It failed while handling request #{r}: {why}."); + format!("處理請求 #{r} 時出錯:{why}。"), + format!("It failed while handling request #{r}: {why}."), + format!("Falló mientras manejaba la solicitud #{r}: {why}."), ), None => tr!( format!("处理请求 #{r} 时出错。"), - format!("It failed while handling request #{r}.") + format!("It failed while handling request #{r}."); + format!("處理請求 #{r} 時出錯。"), + format!("It failed while handling request #{r}."), + format!("Falló al manejar la solicitud #{r}."), ), }, ), None => ( tr!( format!("插件「{name}」已停止运行"), - format!("Plugin “{name}” Stopped Running") + format!("Plugin “{name}” Stopped Running"); + format!("外掛「{name}」已停止執行"), + format!("Plugin “{name}” Stopped Running"), + format!("Complemento “{name}” Detiene la ejecución"), ), match reason { - Some(why) => tr!(format!("{why}。"), format!("{why}.")), + Some(why) => tr!( + format!("{why}。"), + format!("{why}."); + format!("{why}。"), + format!("{why}."), + format!("{why}."), + ), None => tr!( "在插件页处理之前,此插件不再运行。".to_string(), "Until it is dealt with on the Plugins page, the plugin does not run." - .to_string() + .to_string(); + "在外掛頁處理之前,此外掛不再執行。".to_string(), + "Until it is dealt with on the Plugins page, the plugin does not run." + .to_string(), + "Hasta que no se trate en la página de Plugins, el plugin no se ejecuta." + .to_string(), ), }, ), @@ -643,13 +782,28 @@ pub fn plugin_failed(id: &str, name: &str, request: Option, why: &tw_api::M /// 错、交回的东西不合规矩)是 None fn plugin_reason(m: &tw_api::Msg) -> Option { Some(match m.code.as_str() { - "gw.plugin.cpu_limit" => tr!("CPU 时间超出上限", "it used more CPU time than allowed").into(), + "gw.plugin.cpu_limit" => tr!( + "CPU 时间超出上限", + "it used more CPU time than allowed"; + "CPU 時間超出上限", + "it used more CPU time than allowed", + "usó más tiempo de CPU de lo permitido", + ).into(), "gw.plugin.memory_limit" => { - tr!("内存超出上限", "it used more memory than allowed").into() + tr!( + "内存超出上限", + "it used more memory than allowed"; + "記憶體超出上限", + "it used more memory than allowed", + "Utilizó más memoria de lo permitido", + ).into() } "gw.plugin.output_limit" => tr!( "返回的内容超出上限", - "it returned more output than allowed" + "it returned more output than allowed"; + "返回的內容超出上限", + "it returned more output than allowed", + "Devolvió más salida de lo permitido", ) .into(), // 不是插件的错:同时跑在回答上的插件到了上限,这一个没起来 @@ -658,17 +812,30 @@ fn plugin_reason(m: &tw_api::Msg) -> Option { format!("同时处理回答的插件已达上限({max} 个),此回答未经此插件处理"), format!( "the limit of {max} plugins running on answers at once was reached, so it did not run on this answer" - ) + ); + format!("同時處理回答的外掛已達上限({max} 個),此回答未經此外掛處理"), + format!( + "the limit of {max} plugins running on answers at once was reached, so it did not run on this answer" + ), + format!( + "el límite de {max} plugins que se ejecutan en las respuestas a la vez se alcanzó, por lo que no se ejecutó en esta respuesta" + ), ), None => tr!( "同时处理回答的插件已达上限,此回答未经此插件处理", - "the limit of plugins running on answers at once was reached, so it did not run on this answer" + "the limit of plugins running on answers at once was reached, so it did not run on this answer"; + "同時處理回答的外掛已達上限,此回答未經此外掛處理", + "the limit of plugins running on answers at once was reached, so it did not run on this answer", + "el límite de plugins que se ejecutan en las respuestas a la vez se alcanzó, por lo que no se ejecutó en esta respuesta", ) .into(), }, "gw.plugin.file_changed" | "gw.plugin.changed" => tr!( "插件文件已更改,在插件页审核并确认之前不再运行", - "its file changed, and it does not run until the change is reviewed and approved on the Plugins page" + "its file changed, and it does not run until the change is reviewed and approved on the Plugins page"; + "外掛檔案已更改,在外掛頁稽核並確認之前不再執行", + "its file changed, and it does not run until the change is reviewed and approved on the Plugins page", + "su archivo cambió, y no se ejecuta hasta que el cambio sea revisado y aprobado en la página de Plugins", ) .into(), _ => return None, @@ -688,7 +855,10 @@ pub fn scan_alert(n: usize) -> Option { Level::Warning, tr!( "客户端配置中出现可疑内容", - "Suspicious Content in Client Configuration" + "Suspicious Content in Client Configuration"; + "用戶端配置中出現可疑內容", + "Suspicious Content in Client Configuration", + "Contenido sospechoso en la configuración del cliente", ), ) .body(tr!( @@ -696,7 +866,16 @@ pub fn scan_alert(n: usize) -> Option { match n { 1 => "1 new item. Details are on the MCP page.".to_string(), n => format!("{n} new items. Details are on the MCP page."), - } + }; + format!("新增 {n} 項,詳見 MCP 頁。"), + match n { + 1 => "1 new item. Details are on the MCP page.".to_string(), + n => format!("{n} new items. Details are on the MCP page."), + }, + match n { + 1 => "1 elemento nuevo. Los detalles están en la página de MCP.".to_string(), + n => format!("{n} nuevos ítems. Los detalles están en la página de MCP."), + }, )) .view(MCP) .event() @@ -852,7 +1031,10 @@ fn unpriced(m: &tw_api::UnpricedModel) -> Signal { Level::Info, tr!( format!("模型「{model}」未定价"), - format!("No Price for “{model}”") + format!("No Price for “{model}”"); + format!("模型「{model}」未定價"), + format!("No Price for “{model}”"), + format!("Sin precio para “{model}”"), ), ) .body(tr!( @@ -860,7 +1042,16 @@ fn unpriced(m: &tw_api::UnpricedModel) -> Signal { format!( "{n} {} through “{provider}” in the last 7 days could not be priced, so their cost is not counted. Set a price for it on the Upstreams page.", if n == 1 { "request" } else { "requests" } - ) + ); + format!("最近 7 天經「{provider}」的 {n} 次請求無法計價,費用未計入。在上游頁為它設定價格。"), + format!( + "{n} {} through “{provider}” in the last 7 days could not be priced, so their cost is not counted. Set a price for it on the Upstreams page.", + if n == 1 { "request" } else { "requests" } + ), + format!( + "{n} {} a través de “{provider}” en los últimos 7 días no se pudo calcular el precio, por lo que su costo no se cuenta. Fije un precio para ello en la página Upstreams.", + if n == 1 { "request" } else { "requests" } + ), )) .view(UPSTREAMS) } @@ -887,38 +1078,44 @@ fn watched( let name = guard_rule_name(guard, rule, custom, &detail.rule_snapshot.name); let what = guard_name(guard); let answer = detail.direction == tw_api::SecurityDirection::Response; - let body = match (source, answer, crate::i18n::current()) { - (Some(s), false, crate::i18n::Lang::Zh) => { - let s = saved_source_zh(s); - format!("{what}:经上游「{provider}」的请求含有{s},已记入安全日志。") - } - (Some(s), true, crate::i18n::Lang::Zh) => { - let s = saved_source_zh(s); - format!("{what}:上游「{provider}」的回答含有{s},已记入安全日志。") - } - (Some(s), false, crate::i18n::Lang::En) => { - let s = saved_source_en(s); - format!( - "{what}: a request through upstream “{provider}” contained {s}. It was recorded in the security log." + let body = match (source, answer) { + (Some(source), false) => { + let s = saved_source(source); + tr!( + format!("{what}:经上游「{provider}」的请求含有{s},已记入安全日志。"), + format!("{what}: a request through upstream “{provider}” contained {s}. It was recorded in the security log."), + format!("{what}:アップストリーム「{provider}」へのリクエストに{s}が含まれていました。セキュリティログに記録しました。"); + format!("{what}:經由上游「{provider}」的請求包含{s},已記錄到安全性記錄。"), + format!("{what}: 업스트림 「{provider}」에 보낸 요청에 {s}이(가) 들어 있었습니다. 보안 로그에 기록했습니다."), + format!("{what}: una solicitud al proveedor «{provider}» contenía {s}. Se anotó en el registro de seguridad.") ) } - (Some(s), true, crate::i18n::Lang::En) => { - let s = saved_source_en(s); - format!( - "{what}: an answer from upstream “{provider}” contained {s}. It was recorded in the security log." + (Some(source), true) => { + let s = saved_source(source); + tr!( + format!("{what}:上游「{provider}」的回答含有{s},已记入安全日志。"), + format!("{what}: an answer from upstream “{provider}” contained {s}. It was recorded in the security log."), + format!("{what}:アップストリーム「{provider}」の応答に{s}が含まれていました。セキュリティログに記録しました。"); + format!("{what}:上游「{provider}」的回應包含{s},已記錄到安全性記錄。"), + format!("{what}: 업스트림 「{provider}」의 응답에 {s}이(가) 들어 있었습니다. 보안 로그에 기록했습니다."), + format!("{what}: una respuesta del proveedor «{provider}» contenía {s}. Se anotó en el registro de seguridad.") ) } - (None, false, crate::i18n::Lang::Zh) => { - format!("{what}:经上游「{provider}」的请求命中此规则,已记入安全日志。") - } - (None, true, crate::i18n::Lang::Zh) => { - format!("{what}:上游「{provider}」的回答命中此规则,已记入安全日志。") - } - (None, false, crate::i18n::Lang::En) => format!( - "{what}: a request through upstream “{provider}” matched this rule. It was recorded in the security log." + (None, false) => tr!( + format!("{what}:经上游「{provider}」的请求命中此规则,已记入安全日志。"), + format!("{what}: a request through upstream “{provider}” matched this rule. It was recorded in the security log."), + format!("{what}:アップストリーム「{provider}」へのリクエストがこのルールに一致しました。セキュリティログに記録しました。"); + format!("{what}:經由上游「{provider}」的請求符合此規則,已記錄到安全性記錄。"), + format!("{what}: 업스트림 「{provider}」에 보낸 요청이 이 규칙과 일치했습니다. 보안 로그에 기록했습니다."), + format!("{what}: una solicitud al proveedor «{provider}» coincidió con esta regla. Se anotó en el registro de seguridad.") ), - (None, true, crate::i18n::Lang::En) => format!( - "{what}: an answer from upstream “{provider}” matched this rule. It was recorded in the security log." + (None, true) => tr!( + format!("{what}:上游「{provider}」的回答命中此规则,已记入安全日志。"), + format!("{what}: an answer from upstream “{provider}” matched this rule. It was recorded in the security log."), + format!("{what}:アップストリーム「{provider}」の応答がこのルールに一致しました。セキュリティログに記録しました。"); + format!("{what}:上游「{provider}」的回應符合此規則,已記錄到安全性記錄。"), + format!("{what}: 업스트림 「{provider}」의 응답이 이 규칙과 일치했습니다. 보안 로그에 기록했습니다."), + format!("{what}: una respuesta del proveedor «{provider}» coincidió con esta regla. Se anotó en el registro de seguridad.") ), }; let kind = if custom { "c" } else { "b" }; @@ -928,7 +1125,10 @@ fn watched( Level::Warning, tr!( format!("安全规则「{name}」命中"), - format!("Security Rule “{name}” Matched") + format!("Security Rule “{name}” Matched"); + format!("安全規則「{name}」命中"), + format!("Security Rule “{name}” Matched"), + format!("Regla de seguridad “{name}” igualada"), ), ) .body(body) @@ -936,71 +1136,68 @@ fn watched( .event() .merged(tr!( format!("「{name}」· {provider}"), - format!("“{name}” · {provider}") + format!("“{name}” · {provider}"); + format!("「{name}」· {provider}"), + format!("“{name}” · {provider}"), + format!("“{name}” · {provider}"), )), ) } /// 防护的名字,和安全页的页签一样 fn guard_name(guard: &str) -> String { - tr!( - crate::core_text::table_zh("guard", guard).unwrap_or_else(|| guard.to_string()), + core_text::table_word(crate::i18n::current(), "guard", guard).unwrap_or_else(|| { match guard { "redact" => "Secrets & privacy", "inspect_tools" => "Dangerous commands", _ => "Content filter", } .to_string() - ) + }) } /// 保存的密钥是哪一处的,放进句中(「经上游「X」的请求含有上游「DeepSeek」的密钥」)。 /// 和安全页上写的一样(`savedSourceText`) -fn saved_source_zh(s: &tw_api::SavedSource) -> String { - use tw_api::SavedSourceKind as K; - let n = &s.name; - match s.kind { - K::UpstreamKey => format!("上游「{n}」的密钥"), - K::UpstreamHeader => format!("上游「{n}」请求头中的值"), - K::AccessKey => format!("网关密钥「{n}」"), - K::ProxyPassword => format!("代理「{n}」的密码"), - K::ControlKey => "远程控制密钥".to_string(), - K::SyncCredential => "同步与备份凭据".to_string(), - } -} - -/// 同上,英文,句中的写法(小写开头) -fn saved_source_en(s: &tw_api::SavedSource) -> String { +fn saved_source(s: &tw_api::SavedSource) -> String { use tw_api::SavedSourceKind as K; let n = &s.name; match s.kind { - K::UpstreamKey => format!("the key of upstream “{n}”"), - K::UpstreamHeader => format!("a header value of upstream “{n}”"), - K::AccessKey => format!("gateway key “{n}”"), - K::ProxyPassword => format!("the password of proxy “{n}”"), - K::ControlKey => "the remote control key".to_string(), - K::SyncCredential => "a sync and backup credential".to_string(), + K::UpstreamKey => tr!( + format!("上游「{n}」的密钥"), format!("the key of upstream “{n}”"), format!("アップストリーム「{n}」のキー"); + format!("上游「{n}」的金鑰"), format!("업스트림 「{n}」의 키"), format!("la clave del proveedor «{n}»") + ), + K::UpstreamHeader => tr!( + format!("上游「{n}」请求头中的值"), format!("a header value of upstream “{n}”"), format!("アップストリーム「{n}」のヘッダー値"); + format!("上游「{n}」的請求標頭值"), format!("업스트림 「{n}」의 헤더 값"), format!("un valor de cabecera del proveedor «{n}»") + ), + K::AccessKey => tr!( + format!("网关密钥「{n}」"), format!("gateway key “{n}”"), format!("ゲートウェイキー「{n}」"); + format!("閘道金鑰「{n}」"), format!("게이트웨이 키 「{n}」"), format!("la clave de la puerta de enlace «{n}»") + ), + K::ProxyPassword => tr!( + format!("代理「{n}」的密码"), format!("the password of proxy “{n}”"), format!("プロキシ「{n}」のパスワード"); + format!("代理伺服器「{n}」的密碼"), format!("프록시 「{n}」의 비밀번호"), format!("la contraseña del proxy «{n}»") + ), + K::ControlKey => tr!( + "远程控制密钥", "the remote control key", "リモート制御キー"; + "遠端控制金鑰", "원격 제어 키", "la clave de control remoto" + ).to_string(), + K::SyncCredential => tr!( + "同步与备份凭据", "a sync and backup credential", "同期とバックアップの認証情報"; + "同步與備份認證資訊", "동기화 및 백업 인증 정보", "una credencial de sincronización y copias de seguridad" + ).to_string(), } } -/// 规则的名字,和安全页上的一样:自定义规则就是用户起的名字;内置的取 core 规则目录里的 -/// 中英文名(钉着的这一版 tw-guard,安全页上 core 给的是同一份)。目录里没有的(连着的远程 -/// core 更新、多了规则),用事件里的英文名 +/// 内置规则和安全页共用客户端词表。新规则缺译时用事件里的英文名。 fn guard_rule_name(guard: &str, rule: &str, custom: bool, english: &str) -> String { if custom { return rule.to_string(); } let english = if english.is_empty() { rule } else { english }; - let zh = match guard { - "redact" => tw_guard::redact::rules::builtin(rule).map(|b| b.name_zh.to_string()), - "content" => tw_guard::content::builtin(rule).map(|b| b.name_zh.clone()), - _ => tool_rule(rule).map(|r| r.name_zh.clone()), - }; - tr!( - zh.filter(|z| !z.is_empty()) - .unwrap_or_else(|| english.to_string()), - english.to_string() - ) + core_text::rule_name(crate::i18n::current(), guard, rule) + .unwrap_or(english) + .to_string() } /// 一条内置的工具调用规则(危险命令和提示注入两组) @@ -1028,12 +1225,13 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { Signal::raised( "gateway", Level::Critical, - tr!("网关未在转发", "Gateway Not Forwarding"), + tr!("网关未在转发", "Gateway Not Forwarding", "ゲートウェイは転送停止中"), ) .body( tr!( "已连续启动失败,当前只有配置和历史可用。", - "Startup failed several times in a row. Only configuration and history are available." + "Startup failed several times in a row. Only configuration and history are available.", + "起動に繰り返し失敗しました。設定と履歴は引き続き利用できます。" ) .to_string(), ) @@ -1046,12 +1244,13 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { Signal::raised( "gateway", Level::Critical, - tr!("网关无法启动", "Gateway Cannot Start"), + tr!("网关无法启动", "Gateway Cannot Start", "ゲートウェイを起動できません"), ) .body( tr!( "core 启动后退出,转发已停止。打开窗口可以查看原因并重试。", - "core exited right after starting, so forwarding has stopped. Open the window to see why and try again." + "core exited right after starting, so forwarding has stopped. Open the window to see why and try again.", + "core が起動直後に終了し、転送を停止しました。ウィンドウを開いて原因を確認し、再試行してください。" ) .to_string(), ) @@ -1064,12 +1263,13 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { Signal::raised( "gateway", Level::Critical, - tr!("网关无法启动", "Gateway Cannot Start"), + tr!("网关无法启动", "Gateway Cannot Start", "ゲートウェイを起動できません"), ) .body( tr!( "core 程序未能运行,转发已停止。打开窗口可以查看原因并重试。", - "The core program could not run, so forwarding has stopped. Open the window to see why and try again." + "The core program could not run, so forwarding has stopped. Open the window to see why and try again.", + "core を実行できなかったため、転送を停止しました。ウィンドウを開いて原因を確認し、再試行してください。" ) .to_string(), ) @@ -1082,13 +1282,14 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { Signal::raised( "gateway", Level::Critical, - tr!("网关反复退出", "Gateway Keeps Exiting"), + tr!("网关反复退出", "Gateway Keeps Exiting", "ゲートウェイが繰り返し終了しています"), ) .body(tr!( format!("已连续重启 {attempt} 次,转发可能时断时续。"), format!( "The gateway restarted {attempt} times in a row. Forwarding may be intermittent." - ) + ), + format!("{attempt} 回連続で再起動しました。転送が断続的に停止する場合があります。") )) .view(SETTINGS) .now() @@ -1106,12 +1307,23 @@ pub fn wedged() -> Signal { Signal::raised( "wedged", Level::Info, - tr!("网关曾无响应,已重启", "Gateway Stopped Responding and Was Restarted"), + tr!( + "网关曾无响应,已重启", + "Gateway Stopped Responding and Was Restarted", + "応答がなかったためゲートウェイを再起動しました"; + "閘道器曾無回應,已重啟", + "Gateway Stopped Responding and Was Restarted", + "Gateway dejó de responder y fue reiniciada", + ), ) .body( tr!( "网关连续几次没有响应,已自动重启。重启期间的请求可能失败。", - "The gateway did not respond several times in a row and was restarted automatically. Requests during the restart may have failed." + "The gateway did not respond several times in a row and was restarted automatically. Requests during the restart may have failed.", + "ゲートウェイが繰り返し応答しなかったため、自動で再起動しました。再起動中のリクエストは失敗した可能性があります。"; + "閘道器連續幾次沒有回應,已自動重啟。重啟期間的請求可能失敗。", + "The gateway did not respond several times in a row and was restarted automatically. Requests during the restart may have failed.", + "El gateway no respondió varias veces seguidas y se reinicia automáticamente. Las peticiones durante el reinicio pueden haber fallado.", ) .to_string(), ) @@ -1146,12 +1358,21 @@ pub fn tray_failed() -> Signal { Signal::raised( "startup:tray", Level::Warning, - tr!(format!("{zh}图标未能显示"), title_en.to_string()), + tr!( + format!("{zh}图标未能显示"), + title_en.to_string(); + format!("{zh}圖示未能顯示"), + title_en.to_string(), + title_en.to_string(), + ), ) .body( tr!( "网关照常运行。窗口关闭后,再次打开应用即可回到主界面。", - "The gateway keeps running. After the window is closed, opening the app again brings it back." + "The gateway keeps running. After the window is closed, opening the app again brings it back."; + "閘道器照常執行。視窗關閉後,再次開啟應用即可回到主介面。", + "The gateway keeps running. After the window is closed, opening the app again brings it back.", + "La puerta de enlace sigue funcionando. Después de cerrar la ventana, abrir la aplicación de nuevo lo devuelve.", ) .to_string(), ) @@ -1164,11 +1385,21 @@ pub fn window_failed() -> Signal { Signal::raised( "startup:window", Level::Warning, - tr!("主窗口未能打开", "Main Window Could Not Be Opened"), + tr!( + "主窗口未能打开", + "Main Window Could Not Be Opened", + "メインウィンドウを開けませんでした"; + "主視窗未能開啟", + "Main Window Could Not Be Opened", + "No se pudo abrir la ventana principal", + ), ) .body(tr!( format!("网关照常运行。可以从{zh}再次打开主界面。"), - format!("The gateway keeps running. The window can be opened again from the {en}.") + format!("The gateway keeps running. The window can be opened again from the {en}."); + format!("閘道器照常執行。可以從{zh}再次開啟主介面。"), + format!("The gateway keeps running. The window can be opened again from the {en}."), + format!("La puerta de enlace sigue funcionando. La ventana se puede abrir de nuevo desde el {en}."), )) .event() } @@ -1179,11 +1410,21 @@ pub fn picker_failed() -> Signal { Signal::raised( "startup:picker", Level::Warning, - tr!("连接选择未能打开", "Connection Picker Could Not Be Opened"), + tr!( + "连接选择未能打开", + "Connection Picker Could Not Be Opened", + "接続の選択画面を開けませんでした"; + "連線選擇未能開啟", + "연결 선택 창을 열 수 없음", + "No se pudo abrir el selector de conexión", + ), ) .body(tr!( format!("尚未连接 core。可以在{zh}的「连接」中选择要连接的 core。"), - format!("No core is connected yet. One can be chosen under Connection in the {en}.") + format!("No core is connected yet. One can be chosen under Connection in the {en}."); + format!("尚未連線 core。可以在{zh}的「連線」中選擇要連線的 core。"), + format!("No core is connected yet. One can be chosen under Connection in the {en}."), + format!("No hay núcleo conectado todavía. Uno puede ser elegido bajo Conexión en el {en}."), )) .event() } @@ -1196,13 +1437,19 @@ pub fn remote_lost(name: &str) -> Signal { Level::Critical, tr!( format!("与 {name} 的连接已断开"), - format!("Disconnected from “{name}”") + format!("Disconnected from “{name}”"); + format!("與 {name} 的連線已斷開"), + format!("Disconnected from “{name}”"), + format!("Desconectado de “{name}”"), ), ) .body( tr!( "正在重新连接。连接恢复前,应用中的内容停留在断开时的状态。", - "Reconnecting. Until the connection is restored, the app shows the state at the time of the disconnect." + "Reconnecting. Until the connection is restored, the app shows the state at the time of the disconnect."; + "正在重新連線。連線恢復前,應用中的內容停留在斷開時的狀態。", + "Reconnecting. Until the connection is restored, the app shows the state at the time of the disconnect.", + "Reconectar. Hasta que se restaure la conexión, la aplicación muestra el estado en el momento de la desconexión.", ) .to_string(), ) @@ -1222,12 +1469,44 @@ pub fn remote_back() -> Signal { fn window_label(w: &str) -> String { use crate::menubar::model::{Span, window_span}; match w { - "weekly" => tr!("每周", "weekly").into(), - "5h" => tr!("5 小时", "5-hour").into(), + "weekly" => tr!( + "每周", + "weekly"; + "每週", + "weekly", + "weekly", + ) + .into(), + "5h" => tr!( + "5 小时", + "5-hour"; + "5 小時", + "5-hour", + "5-hour", + ) + .into(), other => match window_span(other) { - Some((n, Span::Days)) => tr!(format!("{n} 天"), format!("{n}-day")), - Some((n, Span::Hours)) => tr!(format!("{n} 小时"), format!("{n}-hour")), - Some((n, Span::Minutes)) => tr!(format!("{n} 分钟"), format!("{n}-minute")), + Some((n, Span::Days)) => tr!( + format!("{n} 天"), + format!("{n}-day"); + format!("{n} 天"), + format!("{n}-day"), + format!("{n} días"), + ), + Some((n, Span::Hours)) => tr!( + format!("{n} 小时"), + format!("{n}-hour"); + format!("{n} 小時"), + format!("{n}-hour"), + format!("{n}-hora"), + ), + Some((n, Span::Minutes)) => tr!( + format!("{n} 分钟"), + format!("{n}-minute"); + format!("{n} 分鐘"), + format!("{n}-minute"), + format!("{n} minutos"), + ), None => other.to_string(), }, } @@ -1241,7 +1520,14 @@ fn window_label(w: &str) -> String { fn after(secs: u64) -> String { let [m, h, d] = [60.0, 3600.0, 86_400.0].map(|unit| (secs as f64 / unit).round() as u64); let (n, unit, unit_en) = if secs < 60 { - return tr!(",即将重置", " and resets shortly").into(); + return tr!( + ",即将重置", + " and resets shortly"; + ",即將重置", + " and resets shortly", + " y se reinicia en breve", + ) + .into(); } else if m < 60 { (m, "分钟", "minute") } else if h < 24 { @@ -1252,6 +1538,9 @@ fn after(secs: u64) -> String { let plural = if n == 1 { "" } else { "s" }; tr!( format!(",约 {n} {unit}后重置"), - format!(" and resets in about {n} {unit_en}{plural}") + format!(" and resets in about {n} {unit_en}{plural}"); + format!(",約 {n} {unit}後重置"), + format!(" and resets in about {n} {unit_en}{plural}"), + format!(" y se reinicia en aproximadamente {n} {unit_en} {plural}"), ) } diff --git a/src-tauri/src/plugins/defaults.rs b/src-tauri/src/plugins/defaults.rs index 546c71eb..eb20be45 100644 --- a/src-tauri/src/plugins/defaults.rs +++ b/src-tauri/src/plugins/defaults.rs @@ -32,6 +32,11 @@ struct Entry { manifest_name: String, zh: Words, en: Words, + ja: Words, + #[serde(rename = "zh-Hant")] + zh_hant: Words, + ko: Words, + es: Words, } #[derive(Deserialize)] @@ -62,6 +67,10 @@ fn words(e: &Entry, lang: Lang) -> &Words { match lang { Lang::Zh => &e.zh, Lang::En => &e.en, + Lang::Ja => &e.ja, + Lang::ZhHant => &e.zh_hant, + Lang::Ko => &e.ko, + Lang::Es => &e.es, } } diff --git a/src-tauri/src/plugins/mod.rs b/src-tauri/src/plugins/mod.rs index 65b821d7..ccdb91e6 100644 --- a/src-tauri/src/plugins/mod.rs +++ b/src-tauri/src/plugins/mod.rs @@ -158,7 +158,8 @@ pub async fn plugin_approve_confirmed( let (Some(current), Some(sha)) = (source.current, source.current_sha256) else { return Err(CmdError::plain(tr!( "插件文件已不存在或无法读取。", - "The plugin file no longer exists or cannot be read." + "The plugin file no longer exists or cannot be read."; + "外掛檔案已不存在或無法讀取。", ))); }; let read = inspect(c, ¤t).await?; @@ -254,7 +255,8 @@ async fn inspect(c: &ControlClient, source: &str) -> Out { if source.len() > MAX_SOURCE { return Err(CmdError::plain(tr!( "插件文件超过 1 MB 的上限。", - "The plugin file is over the 1 MB limit." + "The plugin file is over the 1 MB limit."; + "外掛檔案超過 1 MB 的上限。", ))); } let i: PluginInspection = c @@ -273,7 +275,8 @@ async fn inspect(c: &ControlClient, source: &str) -> Out { let manifest = i.manifest.ok_or_else(|| { CmdError::plain(tr!( "代码里没有可用的插件清单。", - "The code has no usable plugin manifest." + "The code has no usable plugin manifest."; + "程式碼裡沒有可用的外掛清單。", )) })?; Ok(Read { @@ -318,7 +321,8 @@ async fn installed(c: &ControlClient, id: &str) -> Out { all.into_iter().find(|p| p.id == id).ok_or_else(|| { CmdError::plain(tr!( format!("插件「{id}」不存在,可能已被删除。"), - format!("Plugin “{id}” does not exist; it may have been deleted.") + format!("Plugin “{id}” does not exist; it may have been deleted."); + format!("外掛「{id}」不存在,可能已被刪除。"), )) }) } @@ -339,7 +343,8 @@ async fn confirmed(app: &tauri::AppHandle, ask: words::Ask) -> Out { confirm::ask(app, ask).await.map_err(|confirm::Busy| { CmdError::plain(tr!( "另一个确认窗口尚未关闭。", - "Another confirmation dialog is still open." + "Another confirmation dialog is still open."; + "另一個確認視窗尚未關閉。", )) }) } @@ -347,7 +352,8 @@ async fn confirmed(app: &tauri::AppHandle, ask: words::Ask) -> Out { fn changed_meanwhile() -> CmdError { CmdError::plain(tr!( "插件文件在确认过程中再次被改动,请重新打开审核窗口。", - "The plugin file changed again during the review. Open the review again." + "The plugin file changed again during the review. Open the review again."; + "外掛檔案在確認過程中再次被改動,請重新開啟稽核視窗。", )) } diff --git a/src-tauri/src/plugins/words.rs b/src-tauri/src/plugins/words.rs index bfb7f51b..bdb15675 100644 --- a/src-tauri/src/plugins/words.rs +++ b/src-tauri/src/plugins/words.rs @@ -28,26 +28,35 @@ pub struct Ask { /// 一项权限允许做的事 pub fn permission_text(p: Permission) -> &'static str { match p { - Permission::System => tr!("读取和修改系统提示词", "Read and change the system prompt"), + Permission::System => tr!( + "读取和修改系统提示词", + "Read and change the system prompt"; + "讀取和修改系統提示詞", + ), Permission::Messages => tr!( "读取和修改对话消息中的文字和工具结果(可以向对话中加入指令)", - "Read and change the text and tool results in conversation messages (can add instructions to the conversation)" + "Read and change the text and tool results in conversation messages (can add instructions to the conversation)"; + "讀取和修改對話訊息中的文字和工具結果(可以向對話中加入指令)", ), Permission::Tools => tr!( "读取和修改工具定义(会改变模型可用的工具)", - "Read and change tool definitions (changes which tools the model can use)" + "Read and change tool definitions (changes which tools the model can use)"; + "讀取和修改工具定義(會改變模型可用的工具)", ), Permission::Params => tr!( "读取和修改模型名、max_tokens、温度等参数(可能改变发给上游的模型和产生的费用)", - "Read and change the model, max_tokens, temperature and other parameters (may change the model sent upstream and what it costs)" + "Read and change the model, max_tokens, temperature and other parameters (may change the model sent upstream and what it costs)"; + "讀取和修改模型名、max_tokens、溫度等引數(可能改變發給上游的模型和產生的費用)", ), Permission::ReplyText => tr!( "读取和修改回答中的文字", - "Read and change the text of replies" + "Read and change the text of replies"; + "讀取和修改回答中的文字", ), Permission::ReplyToolCalls => tr!( "修改、删除和新增回答中的工具调用。高风险:可以改写客户端将要执行的命令和文件路径", - "Change, remove and add tool calls in replies. High risk: can rewrite the commands and file paths a client is about to run" + "Change, remove and add tool calls in replies. High risk: can rewrite the commands and file paths a client is about to run"; + "修改、刪除和新增回答中的工具呼叫。高風險:可以改寫用戶端將要執行的命令和檔案路徑", ), } } @@ -55,9 +64,17 @@ pub fn permission_text(p: Permission) -> &'static str { /// 一种请求在界面上的叫法 pub fn kind_text(k: RequestKind) -> &'static str { match k { - RequestKind::Conversation => tr!("对话", "conversations"), + RequestKind::Conversation => tr!( + "对话", + "conversations"; + "對話", + ), RequestKind::Embeddings => tr!("向量化", "embeddings"), - RequestKind::Completions => tr!("补全", "completions"), + RequestKind::Completions => tr!( + "补全", + "completions"; + "補全", + ), } } @@ -75,9 +92,17 @@ pub fn requests_line(kinds: &[RequestKind]) -> Option { } let list = extra.join(tr!("、", ", ")); Some(if kinds.contains(&RequestKind::Conversation) { - tr!(format!("也处理:{list}"), format!("Also handles: {list}")) + tr!( + format!("也处理:{list}"), + format!("Also handles: {list}"); + format!("也處理:{list}"), + ) } else { - tr!(format!("仅处理:{list}"), format!("Handles only: {list}")) + tr!( + format!("仅处理:{list}"), + format!("Handles only: {list}"); + format!("僅處理:{list}"), + ) }) } @@ -200,7 +225,11 @@ impl ScopePart { fn text(self) -> &'static str { match self { - ScopePart::Clients => tr!("客户端", "clients"), + ScopePart::Clients => tr!( + "客户端", + "clients"; + "用戶端", + ), ScopePart::Models => tr!("模型", "models"), ScopePart::Upstreams => tr!("上游", "upstreams"), } @@ -232,7 +261,12 @@ fn scope_line(scope: &PluginScope) -> String { .map(|p| format!("{} {}", p.text(), list_text(p.of(scope)))) .collect(); if parts.is_empty() { - tr!("全部请求", "all requests").to_string() + tr!( + "全部请求", + "all requests"; + "全部請求", + ) + .to_string() } else { parts.join(tr!(";", "; ")) } @@ -241,7 +275,8 @@ fn scope_line(scope: &PluginScope) -> String { fn check_line() -> &'static str { tr!( "请核对 SHA-256 与应用中显示的一致。", - "Check that the SHA-256 matches the one shown in the app." + "Check that the SHA-256 matches the one shown in the app."; + "請核對 SHA-256 與應用中顯示的一致。", ) } @@ -267,19 +302,37 @@ pub fn install( scope_line(scope), sha_prefix(sha256), check_line() - ) + ); + format!( + "此外掛可以:\n{can}\n\n適用範圍:{}\nSHA-256:{}\n\n{}", + scope_line(scope), + sha_prefix(sha256), + check_line() + ), ); Ask { - title: tr!("安装插件", "Install Plugin").to_string(), + title: tr!( + "安装插件", + "Install Plugin"; + "安裝外掛", + ) + .to_string(), message: tr!( format!("安装插件「{name}」"), - format!("Install Plugin “{name}”") + format!("Install Plugin “{name}”"); + format!("安裝外掛「{name}」"), ), detail, - accept: tr!("安装", "Install").to_string(), + accept: tr!( + "安装", + "Install"; + "安裝", + ) + .to_string(), ok_hint: tr!( "选择「确定」安装此插件。", - "Choose OK to install the plugin." + "Choose OK to install the plugin."; + "選擇「確定」安裝此外掛。", ) .to_string(), danger: perms.contains(&Permission::ReplyToolCalls), @@ -294,7 +347,8 @@ fn renamed(current: &str, next: &str) -> String { } tr!( format!("新代码中的名称:「{next}」\n\n"), - format!("Name in the new code: “{next}”\n\n") + format!("Name in the new code: “{next}”\n\n"); + format!("新程式碼中的名稱:「{next}」\n\n"), ) } @@ -325,17 +379,39 @@ pub fn approve( sha_prefix(from), sha_prefix(to), check_line() - ) + ); + format!( + "{renamed}更改後的檔案可以:\n{can}\n\nSHA-256:{} → {}\n\n{}", + sha_prefix(from), + sha_prefix(to), + check_line() + ), ); Ask { - title: tr!("确认文件更改", "Approve File Changes").to_string(), + title: tr!( + "确认文件更改", + "Approve File Changes"; + "確認檔案更改", + ) + .to_string(), message: tr!( format!("确认插件「{name}」的文件更改"), - format!("Approve the Changed File of Plugin “{name}”") + format!("Approve the Changed File of Plugin “{name}”"); + format!("確認外掛「{name}」的檔案更改"), ), detail, - accept: tr!("确认", "Approve").to_string(), - ok_hint: tr!("选择「确定」确认更改。", "Choose OK to approve the change.").to_string(), + accept: tr!( + "确认", + "Approve"; + "確認", + ) + .to_string(), + ok_hint: tr!( + "选择「确定」确认更改。", + "Choose OK to approve the change."; + "選擇「確定」確認更改。", + ) + .to_string(), danger: perms.contains(&Permission::ReplyToolCalls), } } @@ -369,8 +445,18 @@ pub enum Change { /// 一个设置的值写给人看:开关是「开 / 关」,数照原样,字只取一小段 pub fn setting_value(v: &tw_api::SettingValue) -> String { match v { - tw_api::SettingValue::Bool(true) => tr!("开", "on").to_string(), - tw_api::SettingValue::Bool(false) => tr!("关", "off").to_string(), + tw_api::SettingValue::Bool(true) => tr!( + "开", + "on"; + "開", + ) + .to_string(), + tw_api::SettingValue::Bool(false) => tr!( + "关", + "off"; + "關", + ) + .to_string(), tw_api::SettingValue::Number(n) if n.fract() == 0.0 && n.abs() < 1e15 => { format!("{}", *n as i64) } @@ -381,15 +467,33 @@ pub fn setting_value(v: &tw_api::SettingValue) -> String { fn on_error_text(o: OnError) -> &'static str { match o { - OnError::Reject => tr!("拒绝这次请求", "Reject the request"), - OnError::Skip => tr!("跳过此插件", "Skip this plugin"), + OnError::Reject => tr!( + "拒绝这次请求", + "Reject the request"; + "拒絕這次請求", + ), + OnError::Skip => tr!( + "跳过此插件", + "Skip this plugin"; + "跳過此外掛", + ), } } fn change_line(c: &Change) -> String { match c { - Change::TurnOn => tr!("启用此插件", "Turn on the plugin").to_string(), - Change::TurnOff => tr!("停用此插件", "Turn off the plugin").to_string(), + Change::TurnOn => tr!( + "启用此插件", + "Turn on the plugin"; + "啟用此外掛", + ) + .to_string(), + Change::TurnOff => tr!( + "停用此插件", + "Turn off the plugin"; + "停用此外掛", + ) + .to_string(), Change::Code { from, to } => tr!( format!( "修改代码(SHA-256:{} → {})", @@ -400,7 +504,12 @@ fn change_line(c: &Change) -> String { "Change the code (SHA-256: {} → {})", sha_prefix(from), sha_prefix(to) - ) + ); + format!( + "修改程式碼(SHA-256:{} → {})", + sha_prefix(from), + sha_prefix(to) + ), ), Change::OnError { from, to } => tr!( format!("出错时:{} → {}", on_error_text(*from), on_error_text(*to)), @@ -408,7 +517,8 @@ fn change_line(c: &Change) -> String { "On error: {} → {}", on_error_text(*from), on_error_text(*to) - ) + ); + format!("出錯時:{} → {}", on_error_text(*from), on_error_text(*to)), ), Change::Scope { part, from, to } => tr!( format!( @@ -422,13 +532,20 @@ fn change_line(c: &Change) -> String { part.text(), list_text(from), list_text(to) - ) + ); + format!( + "適用範圍({}):{} → {}", + part.text(), + list_text(from), + list_text(to) + ), ), Change::Setting { label, from, to } => { let label = clean_name(label); tr!( format!("设置「{label}」:{from} → {to}"), - format!("Setting “{label}”: {from} → {to}") + format!("Setting “{label}”: {from} → {to}"); + format!("設定「{label}」:{from} → {to}"), ) } } @@ -473,35 +590,59 @@ pub fn save( }; let detail = tr!( format!("{renamed}本次改动:\n{changes_text}\n\n此插件可以:\n{can}{check}"), - format!("{renamed}Changes:\n{changes_text}\n\nThis plugin can:\n{can}{check}") + format!("{renamed}Changes:\n{changes_text}\n\nThis plugin can:\n{can}{check}"); + format!("{renamed}本次改動:\n{changes_text}\n\n此外掛可以:\n{can}{check}"), ); Ask { - title: tr!("确认插件改动", "Confirm Plugin Changes").to_string(), + title: tr!( + "确认插件改动", + "Confirm Plugin Changes"; + "確認外掛改動", + ) + .to_string(), message: if only_on { tr!( format!("启用插件「{name}」"), - format!("Turn On Plugin “{name}”") + format!("Turn On Plugin “{name}”"); + format!("啟用外掛「{name}」"), ) } else { tr!( format!("保存插件「{name}」"), - format!("Save Plugin “{name}”") + format!("Save Plugin “{name}”"); + format!("儲存外掛「{name}」"), ) }, detail, accept: if only_on { - tr!("启用", "Turn On").to_string() + tr!( + "启用", + "Turn On"; + "啟用", + ) + .to_string() } else { - tr!("保存", "Save").to_string() + tr!( + "保存", + "Save"; + "儲存", + ) + .to_string() }, ok_hint: if only_on { tr!( "选择「确定」启用此插件。", - "Choose OK to turn on the plugin." + "Choose OK to turn on the plugin."; + "選擇「確定」啟用此外掛。", ) .to_string() } else { - tr!("选择「确定」保存改动。", "Choose OK to save the changes.").to_string() + tr!( + "选择「确定」保存改动。", + "Choose OK to save the changes."; + "選擇「確定」儲存改動。", + ) + .to_string() }, danger: perms.contains(&Permission::ReplyToolCalls) || previous.is_none_or(|p| p.contains(&Permission::ReplyToolCalls)), diff --git a/src-tauri/src/portable.rs b/src-tauri/src/portable.rs index 06d455d4..240e6cd9 100644 --- a/src-tauri/src/portable.rs +++ b/src-tauri/src/portable.rs @@ -132,7 +132,8 @@ fn refusal_text(why: &Refusal) -> (&'static str, String) { let extract = || -> String { tr!( "请将 ThinkWatch Lite 解压到可写入的位置后再运行。", - "Extract ThinkWatch Lite to a writable location and run it again." + "Extract ThinkWatch Lite to a writable location and run it again."; + "請將 ThinkWatch Lite 解壓到可寫入的位置後再執行。", ) .into() }; @@ -140,18 +141,24 @@ fn refusal_text(why: &Refusal) -> (&'static str, String) { Refusal::NoFolder => ( tr!( "无法确定程序所在的文件夹", - "The program folder could not be determined" + "The program folder could not be determined"; + "無法確定程式所在的資料夾", ), extract(), ), Refusal::NotWritable => ( - tr!("当前文件夹没有写入权限", "This folder is not writable"), + tr!( + "当前文件夹没有写入权限", + "This folder is not writable"; + "當前資料夾沒有寫入許可權", + ), extract(), ), Refusal::OtherAccount(data) => ( tr!( "数据文件夹属于另一个 Windows 账户", - "The data folder belongs to another Windows account" + "The data folder belongs to another Windows account"; + "資料資料夾屬於另一個 Windows 賬戶", ), tr!( format!( @@ -161,7 +168,11 @@ fn refusal_text(why: &Refusal) -> (&'static str, String) { format!( "The current account cannot access {}. Take ownership of the folder on its Properties › Security page and run ThinkWatch Lite again, or extract ThinkWatch Lite to a new location.", data.display() - ) + ); + format!( + "當前賬戶無法訪問 {}。可在該資料夾屬性的「安全」頁取得所有權後再執行,或將 ThinkWatch Lite 解壓到新的位置。", + data.display() + ), ), ), } @@ -176,7 +187,11 @@ fn refuse(why: &Refusal) -> ! { "ThinkWatch Lite", instruction, &content, - &[tr!("确定", "OK")], + &[tr!( + "确定", + "OK"; + "確定", + )], ); std::process::exit(1); } @@ -356,7 +371,8 @@ pub fn unpack(zip: &[u8]) -> Result { let unreadable = |e| { tr!( format!("无法打开更新包:{e}"), - format!("The update package could not be opened: {e}") + format!("The update package could not be opened: {e}"); + format!("無法開啟更新包:{e}"), ) }; let mut archive = zip::ZipArchive::new(std::io::Cursor::new(zip)).map_err(unreadable)?; @@ -373,14 +389,16 @@ pub fn unpack(zip: &[u8]) -> Result { format!("更新包中应恰好有 {APP_EXE} 和 {CORE_EXE} 两个文件,实际为:{list}"), format!( "The update package should hold exactly {APP_EXE} and {CORE_EXE}; it holds: {list}" - ) + ); + format!("更新包中應恰好有 {APP_EXE} 和 {CORE_EXE} 兩個檔案,實際為:{list}"), )); } let mut read = |name: &str| -> Result, String> { let unreadable = |e: &dyn std::fmt::Display| { tr!( format!("无法读取更新包中的 {name}:{e}"), - format!("{name} could not be read from the update package: {e}") + format!("{name} could not be read from the update package: {e}"); + format!("無法讀取更新包中的 {name}:{e}"), ) }; let mut entry = archive.by_name(name).map_err(|e| unreadable(&e))?; @@ -393,7 +411,8 @@ pub fn unpack(zip: &[u8]) -> Result { if !bytes.starts_with(b"MZ") { return Err(tr!( format!("更新包中的 {name} 不是可执行文件"), - format!("{name} in the update package is not an executable") + format!("{name} in the update package is not an executable"); + format!("更新包中的 {name} 不是可執行檔案"), )); } Ok(bytes) @@ -441,7 +460,8 @@ pub fn swap_in(files: &[(PathBuf, &[u8])]) -> Result<(), String> { if let Err(e) = swap_one(target, bytes, &mut moved) { let e = tr!( format!("无法替换 {}:{e}", target.display()), - format!("{} could not be replaced: {e}", target.display()) + format!("{} could not be replaced: {e}", target.display()); + format!("無法替換 {}:{e}", target.display()), ); return Err(match roll_back(&moved) { Ok(()) => e, @@ -449,7 +469,8 @@ pub fn swap_in(files: &[(PathBuf, &[u8])]) -> Result<(), String> { tracing::error!("更新没换成,改回原来的文件也失败了:{r}"); tr!( format!("{e};未能还原原来的文件:{r}"), - format!("{e}; the previous files could not be restored: {r}") + format!("{e}; the previous files could not be restored: {r}"); + format!("{e};未能還原原來的檔案:{r}"), ) } }); diff --git a/src-tauri/src/prefs.rs b/src-tauri/src/prefs.rs index 98a9870c..8698c0b5 100644 --- a/src-tauri/src/prefs.rs +++ b/src-tauri/src/prefs.rs @@ -217,7 +217,8 @@ pub async fn change(f: impl FnOnce(&mut Prefs) + Send + 'static) -> crate::error saved.map_err(|e| { crate::error::CmdError::from(tr!( format!("无法保存设置:{e:#}"), - format!("The setting could not be saved: {e:#}") + format!("The setting could not be saved: {e:#}"); + format!("無法儲存設定:{e:#}"), )) }) } @@ -427,7 +428,7 @@ mod tests { let (_tmp, dir) = tmp(); std::fs::write( prefs_path(&dir), - br#"{"check_updates":"no","language":"ja","theme":1,"zoom":120,"hotkey":"Shift+H","notices":"off","menubar":"icon"}"#, + br#"{"check_updates":"no","language":"fr","theme":1,"zoom":120,"hotkey":"Shift+H","notices":"off","menubar":"icon"}"#, ) .unwrap(); let p = load(&dir); @@ -485,11 +486,11 @@ mod tests { let (_tmp, dir) = tmp(); update(&dir, |p| p.language = Some(Lang::En)).unwrap(); let mut before = std::fs::File::open(prefs_path(&dir)).unwrap(); - update(&dir, |p| p.language = Some(Lang::Zh)).unwrap(); + update(&dir, |p| p.language = Some(Lang::Ja)).unwrap(); let mut text = String::new(); before.read_to_string(&mut text).unwrap(); assert!(text.contains(r#""language": "en""#), "{text}"); - assert_eq!(load(&dir).language, Some(Lang::Zh)); + assert_eq!(load(&dir).language, Some(Lang::Ja)); let files: Vec<_> = std::fs::read_dir(&dir) .unwrap() .map(|e| e.unwrap().file_name()) diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 3418574e..8045e3e8 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -196,7 +196,8 @@ pub async fn set_hotkey(app: tauri::AppHandle, combo: Option) -> if !hotkey::supported() { return Err(tr!( "当前桌面环境不支持全局快捷键", - "Global shortcuts are not supported on this desktop" + "Global shortcuts are not supported on this desktop"; + "當前桌面環境不支援全域性快捷鍵", ) .into()); } @@ -204,12 +205,14 @@ pub async fn set_hotkey(app: tauri::AppHandle, combo: Option) -> c.check().map_err(|e| match e { hotkey::Invalid::Key => tr!( "这个键不能用作快捷键", - "This key cannot be used in a shortcut" + "This key cannot be used in a shortcut"; + "這個鍵不能用作快捷鍵", ) .to_string(), hotkey::Invalid::NoModifier => tr!( format!("须包含 Ctrl、Alt 或 {META} 中的至少一个"), - format!("The shortcut must include Ctrl, Alt or {META}") + format!("The shortcut must include Ctrl, Alt or {META}"); + format!("須包含 Ctrl、Alt 或 {META} 中的至少一個"), ), })?; } @@ -222,7 +225,8 @@ pub async fn set_hotkey(app: tauri::AppHandle, combo: Option) -> tracing::debug!("呼出快捷键注册不上:{e}"); tr!( "该组合键已被其他程序占用,请换一个", - "This shortcut is already used by another app. Choose another one." + "This shortcut is already used by another app. Choose another one."; + "該組合鍵已被其他程式佔用,請換一個", ) })?; let saved = prefs::change(move |p| p.hotkey = hotkey::Setting(combo)).await; @@ -296,7 +300,8 @@ pub fn set_autostart(app: tauri::AppHandle, on: bool) -> Out { if !autostart::allowed_in_this_build() { return Err(tr!( "开发构建不支持开机启动", - "Launch at login is not available in development builds" + "Launch at login is not available in development builds"; + "開發構建不支援開機啟動", ) .into()); } @@ -323,7 +328,8 @@ pub fn set_autostart(app: tauri::AppHandle, on: bool) -> Out { std::fs::create_dir_all(dir).map_err(|e| { tr!( format!("无法创建目录 {}:{e}", dir.display()), - format!("The directory {} could not be created: {e}", dir.display()) + format!("The directory {} could not be created: {e}", dir.display()); + format!("無法建立目錄 {}:{e}", dir.display()), ) })?; } @@ -401,43 +407,54 @@ pub(crate) fn maybe_notify_first_autostart(app: &tauri::AppHandle) { let (title, body) = ( tr!( "ThinkWatch 已在通知区域运行", - "ThinkWatch Is Running in the Notification Area" + "ThinkWatch Is Running in the Notification Area"; + "ThinkWatch 已在通知區域執行", ), tr!( "开机时已自动启动。窗口关闭后,应用仍在通知区域中运行。", - "It started at login. When the window is closed, the app keeps running in the notification area." + "It started at login. When the window is closed, the app keeps running in the notification area."; + "開機時已自動啟動。視窗關閉後,應用仍在通知區域中執行。", ), ); #[cfg(target_os = "linux")] let (title, body) = ( tr!( "ThinkWatch 已在系统托盘运行", - "ThinkWatch Is Running in the System Tray" + "ThinkWatch Is Running in the System Tray"; + "ThinkWatch 已在系統托盤執行", ), tr!( "开机时已自动启动。窗口关闭后,应用仍在系统托盘中运行。", - "It started at login. When the window is closed, the app keeps running in the system tray." + "It started at login. When the window is closed, the app keeps running in the system tray."; + "開機時已自動啟動。視窗關閉後,應用仍在系統托盤中執行。", ), ); // 菜单栏设成不显示时,那里没有它:说怎么回到窗口 #[cfg(target_os = "macos")] let (title, body) = if menubar::style() == menubar::Style::Hidden { ( - tr!("ThinkWatch 已在后台运行", "ThinkWatch Is Running"), + tr!( + "ThinkWatch 已在后台运行", + "ThinkWatch Is Running"; + "ThinkWatch 已在後臺執行", + ), tr!( "开机时已自动启动。再次打开 ThinkWatch Lite 即可显示主窗口。", - "It started at login. Open ThinkWatch Lite again to show the main window." + "It started at login. Open ThinkWatch Lite again to show the main window."; + "開機時已自動啟動。再次開啟 ThinkWatch Lite 即可顯示主視窗。", ), ) } else { ( tr!( "ThinkWatch 已在菜单栏运行", - "ThinkWatch Is Running in the Menu Bar" + "ThinkWatch Is Running in the Menu Bar"; + "ThinkWatch 已在選單欄執行", ), tr!( "开机时已自动启动。窗口关闭后,应用仍在菜单栏中运行。", - "It started at login. When the window is closed, the app keeps running in the menu bar." + "It started at login. When the window is closed, the app keeps running in the menu bar."; + "開機時已自動啟動。視窗關閉後,應用仍在選單欄中執行。", ), ) }; diff --git a/src-tauri/src/single.rs b/src-tauri/src/single.rs index a94dadd6..6209d0e4 100644 --- a/src-tauri/src/single.rs +++ b/src-tauri/src/single.rs @@ -99,7 +99,11 @@ const TITLE: &str = "ThinkWatch Lite"; pub(crate) fn running_text() -> &'static str { tr!( "ThinkWatch Lite 已在运行", - "ThinkWatch Lite is already running" + "ThinkWatch Lite is already running", + "ThinkWatch Lite はすでに実行中です"; + "ThinkWatch Lite 已在執行", + "ThinkWatch Lite is already running", + "ThinkWatch Lite ya está funcionando", ) } @@ -111,14 +115,35 @@ pub(crate) fn ask_text(running: &str) -> (&'static str, String, [&'static str; 2 format!("运行中的程序位于:{running}。同一时间只能运行一个 ThinkWatch Lite。"), format!( "The running program is at {running}. Only one ThinkWatch Lite can run at a time." - ) + ), + format!( + "実行中のアプリは {running} にあります。同時に実行できる ThinkWatch Lite は 1 つです。" + ); + format!("執行中的程式位於:{running}。同一時間只能執行一個 ThinkWatch Lite。"), + format!( + "The running program is at {running}. Only one ThinkWatch Lite can run at a time." + ), + format!( + "El programa en ejecución está en {running}. Sólo un ThinkWatch Lite puede ejecutarse a la vez." + ), ), [ tr!( "停止运行中的程序并启动此程序", - "Stop the running program and start this one" + "Stop the running program and start this one", + "実行中のアプリを終了してこちらを起動"; + "停止執行中的程式並啟動此程式", + "Stop the running program and start this one", + "Detener el programa en ejecución y comenzar este", + ), + tr!( + "取消", + "Cancel", + "キャンセル"; + "取消", + "취소", + "Cancelar", ), - tr!("取消", "Cancel"), ], ) } @@ -127,7 +152,11 @@ pub(crate) fn ask_text(running: &str) -> (&'static str, String, [&'static str; 2 pub(crate) fn waiting_text() -> &'static str { tr!( "正在等待进行中的请求完成…", - "Waiting for requests in progress to finish…" + "Waiting for requests in progress to finish…", + "処理中のリクエストの完了を待っています…"; + "正在等待進行中的請求完成…", + "Waiting for requests in progress to finish…", + "Esperando peticiones en curso para terminar…", ) } @@ -135,7 +164,11 @@ pub(crate) fn waiting_text() -> &'static str { pub(crate) fn unsupported_text() -> &'static str { tr!( "运行中的程序不支持切换,请先退出该程序。", - "The running program does not support switching. Quit it first." + "The running program does not support switching. Quit it first.", + "実行中のアプリは切り替えに対応していません。先に終了してください。"; + "執行中的程式不支援切換,請先退出該程式。", + "The running program does not support switching. Quit it first.", + "El programa en ejecución no es compatible con el cambio.", ) } @@ -143,7 +176,11 @@ pub(crate) fn unsupported_text() -> &'static str { pub(crate) fn elevated_text() -> &'static str { tr!( "运行中的程序以管理员身份运行,无法从此处停止。请先退出该程序。", - "The running program runs as administrator and cannot be stopped from here. Quit it first." + "The running program runs as administrator and cannot be stopped from here. Quit it first.", + "実行中のアプリは管理者権限で動作しています。そのアプリを終了してから再試行してください。"; + "執行中的程式以管理員身份執行,無法從此處停止。請先退出該程式。", + "The running program runs as administrator and cannot be stopped from here. Quit it first.", + "El programa en ejecución se ejecuta como administrador y no se puede detener desde aquí.", ) } @@ -151,7 +188,11 @@ pub(crate) fn elevated_text() -> &'static str { pub(crate) fn timeout_text() -> &'static str { tr!( "运行中的程序未能退出。", - "The running program did not quit." + "The running program did not quit.", + "実行中のアプリを終了できませんでした。"; + "執行中的程式未能退出。", + "The running program did not quit.", + "El programa en ejecución no se retiró.", ) } @@ -274,7 +315,18 @@ mod imp { /// 说一句话,只有一个「确定」 fn tell(content: &str) { - dialog::show(TITLE, running_text(), content, &[tr!("确定", "OK")]); + dialog::show( + TITLE, + running_text(), + content, + &[tr!( + "确定", + "OK"; + "確定", + "OK", + "OK", + )], + ); } /// 打开一把已经在的命名锁(只要能等它的权限)。打不开时是系统给的错误码:不在是 diff --git a/src-tauri/src/supervisor/mod.rs b/src-tauri/src/supervisor/mod.rs index 279f8de2..9e0a3fa0 100644 --- a/src-tauri/src/supervisor/mod.rs +++ b/src-tauri/src/supervisor/mod.rs @@ -146,13 +146,31 @@ pub enum CoreState { /// 权限」这种能照着去做的话。 fn why_not(e: &std::io::Error) -> String { match e.kind() { - std::io::ErrorKind::NotFound => tr!("文件不存在", "the file does not exist").into(), - std::io::ErrorKind::PermissionDenied => { - tr!("没有执行权限", "it is not allowed to run").into() - } + std::io::ErrorKind::NotFound => tr!( + "文件不存在", + "the file does not exist", + "ファイルが存在しません"; + "檔案不存在", + "the file does not exist", + "el archivo no existe", + ) + .into(), + std::io::ErrorKind::PermissionDenied => tr!( + "没有执行权限", + "it is not allowed to run", + "実行権限がありません"; + "沒有執行許可權", + "it is not allowed to run", + "no está permitido correr", + ) + .into(), _ if e.raw_os_error() == Some(libc::ENOEXEC) => tr!( "不是这台电脑能运行的程序", - "it is not a program this computer can run" + "it is not a program this computer can run", + "この端末で実行できないプログラムです"; + "不是這臺電腦能執行的程式", + "it is not a program this computer can run", + "no es un programa que este equipo puede ejecutar", ) .into(), _ => { @@ -464,13 +482,15 @@ impl Supervisor { | CoreState::SafeMode { pid: None } => { anyhow::bail!(tr!( "core 正在启动,请稍后再试", - "Core is starting; try again in a moment" + "Core is starting; try again in a moment", + "core を起動しています。しばらくしてから再試行してください" )) } CoreState::Stopped | CoreState::Exited { .. } | CoreState::Failed { .. } => { anyhow::bail!(tr!( "core 未运行,无法重启", - "Core is not running and cannot be restarted" + "Core is not running and cannot be restarted", + "core は停止しているため再起動できません" )) } }; @@ -487,7 +507,8 @@ impl Supervisor { self.intentional.store(false, Ordering::SeqCst); anyhow::bail!(tr!( "core 没有响应,未能重启", - "Core did not respond and was not restarted" + "Core did not respond and was not restarted", + "core が応答しなかったため再起動できませんでした" )); } Ok(()) @@ -507,13 +528,15 @@ impl Supervisor { CoreState::Starting | CoreState::Restarting { .. } | CoreState::SafeMode { .. } => { anyhow::bail!(tr!( "core 正在启动,请稍后再试", - "Core is starting; try again in a moment" + "Core is starting; try again in a moment", + "core を起動しています。しばらくしてから再試行してください" )) } CoreState::Stopped | CoreState::Exited { .. } | CoreState::Failed { .. } => { anyhow::bail!(tr!( "core 未运行,无法重启", - "Core is not running and cannot be restarted" + "Core is not running and cannot be restarted", + "core は停止しているため再起動できません" )) } }; @@ -776,7 +799,10 @@ impl Supervisor { self.set(CoreState::Failed { reason: tr!( format!("无法运行 {path}:{why}"), - format!("{path} could not be run: {why}") + format!("{path} could not be run: {why}"); + format!("無法執行 {path}:{why}"), + format!("{path} could not be run: {why}"), + format!("{path} no pudo ejecutarse: {why}"), ), }); return Err(e.into()); diff --git a/src-tauri/src/supervisor/tests.rs b/src-tauri/src/supervisor/tests.rs index b5c0cc3d..17708cce 100644 --- a/src-tauri/src/supervisor/tests.rs +++ b/src-tauri/src/supervisor/tests.rs @@ -498,7 +498,7 @@ async fn a_safe_mode_core_that_exits_reports_what_it_said() { let bin = { let bin = dir.join("fake-core"); let script = format!( - "#!/bin/sh\n[ \"$1\" = {WARM} ] && exit 0\necho 'Error: loading /x/config.yaml' >&2\necho '' >&2\necho 'Caused by:' >&2\necho ' 已有 twcore 实例正在运行(pid 7)。' >&2\nexit 1\n" + "#!/bin/sh\n[ \"$1\" = {WARM} ] && exit 0\necho 'Error: loading /x/config.yaml' >&2\necho '' >&2\necho 'Caused by:' >&2\necho ' A twcore instance is already running (PID 7).' >&2\nexit 1\n" ); std::fs::write(&bin, script).unwrap(); use std::os::unix::fs::PermissionsExt; @@ -528,7 +528,7 @@ async fn a_safe_mode_core_that_exits_reports_what_it_said() { assert!(reason.starts_with("loading /x/config.yaml\n"), "{reason}"); #[cfg(unix)] assert!( - reason.ends_with("已有 twcore 实例正在运行(pid 7)。"), + reason.ends_with("A twcore instance is already running (PID 7)."), "{reason}" ); } diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs index 7a0fa573..a0cf233f 100644 --- a/src-tauri/src/sync.rs +++ b/src-tauri/src/sync.rs @@ -84,11 +84,13 @@ pub fn wanted(b: &SyncView) -> Said { "1 Sync Conflict".to_string() } else { format!("{n} Sync Conflicts") - } + }; + format!("同步有 {n} 項衝突"), ), tr!( "本机与其他设备将同一对象修改为不同内容。处理之前,本机保留当前内容。", - "This device and another one changed the same item in different ways. Until it is resolved, this device keeps its own version." + "This device and another one changed the same item in different ways. Until it is resolved, this device keeps its own version."; + "本機與其他裝置將同一物件修改為不同內容。處理之前,本機保留當前內容。", ) .to_string(), ), @@ -102,11 +104,16 @@ pub fn wanted(b: &SyncView) -> Said { let said: Option<(&'static str, String, String)> = match b.state { SyncState::Unreachable => Some(( "sync:unreachable", - tr!("无法连接同步位置", "Sync Location Unreachable").to_string(), + tr!( + "无法连接同步位置", + "Sync Location Unreachable"; + "無法連線同步位置", + ).to_string(), if why.is_empty() { tr!( "恢复后自动继续,本机的修改在恢复后上传。", - "Syncing continues once it is reachable again; changes made on this device are uploaded then." + "Syncing continues once it is reachable again; changes made on this device are uploaded then."; + "恢復後自動繼續,本機的修改在恢復後上傳。", ) .to_string() } else { @@ -114,16 +121,22 @@ pub fn wanted(b: &SyncView) -> Said { format!("{why}。恢复后自动继续,本机的修改在恢复后上传。"), format!( "{why}. Syncing continues once it is reachable again; changes made on this device are uploaded then." - ) + ); + format!("{why}。恢復後自動繼續,本機的修改在恢復後上傳。"), ) }, )), SyncState::AuthFailed => Some(( "sync:auth", - tr!("同步位置拒绝访问", "Sync Location Denied Access").to_string(), + tr!( + "同步位置拒绝访问", + "Sync Location Denied Access"; + "同步位置拒絕訪問", + ).to_string(), tr!( "请在设置中修改同步位置的连接参数。", - "Change the sync location's connection details in Settings." + "Change the sync location's connection details in Settings."; + "請在設定中修改同步位置的連線引數。", ) .to_string(), )), @@ -131,21 +144,28 @@ pub fn wanted(b: &SyncView) -> Said { "sync:locked", tr!( "同步口令已在其他设备上更改", - "Sync Passphrase Changed on Another Device" + "Sync Passphrase Changed on Another Device"; + "同步口令已在其他裝置上更改", ) .to_string(), tr!( "在设置中输入新的同步口令后继续同步。", - "Enter the new sync passphrase in Settings to continue syncing." + "Enter the new sync passphrase in Settings to continue syncing."; + "在設定中輸入新的同步口令後繼續同步。", ) .to_string(), )), SyncState::TooNew => Some(( "sync:too_new", - tr!("同步已暂停", "Sync Paused").to_string(), + tr!( + "同步已暂停", + "Sync Paused"; + "同步已暫停", + ).to_string(), tr!( "其他设备使用较新版本,更新 ThinkWatch Lite 后继续同步。", - "Another device uses a newer version. Update ThinkWatch Lite to continue syncing." + "Another device uses a newer version. Update ThinkWatch Lite to continue syncing."; + "其他裝置使用較新版本,更新 ThinkWatch Lite 後繼續同步。", ) .to_string(), )), @@ -153,31 +173,43 @@ pub fn wanted(b: &SyncView) -> Said { "sync:keyring", tr!( "同步位置上的同步密钥不可用", - "Sync Key at the Sync Location Unavailable" + "Sync Key at the Sync Location Unavailable"; + "同步位置上的同步金鑰不可用", ) .to_string(), tr!( "同步已暂停。在设置中重新上传本机配置,或停止同步。", - "Syncing is paused. Upload this device's configuration again in Settings, or stop syncing." + "Syncing is paused. Upload this device's configuration again in Settings, or stop syncing."; + "同步已暫停。在設定中重新上傳本機配置,或停止同步。", ) .to_string(), )), SyncState::Emptied => Some(( "sync:emptied", - tr!("同步位置为空", "Sync Location Empty").to_string(), + tr!( + "同步位置为空", + "Sync Location Empty"; + "同步位置為空", + ).to_string(), tr!( "同步已暂停。在设置中重新上传本机配置,或停止同步。", - "Syncing is paused. Upload this device's configuration again in Settings, or stop syncing." + "Syncing is paused. Upload this device's configuration again in Settings, or stop syncing."; + "同步已暫停。在設定中重新上傳本機配置,或停止同步。", ) .to_string(), )), SyncState::Misconfigured => Some(( "sync:misconfigured", - tr!("同步设置无法使用", "Sync Settings Unusable").to_string(), + tr!( + "同步设置无法使用", + "Sync Settings Unusable"; + "同步設定無法使用", + ).to_string(), if why.is_empty() { tr!( "请在设置中修改同步位置的连接参数或出站代理。", - "Change the sync location's connection details or outbound proxy in Settings." + "Change the sync location's connection details or outbound proxy in Settings."; + "請在設定中修改同步位置的連線引數或出站代理。", ) .to_string() } else { @@ -185,7 +217,8 @@ pub fn wanted(b: &SyncView) -> Said { format!("{why}。请在设置中修改同步位置的连接参数或出站代理。"), format!( "{why}. Change the sync location's connection details or outbound proxy in Settings." - ) + ); + format!("{why}。請在設定中修改同步位置的連線引數或出站代理。"), ) }, )), @@ -298,14 +331,16 @@ fn restart_needed(client: &str, name: &str) -> Signal { Level::Warning, tr!( format!("{name} 的网关密钥已更新"), - format!("“{name}” Gateway Key Updated") + format!("“{name}” Gateway Key Updated"); + format!("{name} 的閘道器金鑰已更新"), ), ) .body(tr!( format!("网关密钥经同步或恢复更换,已写入 {name} 的配置。重新启动 {name} 后生效。"), format!( "The gateway key changed through sync or a restore and has been written to {name}'s configuration. Restart {name} for it to take effect." - ) + ); + format!("閘道器金鑰經同步或恢復更換,已寫入 {name} 的配置。重新啟動 {name} 後生效。"), )) .view("clients") .event() @@ -319,14 +354,16 @@ fn rewrite_failed(client: &str, name: &str, why: &Msg) -> Signal { Level::Warning, tr!( format!("未能更新 {name} 的网关密钥"), - format!("Gateway Key Not Updated for “{name}”") + format!("Gateway Key Not Updated for “{name}”"); + format!("未能更新 {name} 的閘道器金鑰"), ), ) .body(tr!( format!("网关密钥经同步或恢复更换,但未能写入 {name} 的配置:{why}。"), format!( "The gateway key changed through sync or a restore, but it could not be written to {name}'s configuration: {why}." - ) + ); + format!("閘道器金鑰經同步或恢復更換,但未能寫入 {name} 的配置:{why}。"), )) .view("clients") .event() @@ -481,7 +518,8 @@ pub async fn pick_sync_folder( if state.link.is_remote() { return Err(tr!( "连接远程 core 时,同步文件夹是服务器上的路径,请手动填写。", - "With a remote core, the sync folder is a path on the server; type it in." + "With a remote core, the sync folder is a path on the server; type it in."; + "連線遠端 core 時,同步資料夾是伺服器上的路徑,請手動填寫。", ) .into()); } @@ -495,7 +533,8 @@ pub async fn pick_sync_folder( let picked = rx.await.map_err(|_| { tr!( "无法打开选择文件夹的对话框。", - "The folder dialog could not be opened." + "The folder dialog could not be opened."; + "無法開啟選擇資料夾的對話方塊。", ) })?; let Some(picked) = picked else { @@ -504,7 +543,8 @@ pub async fn pick_sync_folder( let path = picked.into_path().map_err(|e| { tr!( format!("无法使用所选的文件夹:{e}"), - format!("The chosen folder cannot be used: {e}") + format!("The chosen folder cannot be used: {e}"); + format!("無法使用所選的資料夾:{e}"), ) })?; Ok(Some(path.display().to_string())) diff --git a/src-tauri/src/uninstall.rs b/src-tauri/src/uninstall.rs index 129569a6..2c4f575e 100644 --- a/src-tauri/src/uninstall.rs +++ b/src-tauri/src/uninstall.rs @@ -125,7 +125,14 @@ fn restore_all_in( ok: r.is_ok(), skipped: false, detail: match r { - Ok(_) => tr!("已还原", "Restored").to_string(), + Ok(_) => tr!( + "已还原", + "Restored"; + "已還原", + "Restored", + "Restored", + ) + .to_string(), Err(e) => crate::core_text::text(&e), }, warning: None, @@ -141,7 +148,10 @@ fn restore_all_in( skipped: true, detail: tr!( "由另一个 ThinkWatch Lite 接管,需在接管它的 ThinkWatch Lite 中还原", - "Connected by another ThinkWatch Lite. Restore it from the ThinkWatch Lite that connected it" + "Connected by another ThinkWatch Lite. Restore it from the ThinkWatch Lite that connected it"; + "由另一個 ThinkWatch Lite 接管,需在接管它的 ThinkWatch Lite 中還原", + "Connected by another ThinkWatch Lite. Restore it from the ThinkWatch Lite that connected it", + "Conectado por otro ThinkWatch Lite. Restaurarlo desde el ThinkWatke Lite que lo conectó", ) .to_string(), warning: None, @@ -185,7 +195,10 @@ pub fn restore_steps(restored: Vec) -> (Vec, bool ok: r.ok, text: tr!( format!("{}:{}", r.client, detail), - format!("{}: {}", r.client, detail) + format!("{}: {}", r.client, detail); + format!("{}:{}", r.client, detail), + format!("{}: {}", r.client, detail), + format!("{}: {}", r.client, detail), ), } }) @@ -228,7 +241,10 @@ pub fn drop_data( if !drop_data { return UninstallStep::done(tr!( format!("数据目录已保留:{}", dir.display()), - format!("Data directory kept: {}", dir.display()) + format!("Data directory kept: {}", dir.display()); + format!("資料目錄已保留:{}", dir.display()), + format!("Data directory kept: {}", dir.display()), + format!("Directorio de datos mantenido: {}", dir.display()), )); } if !restored_all { @@ -240,20 +256,44 @@ pub fn drop_data( format!( "Data directory kept: {}. Some clients above could not be restored, and their backups are in it; delete it once they are sorted out.", dir.display() - ) + ); + format!( + "資料目錄已保留:{}。上面有用戶端沒能還原,它們的備份在這個目錄裡;處理好之後再刪除它", + dir.display() + ), + format!( + "Data directory kept: {}. Some clients above could not be restored, and their backups are in it; delete it once they are sorted out.", + dir.display() + ), + format!( + "Directorio de datos mantenido: {}. Algunos clientes anteriores no pudieron ser restaurados, y sus copias de seguridad están en él; eliminarlo una vez que se hayan resuelto.", + dir.display() + ), )); } match remove_retrying(dir, keep, retry) { Ok(()) => UninstallStep::done(tr!( format!("数据目录已删除:{}", dir.display()), - format!("Data directory deleted: {}", dir.display()) + format!("Data directory deleted: {}", dir.display()); + format!("資料目錄已刪除:{}", dir.display()), + format!("Data directory deleted: {}", dir.display()), + format!("Directorio de datos eliminado: {}", dir.display()), )), Err(e) => UninstallStep::failed(tr!( format!("未能删除数据目录:{}({e})", dir.display()), format!( "The data directory could not be deleted: {} ({e})", dir.display() - ) + ); + format!("未能刪除資料目錄:{}({e})", dir.display()), + format!( + "The data directory could not be deleted: {} ({e})", + dir.display() + ), + format!( + "El directorio de datos no pudo ser eliminado: {} ({e})", + dir.display() + ), )), } } @@ -316,20 +356,29 @@ pub fn last_line() -> String { #[cfg(target_os = "macos")] let last = tr!( "现可将应用移到废纸篓。", - "The app can now be moved to the Trash." + "The app can now be moved to the Trash."; + "現可將應用移到廢紙簍。", + "The app can now be moved to the Trash.", + "La aplicación ahora se puede mover a la Papelera.", ) .into(); #[cfg(windows)] let last = if crate::portable::is_portable() { tr!( "卸载步骤已完成,现可删除整个文件夹。", - "Uninstall steps are complete. The whole folder can now be deleted." + "Uninstall steps are complete. The whole folder can now be deleted."; + "解除安裝步驟已完成,現可刪除整個資料夾。", + "Uninstall steps are complete. The whole folder can now be deleted.", + "Los pasos de desinstalación están completos. Toda la carpeta ahora se puede eliminar.", ) .into() } else { tr!( "现可卸载或删除应用。", - "The app can now be uninstalled or deleted." + "The app can now be uninstalled or deleted."; + "現可解除安裝或刪除應用。", + "The app can now be uninstalled or deleted.", + "La aplicación ahora se puede desinstalar o eliminar.", ) .into() }; @@ -337,9 +386,19 @@ pub fn last_line() -> String { let last = match crate::desktop_entry::appimage() { Some(file) => tr!( format!("现可删除 AppImage 文件:{}", file.display()), - format!("The AppImage file can now be deleted: {}", file.display()) + format!("The AppImage file can now be deleted: {}", file.display()); + format!("現可刪除 AppImage 檔案:{}", file.display()), + format!("The AppImage file can now be deleted: {}", file.display()), + format!("El archivo AppImage ahora se puede eliminar: {}", file.display()), ), - None => tr!("现可删除应用。", "The app can now be deleted.").into(), + None => tr!( + "现可删除应用。", + "The app can now be deleted."; + "現可刪除應用。", + "The app can now be deleted.", + "La aplicación ahora se puede eliminar.", + ) + .into(), }; last } @@ -367,7 +426,10 @@ pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out log.push(UninstallStep::done(tr!( "已取消开机启动", - "Launch at login turned off" + "Launch at login turned off"; + "已取消開機啟動", + "Launch at login turned off", + "Lanzar al iniciar sesión apagado", ))), // 退路按平台说:自启项在哪儿、用户去哪儿关,各不相同 #[cfg(target_os = "macos")] @@ -377,7 +439,16 @@ pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out Out Out log.extend(crate::winreg::release_all(&exe)), Err(e) => log.push(UninstallStep::failed(tr!( format!("未能确定程序位置,注册项未清理({e})"), - format!("The program location could not be determined, so its registry entries were left in place ({e})") + format!("The program location could not be determined, so its registry entries were left in place ({e})"); + format!("未能確定程式位置,註冊項未清理({e})"), + format!("The program location could not be determined, so its registry entries were left in place ({e})"), + format!("La ubicación del programa no se pudo determinar, por lo que sus entradas de registro se dejaron en su lugar ({e})"), ))), } // AppImage 每次启动写的菜单条目和图标(见 `desktop_entry`)。删不掉的 diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs index 3246fd30..9887064f 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -314,12 +314,14 @@ pub fn appimage_failure(e: &tauri_plugin_updater::Error) -> String { format!("无法写入 AppImage 所在的位置,更新未安装。新版本可从 {RELEASES_URL} 下载。"), format!( "The location of the AppImage is not writable, so the update was not installed. The new version can be downloaded from {RELEASES_URL}." - ) + ); + format!("無法寫入 AppImage 所在的位置,更新未安裝。新版本可從 {RELEASES_URL} 下載。"), ) } else { tr!( format!("安装失败:{e}"), - format!("Installation failed: {e}") + format!("Installation failed: {e}"); + format!("安裝失敗:{e}"), ) } } @@ -336,7 +338,8 @@ pub fn portable_failure(e: &str) -> String { format!("更新未安装:{e}。新版本可从 {RELEASES_URL} 下载。"), format!( "The update was not installed: {e}. The new version can be downloaded from {RELEASES_URL}." - ) + ); + format!("更新未安裝:{e}。新版本可從 {RELEASES_URL} 下載。"), ) } diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs index e0d8d971..26aef5df 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/updater.rs @@ -54,6 +54,25 @@ pub async fn set_update_check(app: tauri::AppHandle, on: bool) -> Out, + en: Option, +} + +impl ReleaseNotes { + fn from_manifest(zh: Option, raw: &serde_json::Value) -> Self { + // Tauri 已读了标准的 notes(中文),英文在同一份清单的附加字段里。 + let en = raw + .get("notes_en") + .and_then(|v| v.as_str()) + .map(str::to_owned); + Self { zh, en } + } } /// 更新在内存里的那点状态。 @@ -69,6 +88,7 @@ pub struct Updates { #[derive(serde::Serialize)] pub struct OfferView { version: String, + notes: ReleaseNotes, current: String, install: update::Install, /// Homebrew 那一档要执行的命令。**由这里给出,界面上不再写一遍** —— @@ -78,11 +98,12 @@ pub struct OfferView { /// 读发布页上的清单:最新的那一版比现在新吗。 /// -/// 读的是一份几百字节的 JSON,不下载任何别的东西。 -pub(crate) async fn look(app: &tauri::AppHandle) -> Result, String> { +/// 只读清单,不下载安装包。 +async fn look(app: &tauri::AppHandle) -> Result, String> { let found = updater(app)?.check().await.map_err(|e| e.to_string())?; Ok(found.map(|up| Found { - version: up.version.clone(), + version: up.version, + notes: ReleaseNotes::from_manifest(up.body, &up.raw_json), })) } @@ -148,16 +169,34 @@ async fn ask(app: &tauri::AppHandle) -> Result, String> { let Some(version) = update::cask_version(&cask) else { return Err(tr!( "无法从 Homebrew cask 中读取版本号", - "The version number could not be read from the Homebrew cask" + "The version number could not be read from the Homebrew cask", + "Homebrew cask からバージョン番号を読み取れませんでした"; + "無法從 Homebrew cask 中讀取版本號", + "The version number could not be read from the Homebrew cask", + "El número de versión no se pudo leer en el barril de Homebrew", ) .into()); }; if !update::newer(version, ¤t) { return Ok(None); } - Ok(Some(Found { + // 发布说明是附带信息:取不到时仍提示用户更新。只等一小会儿,以免拖慢检查。 + let release = tokio::time::timeout(std::time::Duration::from_secs(3), look(app)) + .await + .ok() + .and_then(Result::ok) + .flatten(); + Ok(Some(brew_offer(version, release))) +} + +fn brew_offer(version: &str, release: Option) -> Found { + Found { version: version.to_string(), - })) + notes: release + .filter(|r| r.version == version) + .map(|r| r.notes) + .unwrap_or_default(), + } } pub(crate) const UPDATE_WINDOW: &str = "update"; @@ -182,7 +221,14 @@ pub(crate) fn show_update_window(app: &tauri::AppHandle) -> tauri::Result<()> { return crate::window::reveal(app, &w); } let b = WebviewWindowBuilder::new(app, UPDATE_WINDOW, WebviewUrl::default()) - .title(tr!("软件更新", "Software Update")) + .title(tr!( + "软件更新", + "Software Update", + "ソフトウェアアップデート"; + "軟體更新", + "소프트웨어 업데이트", + "Actualización de software", + )) .initialization_script(i18n::init_script()) // 高度先随便给一个:网页画完量出内容有多高,再由 `update_fit` 定下来。 // 宽度按界面大小放大(见 `window::fit`) @@ -298,10 +344,21 @@ fn update_signal(version: &str) -> notices::Signal { notices::Level::Info, tr!( format!("ThinkWatch Lite {version} 可用"), - format!("ThinkWatch Lite {version} Is Available") + format!("ThinkWatch Lite {version} Is Available"), + format!("ThinkWatch Lite {version} を利用できます"); + format!("ThinkWatch Lite {version} 可用"), + format!("ThinkWatch Lite {version}을(를) 사용할 수 있습니다"), + format!("ThinkWatch Lite {version} está disponible"), ), ) - .body(tr!("点按此提醒进行更新。", "Click to update.")) + .body(tr!( + "点按此提醒进行更新。", + "Click to update.", + "クリックして更新します。"; + "點按此提醒進行更新。", + "클릭하여 업데이트하세요.", + "Haz clic para actualizar.", + )) .tell() .now() } @@ -354,7 +411,11 @@ pub async fn update_show(app: tauri::AppHandle) -> Out<()> { if pending_update(&app).is_none() { return Err(tr!( "尚无可安装的新版本", - "No new version is waiting to be installed" + "No new version is waiting to be installed", + "インストールできる新しいバージョンはありません"; + "尚無可安裝的新版本", + "설치할 새 버전이 없습니다.", + "No hay ninguna versión nueva para instalar.", ) .into()); } @@ -368,6 +429,7 @@ pub fn update_pending(app: tauri::AppHandle) -> Option { let install = update::kind(); Some(OfferView { version: found.version, + notes: found.notes, current: app.package_info().version.to_string(), install, command: (install == update::Install::Homebrew).then_some(update::BREW_UPGRADE), @@ -489,18 +551,42 @@ pub async fn update_install( format!( "This app is managed by Homebrew. Run this command in Terminal: {}", update::BREW_UPGRADE - ) + ); + format!( + "此應用由 Homebrew 管理,請在終端中執行:{}", + update::BREW_UPGRADE + ), + format!( + "This app is managed by Homebrew. Run this command in Terminal: {}", + update::BREW_UPGRADE + ), + format!( + "Esta aplicación es administrada por Homebrew. Ejecute este comando en Terminal: {}", + update::BREW_UPGRADE + ), ) .into(), _ => tr!( "开发构建不执行自动更新", - "Development builds do not update automatically" + "Development builds do not update automatically", + "開発ビルドでは自動更新を利用できません"; + "開發構建不執行自動更新", + "Development builds do not update automatically", + "Las construcciones de desarrollo no se actualizan automáticamente", ) .into(), }); } if hub.installing.swap(true, Ordering::SeqCst) { - return Err(tr!("更新正在进行中", "An update is already in progress").into()); + return Err(tr!( + "更新正在进行中", + "An update is already in progress", + "更新はすでに進行中です"; + "更新正在進行中", + "이미 업데이트 중입니다.", + "Ya hay una actualización en curso.", + ) + .into()); } // 中途失败要把标记放回去,否则再点一次会被当成「已经在进行中」 struct Release<'a>(&'a std::sync::atomic::AtomicBool); @@ -515,7 +601,17 @@ pub async fn update_install( .check() .await .map_err(|e| e.to_string())? - .ok_or_else(|| tr!("已是最新版本", "Already up to date").to_string())?; + .ok_or_else(|| { + tr!( + "已是最新版本", + "Already up to date", + "最新バージョンです"; + "已是最新版本", + "이미 최신 버전입니다.", + "Ya está al día.", + ) + .to_string() + })?; let _ = app.emit("update-step", Step::Downloading); let h = app.clone(); @@ -527,7 +623,16 @@ pub async fn update_install( || {}, ) .await - .map_err(|e| tr!(format!("下载失败:{e}"), format!("Download failed: {e}")))?; + .map_err(|e| { + tr!( + format!("下载失败:{e}"), + format!("Download failed: {e}"), + format!("ダウンロードに失敗しました:{e}"); + format!("下載失敗:{e}"), + format!("다운로드 실패: {e}"), + format!("Error al descargar: {e}"), + ) + })?; // 绿色版不跑安装程序,自己换文件夹里的两个 exe —— 见 `install_portable` #[cfg(windows)] if install == update::Install::Portable { @@ -541,7 +646,11 @@ pub async fn update_install( .map_err(|e| { tr!( format!("无法打开更新包:{e}"), - format!("The update could not be opened: {e}") + format!("The update could not be opened: {e}"), + format!("更新パッケージを開けませんでした:{e}"); + format!("無法開啟更新包:{e}"), + format!("The update could not be opened: {e}"), + format!("No se pudo abrir la actualización: {e}"), ) })?; @@ -565,7 +674,11 @@ pub async fn update_install( install_blocking(up, bytes).await?.map_err(|e| { tr!( format!("安装失败:{e}"), - format!("Installation failed: {e}") + format!("Installation failed: {e}"), + format!("インストールに失敗しました:{e}"); + format!("安裝失敗:{e}"), + format!("설치 실패: {e}"), + format!("Error al instalar: {e}"), ) })?; hand_over_or_stop(&app, &state).await; @@ -690,7 +803,11 @@ async fn install_windows( } Err(tr!( format!("安装失败:{e}"), - format!("Installation failed: {e}") + format!("Installation failed: {e}"), + format!("インストールに失敗しました:{e}"); + format!("安裝失敗:{e}"), + format!("설치 실패: {e}"), + format!("Error al instalar: {e}"), ) .into()) } @@ -915,10 +1032,21 @@ fn updated_notice(from: &str, now: &str, mode: notices::Mode) -> Option<(String, return None; } Some(( - tr!(format!("已更新到 {now}"), format!("Updated to {now}")), + tr!( + format!("已更新到 {now}"), + format!("Updated to {now}"), + format!("{now} に更新しました"); + format!("已更新到 {now}"), + format!("{now}(으)로 업데이트했습니다"), + format!("Se actualizó a {now}"), + ), tr!( format!("ThinkWatch Lite 已从 {from} 更新到 {now}。"), - format!("ThinkWatch Lite was updated from {from} to {now}.") + format!("ThinkWatch Lite was updated from {from} to {now}."), + format!("ThinkWatch Lite を {from} から {now} に更新しました。"); + format!("ThinkWatch Lite 已從 {from} 更新到 {now}。"), + format!("ThinkWatch Lite를 {from}에서 {now}(으)로 업데이트했습니다."), + format!("ThinkWatch Lite se actualizó de {from} a {now}."), ), )) } @@ -962,6 +1090,54 @@ mod tests { use crate::i18n::{Lang, with_lang}; use notices::Mode; + #[test] + fn release_notes_read_both_languages_from_the_same_manifest() { + let manifest = serde_json::json!({ + "version": "2026.11.20", + "notes": "修复路由", + "notes_en": "Fixed routing", + "platforms": {}, + }); + let release: tauri_plugin_updater::RemoteRelease = + serde_json::from_value(manifest.clone()).unwrap(); + let notes = ReleaseNotes::from_manifest(release.notes, &manifest); + assert_eq!(notes.zh.as_deref(), Some("修复路由")); + assert_eq!(notes.en.as_deref(), Some("Fixed routing")); + } + + #[test] + fn older_or_malformed_manifests_can_still_offer_an_update() { + for manifest in [serde_json::json!({}), serde_json::json!({ "notes_en": 42 })] { + let notes = ReleaseNotes::from_manifest(Some("修复路由".into()), &manifest); + assert_eq!(notes.zh.as_deref(), Some("修复路由")); + assert_eq!(notes.en, None); + } + } + + #[test] + fn brew_uses_notes_only_for_the_version_in_the_cask() { + let release = Found { + version: "2026.11.20".into(), + notes: ReleaseNotes { + zh: Some("修复路由".into()), + en: Some("Fixed routing".into()), + }, + }; + let matching = brew_offer("2026.11.20", Some(release.clone())); + assert_eq!(matching.notes.zh.as_deref(), Some("修复路由")); + assert_eq!(matching.notes.en.as_deref(), Some("Fixed routing")); + + let behind = brew_offer("2026.11.19", Some(release)); + assert_eq!(behind.version, "2026.11.19"); + assert_eq!(behind.notes.zh, None); + assert_eq!(behind.notes.en, None); + + let unavailable = brew_offer("2026.11.20", None); + assert_eq!(unavailable.version, "2026.11.20"); + assert_eq!(unavailable.notes.zh, None); + assert_eq!(unavailable.notes.en, None); + } + /// 「已更新到 x」和别的告知同一个开关:**只在「系统通知」那一档弹** #[test] fn the_updated_notice_follows_the_notification_setting() { @@ -1140,6 +1316,24 @@ mod tests { }); } + #[test] + fn japanese_update_notice_uses_japanese_copy() { + with_lang(Lang::Ja, || { + let (n, shown) = bus(Mode::System); + tell_update(&n, "2026.10.8"); + assert_eq!( + *shown.0.lock().unwrap(), + ["ThinkWatch Lite 2026.10.8 を利用できます"] + ); + assert_eq!( + updated_notice("2026.10.7", "2026.10.8", Mode::System) + .unwrap() + .1, + "ThinkWatch Lite を 2026.10.7 から 2026.10.8 に更新しました。" + ); + }); + } + /// 只在应用内:进列表,不弹 #[tokio::test] async fn in_app_only_lists_the_new_version() { diff --git a/src-tauri/src/webview2.rs b/src-tauri/src/webview2.rs index b9c6b0c4..d44176a6 100644 --- a/src-tauri/src/webview2.rs +++ b/src-tauri/src/webview2.rs @@ -33,13 +33,22 @@ fn refuse() -> ! { "ThinkWatch Lite", tr!( "缺少 Microsoft Edge WebView2 运行时", - "The Microsoft Edge WebView2 Runtime is missing" + "The Microsoft Edge WebView2 Runtime is missing"; + "缺少 Microsoft Edge WebView2 執行時", ), tr!( "ThinkWatch Lite 无法启动。", - "ThinkWatch Lite cannot start." + "ThinkWatch Lite cannot start."; + "ThinkWatch Lite 無法啟動。", ), - &[tr!("前往下载", "Download"), tr!("退出", "Quit")], + &[ + tr!( + "前往下载", + "Download"; + "前往下載", + ), + tr!("退出", "Quit"), + ], ); if picked == Some(0) && let Err(e) = tauri_plugin_opener::open_url(DOWNLOAD, None::<&str>) diff --git a/src-tauri/src/winreg.rs b/src-tauri/src/winreg.rs index 846550fd..ba0f43fb 100644 --- a/src-tauri/src/winreg.rs +++ b/src-tauri/src/winreg.rs @@ -390,11 +390,13 @@ mod imp { out.push(match removed { Ok(()) => UninstallStep::done(tr!( "已移除 thinkwatch:// 链接", - "thinkwatch:// links unregistered" + "thinkwatch:// links unregistered"; + "已移除 thinkwatch:// 連結", )), Err(e) => UninstallStep::failed(tr!( format!("未能移除 thinkwatch:// 链接({e})"), - format!("thinkwatch:// links could not be unregistered ({e})") + format!("thinkwatch:// links could not be unregistered ({e})"); + format!("未能移除 thinkwatch:// 連結({e})"), )), }); } @@ -406,7 +408,8 @@ mod imp { let other = command_exe(&cmd).unwrap_or(&cmd).to_string(); out.push(UninstallStep::done(tr!( format!("开机启动项指向 {other},未作更改"), - format!("The launch-at-login entry points to {other} and was left unchanged") + format!("The launch-at-login entry points to {other} and was left unchanged"); + format!("開機啟動項指向 {other},未作更改"), ))); return; } @@ -419,12 +422,17 @@ mod imp { Err(e) => Err(e), }; out.push(match removed { - Ok(()) => UninstallStep::done(tr!("已取消开机启动", "Launch at login turned off")), + Ok(()) => UninstallStep::done(tr!( + "已取消开机启动", + "Launch at login turned off"; + "已取消開機啟動", + )), Err(e) => UninstallStep::failed(tr!( format!("未能取消开机启动({e})。请在「设置 › 应用 › 启动」中关闭 ThinkWatch Lite。"), format!( "Launch at login could not be turned off ({e}). Turn off ThinkWatch Lite in Settings › Apps › Startup." - ) + ); + format!("未能取消開機啟動({e})。請在「設定 › 應用 › 啟動」中關閉 ThinkWatch Lite。"), )), }); } @@ -444,11 +452,13 @@ mod imp { out.push(match absent_is_none(hive.remove_tree(&aumid_key(aumid))) { Ok(_) => UninstallStep::done(tr!( "已移除系统通知的登记", - "System notification registration removed" + "System notification registration removed"; + "已移除系統通知的登記", )), Err(e) => UninstallStep::failed(tr!( format!("未能移除系统通知的登记({e})"), - format!("The system notification registration could not be removed ({e})") + format!("The system notification registration could not be removed ({e})"); + format!("未能移除系統通知的登記({e})"), )), }); } @@ -465,7 +475,8 @@ mod imp { format!( "The notification icon could not be deleted: {} ({e})", icon.display() - ) + ); + format!("未能刪除通知圖示:{}({e})", icon.display()), ))), } } diff --git a/src-tauri/src/zai.rs b/src-tauri/src/zai.rs index cd96dcdb..7cc0b2e6 100644 --- a/src-tauri/src/zai.rs +++ b/src-tauri/src/zai.rs @@ -100,7 +100,8 @@ fn pending_url(id: &str) -> Result { .ok_or_else(|| { tr!( "这次登录已经结束,请重新发起", - "This sign-in has ended; start a new one" + "This sign-in has ended; start a new one"; + "這次登入已經結束,請重新發起", ) .to_string() }) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index a4089846..9a8b42eb 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "ThinkWatch Lite", - "version": "2026.11.20", + "version": "2026.11.22", "identifier": "app.thinkwatch.lite", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src-tauri/tests/control_plane.rs b/src-tauri/tests/control_plane.rs index e035ef3f..dfdf7311 100644 --- a/src-tauri/tests/control_plane.rs +++ b/src-tauri/tests/control_plane.rs @@ -164,6 +164,33 @@ async fn the_desktop_side_gets_in_with_the_key_and_not_without() { assert!(e.contains("密钥") || e.contains("key"), "{e}"); } +#[tokio::test] +async fn the_security_catalog_has_stable_ids_and_english_fallbacks() { + let core = Core::start(); + core.wait_ready().await; + let catalog = core + .ok() + .call::(&[], &()) + .await + .unwrap(); + + let rule = catalog + .redact + .rules + .iter() + .find(|r| r.id == "anthropic-api-key") + .unwrap(); + assert_eq!(rule.name, "Anthropic API key"); + assert!(rule.about.starts_with("Starts with")); + let group = catalog + .redact + .kinds + .iter() + .find(|k| k.slug == rule.kind) + .unwrap(); + assert_eq!(group.name, "AI services"); +} + /// 写请求也走同一条握手。 /// /// **读和写是两条代码路径**,2026.9.10 就是只有读的那条带了凭据:界面照常显示 diff --git a/src/App.i18n.tsx b/src/App.i18n.tsx index a0ca13b1..6b712d72 100644 --- a/src/App.i18n.tsx +++ b/src/App.i18n.tsx @@ -109,4 +109,142 @@ export const appText = messages( staleData: (what: string) => `${what} · Data below is as of the disconnect`, restart: "Restart", }, + { + "zh-Hant": { + surfaces: { + dashboard: "概覽", + requests: "流量", + security: "安全", + upstreams: "上游", + routing: "路由", + clients: "用戶端", + keys: "金鑰", + mcp: "MCP", + plugins: "外掛", + settings: "設定", + }, + newFindings: (label: string, n: number) => `${label} · ${n} 項新發現`, + listenStale: (why: string) => `監聽設定未生效:${why}`, + running: "執行中", + starting: "啟動中", + restarting: (attempt: string) => `重啟中(第 ${attempt} 次)`, + restartingShort: "重啟中", + safeMode: "安全模式 · 閘道器未執行", + cannotStart: "無法啟動", + expandRail: "展開源列表", + configFile: "配置檔案", + versionHistory: "備份", + rejectedTitle: "配置校驗未透過,仍在使用上一版本", + rejectedAt: (stage: string, line: number | null) => `${stage}錯誤${line != null ? `(第 ${line} 行)` : ""}:`, + rotatedUnsaved: (provider: string) => `${provider} 已換髮新憑據,但未能寫回 config.yaml。當前轉發正常。`, + oldRevoked: (em: Em) => <>原憑據已在伺服器端失效。{em("重啟前如未處理,該上游的請求將持續返回 401")}。, + staleData: (what: string) => `${what} · 以下資料截至連線斷開時`, + restart: "重新啟動", + }, + ja: { + surfaces: { + dashboard: "概要", + requests: "トラフィック", + security: "セキュリティ", + upstreams: "アップストリーム", + routing: "ルーティング", + clients: "クライアント", + keys: "キー", + mcp: "MCP", + plugins: "プラグイン", + settings: "設定", + }, + newFindings: (label: string, n: number) => `${label} · 新規検出 ${n} 件`, + listenStale: (why: string) => `リッスン設定を適用できませんでした:${why}`, + running: "実行中", + starting: "起動中", + restarting: (attempt: string) => `再起動中(${attempt} 回目)`, + restartingShort: "再起動中", + safeMode: "セーフモード · ゲートウェイ停止中", + safeModeShort: "セーフモード", + stopped: "停止中", + cannotStart: "起動できません", + collapseRail: "サイドバーを折りたたむ", + expandRail: "サイドバーを展開", + configFile: "設定ファイル", + versionHistory: "バックアップ", + rejectedTitle: "設定の検証に失敗したため、以前の設定を使用しています", + rejectedAt: (stage: string, line: number | null) => `${stage}エラー${line != null ? `(${line} 行目)` : ""}:`, + rotatedUnsaved: (provider: string) => `${provider} が新しい認証情報を発行しましたが、config.yaml に保存できませんでした。現在、転送は正常に動作しています。`, + oldRevoked: (em: Em) => <>以前の認証情報はサーバーで無効になりました。{em("再起動前に解決しないと、このアップストリームへのリクエストは 401 を返し続けます")}。, + staleData: (what: string) => `${what} · 切断時点のデータを表示しています`, + restart: "再起動", + }, + ko: { + surfaces: { + dashboard: "개요", + requests: "트래픽", + security: "보안", + upstreams: "업스트림", + routing: "라우팅", + clients: "클라이언트", + keys: "키", + mcp: "MCP", + plugins: "플러그인", + settings: "설정", + }, + listenStale: (why: string) => `수신 설정이 적용되지 않았습니다: ${why}`, + running: "실행 중", + starting: "시작 중", + restarting: (attempt: string) => `다시 시작 중(${attempt}번째 시도)`, + restartingShort: "다시 시작 중", + safeMode: "안전 모드 · 게이트웨이 중지됨", + safeModeShort: "안전 모드", + stopped: "중지됨", + cannotStart: "시작할 수 없음", + collapseRail: "사이드바 접기", + expandRail: "사이드바 펼치기", + configFile: "설정 파일", + versionHistory: "백업", + rejectedTitle: "설정 검사에 실패했습니다. 이전 설정을 계속 사용합니다.", + restart: "다시 시작", + newFindings: (label: string, n: number) => `${label} · 새로 발견된 항목 ${n}건`, + rejectedAt: (stage: string, line: number | null) => `${stage} 오류${line != null ? `(${line}번째 줄)` : ""}: `, + rotatedUnsaved: (provider: string) => `${provider}에서 새 인증 정보를 발급했으나 config.yaml에 저장하지 못했습니다. 요청은 정상적으로 전달 중입니다.`, + oldRevoked: (em: Em) => <>이전 인증 정보는 서버에서 이미 만료되었습니다. {em("재시작 전에 문제를 해결하지 않으면 이 업스트림의 요청이 계속 401 오류를 반환합니다")}., + staleData: (what: string) => `${what} · 연결이 끊기기 직전의 데이터입니다`, + }, + es: { + surfaces: { + dashboard: "Resumen", + requests: "Tráfico", + security: "Seguridad", + upstreams: "Proveedores", + routing: "Enrutamiento", + clients: "Clientes", + keys: "Claves", + mcp: "MCP", + plugins: "Complementos", + settings: "Configuración", + }, + newFindings: (label: string, n: number) => `${label} · ${count(n, "Nueva conclusión", "nuevas conclusiones")}`, + listenStale: (why: string) => `No se aplicó la configuración de escucha: ${why}`, + running: "En ejecución", + starting: "Iniciando", + restarting: (attempt: string) => `Reiniciando (intento ${attempt})`, + restartingShort: "Reiniciando", + safeMode: "Modo seguro · Puerta de enlace detenida", + safeModeShort: "Modo seguro", + stopped: "Detenido", + cannotStart: "No se pudo iniciar", + collapseRail: "Contraer la barra lateral", + expandRail: "Expandir la barra lateral", + configFile: "Archivo de configuración", + versionHistory: "Copias de seguridad", + rejectedTitle: "La configuración no es válida. Se sigue usando la configuración anterior.", + rejectedAt: (stage: string, line: number | null) => `${stage} error${line != null ? ` (línea ${line})` : ""}: `, + rotatedUnsaved: (provider: string) => `${provider} emitió nuevas credenciales, pero no pudieron ser escritas de nuevo a config.yaml. La reenvío actualmente funciona normalmente.`, + oldRevoked: (em: Em) => (<> + Las credenciales anteriores ya no son válidas en el servidor.{" "} + {em("A menos que esto se resuelva antes del siguiente reinicio, las solicitudes a este curso anterior seguirán devolviendo 401")}. + ), + staleData: (what: string) => `${what} · Los datos de abajo son de la desconexión`, + restart: "Reiniciar", + }, + }, ); diff --git a/src/ConfigDialogs.i18n.ts b/src/ConfigDialogs.i18n.ts index 7f5a1370..b575524a 100644 --- a/src/ConfigDialogs.i18n.ts +++ b/src/ConfigDialogs.i18n.ts @@ -14,4 +14,21 @@ export const configDialogsText = messages( readingFile: "Reading the config file", fileFailed: "Could not read the config file", }, + { + "zh-Hant": { + fileTitle: "配置檔案", + fileDescription: "儲存前會校驗;校驗未透過時仍使用上一版本。每次儲存都在備份中生成一個版本。", + readingFile: "正在讀取配置檔案", + fileFailed: "配置檔案讀取失敗", + }, + ko: { + fileTitle: "설정 파일", + }, + es: { + fileTitle: "Archivo de configuración", + fileDescription: "Los cambios son validados antes de guardarlos. Si la validación falla, la versión anterior permanece en uso. Cada guardar crea una versión en las copias de seguridad.", + readingFile: "Leyendo el archivo de configuraciónuración", + fileFailed: "No se pudo leer el archivo de configuraciónuración", + }, + }, ); diff --git a/src/ConfigText.i18n.ts b/src/ConfigText.i18n.ts index f30de2f8..259f4b6c 100644 --- a/src/ConfigText.i18n.ts +++ b/src/ConfigText.i18n.ts @@ -61,4 +61,75 @@ export const configTextText = messages( open: "Open Plugins", }, }, + { + "zh-Hant": { + sections: { + providers: "上游", + proxies: "代理", + pricing: "價目表", + clients: "金鑰", + routes: "路由", + groups: "策略組", + default_route: "預設路由", + listen: "監聽", + client_probes: "用戶端探測請求", + security: "防護", + }, + staleTitle: "檔案已被其他程序修改", + staleBody: "此時儲存將覆蓋該程序所做的修改。", + useFile: "放棄本地修改,使用檔案中的版本", + keepMine: "保留本地修改並覆蓋檔案", + cursorAt: (section: string) => `游標位於${section}`, + showInApp: "在介面中檢視", + unsaved: "有未儲存的修改", + pluginConfirm: { + title: "此更改須在外掛頁中確認", + notSaved: (reason: string) => `配置檔案未儲存。${reason}`, + notRestored: (reason: string) => `未恢復此版本。${reason}`, + open: "開啟外掛頁", + }, + }, + ko: { + sections: { + providers: "업스트림", + proxies: "proxy", + pricing: "price sheet", + clients: "key", + routes: "route", + groups: "group", + default_route: "default route", + listen: "listening", + client_probes: "client probes", + security: "protection", + }, + unsaved: "저장하지 않은 변경 사항", + }, + es: { + sections: { + providers: "proveedor", + proxies: "proxy", + pricing: "hoja de precios", + clients: "tecla", + routes: "ruta", + groups: "grupo", + default_route: "ruta predeterminada", + listen: "escuchar", + client_probes: "sondas cliente", + security: "protección", + }, + staleTitle: "El archivo fue cambiado por otro proceso", + staleBody: "Guardar ahora sobrescribe los cambios que el proceso hizo.", + useFile: "Desechar los cambios locales y utilizar la versión en el archivo", + keepMine: "Mantenga los cambios locales y sobrescriba el archivo", + cursorAt: (section: string) => `Cursor en ${section}`, + showInApp: "Mostrar en la aplicación", + unsaved: "Cambios sin guardar", + pluginConfirm: { + title: "Este cambio tiene que ser confirmado en la página Plugins", + notSaved: (reason: string) => `El archivo de configuraciónuración no se ha guardado. ${reason}`, + notRestored: (reason: string) => `Esta versión no fue restaurada. ${reason}`, + open: "Abrir complementos", + }, + }, + }, ); diff --git a/src/KeyLabel.i18n.ts b/src/KeyLabel.i18n.ts index dfa0a773..18b6b1c4 100644 --- a/src/KeyLabel.i18n.ts +++ b/src/KeyLabel.i18n.ts @@ -11,4 +11,12 @@ export const keyLabelText = messages( named: (name: string) => ` (${name})`, bare: (name: string) => `Key ${name}`, }, + { + "zh-Hant": { + bare: (name: string) => `金鑰 ${name}`, + }, + es: { + bare: (name: string) => `Clave ${name}`, + }, + }, ); diff --git a/src/Notices.i18n.ts b/src/Notices.i18n.ts index 9529f3fa..df7f689c 100644 --- a/src/Notices.i18n.ts +++ b/src/Notices.i18n.ts @@ -19,4 +19,40 @@ export const noticesText = messages( read: "Mark as read", readOne: (title: string) => `Mark as read: ${title}`, }, + { + "zh-Hant": { + bell: (unread: number) => (unread > 0 ? `提醒,${unread} 項未讀` : "提醒"), + empty: "暫無提醒", + readAll: "全部已讀", + read: "標為已讀", + readOne: (title: string) => `標為已讀:${title}`, + }, + ja: { + bell: (unread: number) => (unread > 0 ? `通知、未読 ${unread} 件` : "通知"), + title: "通知", + empty: "通知はありません", + clearAll: "すべて消去", + readAll: "すべて既読にする", + read: "既読にする", + readOne: (title: string) => `既読にする:${title}`, + }, + ko: { + bell: (unread: number) => (unread > 0 ? `Notices, ${unread} unread` : "알림"), + title: "알림", + empty: "알림 없음", + clearAll: "모두 지우기", + readAll: "모두 읽음으로 표시", + read: "읽음으로 표시", + readOne: (title: string) => `읽음으로 표시: ${title}`, + }, + es: { + bell: (unread: number) => (unread > 0 ? `Avisos, ${unread} no leídos` : "Avisos"), + title: "Avisos", + empty: "No hay avisos", + clearAll: "Borrar todo", + readAll: "Marcar todo como leído", + read: "Marcar como leído", + readOne: (title: string) => `Marque el texto como sigue: ${title}`, + }, + }, ); diff --git a/src/Update.i18n.ts b/src/Update.i18n.ts index cea65ab7..d02e05a2 100644 --- a/src/Update.i18n.ts +++ b/src/Update.i18n.ts @@ -9,6 +9,7 @@ export const updateText = messages( // 更新窗口 current: (version: string) => `当前版本 ${version}`, available: (version: string) => `ThinkWatch Lite ${version} 可用`, + whatsNew: "本次更新", closeWhileWaiting: "关闭此窗口不影响更新,更新完成后将发送通知。", /** 能在窗口里直接装的那几档(网页下载的、Windows 的绿色版)都是这一句 */ standalone: "下载完成后自动安装并重新启动,进行中的请求不会中断。", @@ -32,6 +33,7 @@ export const updateText = messages( { current: (version: string) => `Current version: ${version}`, available: (version: string) => `ThinkWatch Lite ${version} is available`, + whatsNew: "What's new", closeWhileWaiting: "Closing this window does not stop the update. A notification is sent when it is complete.", standalone: "Installs and restarts automatically after downloading. Requests in progress are not interrupted.", @@ -53,4 +55,86 @@ export const updateText = messages( installing: "Installing", restarting: "Restarting", }, + { + "zh-Hant": { + current: (version: string) => `當前版本 ${version}`, + closeWhileWaiting: "關閉此視窗不影響更新,更新完成後將傳送通知。", + standalone: "下載完成後自動安裝並重新啟動,進行中的請求不會中斷。", + later: "稍後", + install: "下載並安裝", + homebrew: "此應用由 Homebrew 管理,請在終端中執行以下命令完成更新:", + copyFailed: "未能寫入剪貼簿。命令已選中,請按 ⌘C 複製。", + copyCommand: "複製命令", + dev: "當前執行的是開發構建,不執行自動更新。", + downloadingOf: (done: string, total: string) => `正在下載 ${done} / ${total} MB`, + downloading: (done: string) => `正在下載 ${done} MB`, + waiting: (n: number) => `等待 ${n} 個進行中的請求結束`, + installing: "正在安裝", + restarting: "正在重新啟動", + }, + ja: { + current: (version: string) => `現在のバージョン:${version}`, + available: (version: string) => `ThinkWatch Lite ${version} を利用できます`, + whatsNew: "更新内容", + closeWhileWaiting: "このウィンドウを閉じても更新は続行されます。完了すると通知が届きます。", + standalone: "ダウンロード後に自動でインストールして再起動します。処理中のリクエストは中断されません。", + later: "あとで", + install: "ダウンロードしてインストール", + failed: "更新を完了できませんでした", + homebrew: "このアプリは Homebrew で管理されています。ターミナルで次のコマンドを実行して更新してください。", + command: "更新コマンド", + copyFailed: "クリップボードにコピーできませんでした。選択されたコマンドを ⌘C でコピーしてください。", + copyCommand: "コマンドをコピー", + dev: "開発ビルドでは自動更新を利用できません。", + downloadingOf: (done: string, total: string) => `ダウンロード中 ${done} / ${total} MB`, + downloading: (done: string) => `ダウンロード中 ${done} MB`, + waiting: (n: number) => `処理中のリクエスト ${n} 件の完了を待っています`, + installing: "インストール中", + restarting: "再起動中", + }, + ko: { + current: (version: string) => `현재 버전: ${version}`, + available: (version: string) => `ThinkWatch Lite ${version}을(를) 사용할 수 있습니다`, + whatsNew: "업데이트 내용", + closeWhileWaiting: "이 창을 닫아도 업데이트는 계속됩니다. 완료되면 알림을 보냅니다.", + standalone: "다운로드 후 자동으로 설치하고 다시 시작합니다. 진행 중인 요청은 계속 처리됩니다.", + later: "나중에", + install: "다운로드 및 설치", + failed: "업데이트를 완료하지 못했습니다.", + homebrew: "이 앱은 Homebrew에서 관리합니다. 업데이트하려면 터미널에서 다음 명령을 실행하세요.", + command: "업데이트 명령", + copyFailed: "클립보드에 복사할 수 없습니다. 명령이 선택되어 있으니 ⌘C를 눌러 복사하세요.", + copyCommand: "명령 복사", + dev: "개발 빌드는 자동으로 업데이트되지 않습니다.", + downloadingOf: (done: string, total: string) => `다운로드 중 ${done} / ${total} MB`, + downloading: (done: string) => `다운로드 중 ${done} MB`, + waiting: (n: number) => n === 1 + ? "진행 중인 요청 1건의 완료를 기다리는 중" + : `진행 중인 요청 ${n}건의 완료를 기다리는 중`, + installing: "설치 중", + restarting: "다시 시작 중", + }, + es: { + current: (version: string) => `Versión actual: ${version}`, + available: (version: string) => `ThinkWatch Lite ${version} está disponible`, + whatsNew: "Novedades", + closeWhileWaiting: "La actualización continúa si cierras esta ventana. Recibirás un aviso al terminar.", + standalone: "Tras la descarga, la aplicación se instala y reinicia automáticamente. Las solicitudes en curso continúan.", + later: "Más tarde", + install: "Descargar e instalar", + failed: "No se completó la actualización.", + homebrew: "Homebrew gestiona esta aplicación. Para actualizarla, ejecuta este comando en Terminal:", + command: "Comando de actualización", + copyFailed: "No se pudo copiar al portapapeles. Pulsa ⌘C para copiar el comando seleccionado.", + copyCommand: "Copiar comando", + dev: "Las compilaciones de desarrollo no se actualizan automáticamente.", + downloadingOf: (done: string, total: string) => `Descargando ${done} / ${total} MB`, + downloading: (done: string) => `Descargando ${done} MB`, + waiting: (n: number) => n === 1 + ? "Esperando a que termine 1 solicitud en curso" + : `Esperando a que terminen ${n} solicitudes en curso`, + installing: "Instalando", + restarting: "Reiniciando", + }, + }, ); diff --git a/src/UpdateWindow.tsx b/src/UpdateWindow.tsx index b2a1da67..0146261b 100644 --- a/src/UpdateWindow.tsx +++ b/src/UpdateWindow.tsx @@ -10,9 +10,10 @@ import { Meter } from "@/ui/meter"; import { Spinner } from "@/ui/spinner"; import { StatusDot } from "@/ui/status-dot"; import { IconCopied, IconCopy } from "@/ui/icons"; -import { useText } from "@/i18n"; +import { Markdown } from "@/traffic/Markdown"; +import { useLang, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; -import { canInstall, describeStep, type Offer, type Step } from "./updateFlow"; +import { canInstall, describeStep, releaseNotesFor, type Offer, type Step } from "./updateFlow"; import { updateText } from "./Update.i18n"; import { errorText } from "@/i18n/core.i18n"; @@ -26,7 +27,7 @@ const COPIED_MS = 2_000; * 点了自动检查发出的那条通知、菜单里的「安装新版本」。窗口建出来时是隐藏的 —— 这里 * 画好、量出高度之后再亮出来。 * - * 上面是应用图标、哪一版可用、现在是哪一版;下面画哪一种取决于这一份是怎么装上来的: + * 上面是应用图标、哪一版可用、现在是哪一版、本次更新;下面画哪一种取决于这一份是怎么装上来的: * * · 从网页下载的:「下载并安装」,按一次之后不再问任何问题 —— 下载、 * 等网关手上的请求结束、替换、重启,全部自动。 @@ -40,6 +41,7 @@ const COPIED_MS = 2_000; * 内容一边展开、窗口一边一格格地改尺寸,比直接换过去难看。 */ export default function UpdateWindow() { + const lang = useLang(); const t = useText(updateText); const common = useText(commonText); const [offer, setOffer] = useState(null); @@ -93,6 +95,8 @@ export default function UpdateWindow() { void invoke("update_fit", { height }).then(async () => { if (shown.current) return; shown.current = true; + // 先把焦点落在窗口正文。WebKit 激活窗口时就不会选中更新说明或按钮。 + el.focus({ preventScroll: true }); await w.show(); await w.setFocus(); }); @@ -116,6 +120,7 @@ export default function UpdateWindow() { if (!offer) return null; const busy = step !== null && failed === null; + const notes = busy ? null : releaseNotesFor(offer.notes, lang); const install = async () => { setFailed(null); @@ -217,7 +222,7 @@ export default function UpdateWindow() { return (
-
+
{/* 应用图标本身(和程序坞里同一张) */} @@ -226,6 +231,21 @@ export default function UpdateWindow() {

{t.current(offer.current)}

+ {notes && ( +
+

+ {t.whatsNew} +

+
+ +
+
+ )} {content} {actions &&
{actions}
}
diff --git a/src/aliases/AliasDialog.i18n.ts b/src/aliases/AliasDialog.i18n.ts index 45521725..a5d50618 100644 --- a/src/aliases/AliasDialog.i18n.ts +++ b/src/aliases/AliasDialog.i18n.ts @@ -138,4 +138,113 @@ export const aliasDialogText = messages( sep: ", ", }, + { + "zh-Hant": { + createTitle: "新建別名", + editTitle: (name: string) => `編輯別名 ${name}`, + desc: "給模型起一個用戶端用的名稱。原來的名稱照常可用。", + loading: "正在讀取別名", + notFound: (name: string) => `別名 ${name} 已不在配置裡。`, + name: "名稱", + nameHint: "用戶端用這個名稱請求。", + prefilled: (providers: string, name: string) => `${providers} 也有名為 ${name} 的模型,已列為第一個上游模型。`, + shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} 有名為 ${name} 的模型。${creating ? "建這個別名後" : "儲存後"},所有用戶端用 ${name} 請求都會改發給 ${models},不再發給 ${providers}。只想讓某個用戶端這樣用,請在路由裡給它的金鑰寫一條規則,轉發至選「指定模型」。`, + writeRule: "改為寫路由規則…", + claudeCodeReserved: (name: string) => `Claude Code 把 ${name} 當作自己的檔位名,請求前換成完整的模型名,它的請求用不到這個別名。`, + familyMismatch: (family: string, model: string, clients: string) => `名稱像 ${family} 模型,上游模型卻是 ${model}:${clients} 會按 ${family} 模型的格式發出這個名稱的請求,由閘道器轉換後發給上游。`, + desktopHidden: (name: string) => `Claude Desktop 只列出名稱像 Claude 的模型,不會顯示 ${name}。`, + desktopShown: (name: string) => `Claude Desktop 會在模型列表裡顯示 ${name}。`, + renameRefs: (old: string, refs: string) => `改名後,${refs}裡的 ${old} 一起改為新名稱。`, + keysRef: (keys: string) => `金鑰 ${keys} 的可見範圍`, + rulesRef: (rules: string) => `規則 ${rules}`, + modelsPlaceholder: "從上游的模型裡選,或直接輸入", + enterToAdd: "回車新增", + removeShort: "刪除", + remove: (m: string) => `刪除 ${m}`, + unserved: "沒有上游提供", + modelsWhat: "同一模型在各上游的名稱。上游有其中任一名稱,就由它提供;可新增多個。", + modelsUnserved: (n: number) => n === 1 ? "標黃的模型沒有上游提供,請求不會發往它。" : `標黃的 ${n} 個模型沒有上游提供,請求不會發往它們。`, + sameModelWhat: "按名稱認出的,確認是同一個模型再勾選。", + hideOriginals: "用戶端僅展示別名", + hideOriginalsHint: "從用戶端模型列表隱藏對應的上游原名;其他別名不受影響。原名仍可按現有許可權請求,用戶端可能需要重新整理模型列表。", + hideOriginalsUpgrade: "連線的 Core 不支援此設定,請升級 Core。", + hiddenOriginals: (names: string) => `將隱藏的原名:${names}。實際列表仍按協議和金鑰許可權篩選。`, + hiddenOriginalsEmpty: "當前沒有可隱藏的原名。", + sentTo: "發往各上游", + sentHead: (name: string) => `用戶端請求 ${name} 時`, + sentHeadUnnamed: "用戶端請求這個別名時", + notServing: "(不提供,勾選上面一項後提供)", + noLongerReceives: (name: string) => `(不再收到 ${name} 的請求)`, + sentNone: "列出的模型沒有上游提供。", + sentEmpty: "新增上游模型後,這裡列出各上游收到的模型名。", + sentWhat: "請求發往哪個上游由路由決定。", + previewFailed: (reason: string) => `無法預覽:${reason}`, + modelListsUpdate: (clients: string, creating: boolean) => `${creating ? "建立後" : "儲存後"},已接管的 ${clients} 會提示更新模型列表`, + needName: "填寫名稱", + needModels: "新增上游模型", + needOtherName: "新增這個模型在其他上游的名稱", + create: "建立", + renamed: (old: string, name: string) => `已將別名 ${old} 改名為 ${name}`, + renamedIn: (refs: string) => `${refs}裡的名稱已一起更新。`, + }, + ko: { + name: "이름", + removeShort: "제거", + needName: "이름을 입력하세요.", + }, + es: { + createTitle: "Nuevo alias", + editTitle: (name: string) => `Editar alias ${name}`, + desc: "Dele a un modelo un nombre para que los clientes lo usen. Los nombres originales siguen funcionando.", + loading: "Cargando el alias", + notFound: (name: string) => `Alias ${name} ya no está en la configuración.`, + name: "Nombre", + nameHint: "Los clientes solicitan este nombre.", + namePlaceholder: "Por ejemplo, claude-sonnet-5", + prefilled: (providers: string, name: string) => `${providers} también tiene un modelo denominado ${name}; está listado como el primer modelo de del proveedor.`, + shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} tiene un modelo llamado ${name}. ${creating ? "Una vez que este alias existe" : "Una vez guardado"}, cada cliente que solicita ${name} va a ${models} en su lugar, y ${providers} ya no lo recibe. Para hacer esto sólo para un cliente, escriba una regla para su clave en Enrutamiento y reenvíe a "modelos específicos".`, + writeRule: "Escribe una regla de enrutamiento en su lugar…", + claudeCodeReserved: (name: string) => `Claude Code trata ${name} como su propio nombre de nivel y swaps en el nombre completo del modelo antes de solicitar, por lo que sus solicitudes nunca utilizan este alias.`, + familyMismatch: (family: string, model: string, clients: string) => `El nombre se parece a un modelo ${family}, pero el modelo ascendente es ${model}: ${clients} enviará solicitudes para él en el formato ${family}, y la puerta de enlace las convierte para el ascendente.`, + desktopHidden: (name: string) => `Claude Desktop sólo lista modelos cuyos nombres se parecen a Claude, por lo que no se mostrará ${name}.`, + desktopShown: (name: string) => `Claude Desktop mostrará ${name} en su lista de modelos.`, + renameRefs: (old: string, refs: string) => `El renombramiento también cambia ${old} al nuevo nombre en ${refs}.`, + keysRef: (keys: string) => `los modelos visibles de la llave ${keys}`, + rulesRef: (rules: string) => `regla ${rules}`, + refsJoin: " y ", + models: "Modelos ascendentes", + modelsPlaceholder: "Elija entre modelos ascendentes o escriba un nombre", + enterToAdd: "Introduzca para añadir", + removeShort: "Quitar", + remove: (m: string) => `Eliminar ${m}`, + unserved: "No hay del proveedor.", + modelsWhat: "Los nombres del mismo modelo en diferentes del proveedor. Un río arriba que tiene cualquiera de ellos sirve el alias; añadir tantos como sea necesario.", + modelsUnserved: (n: number) => n === 1 + ? "No hay del proveedor sirve el modelo marcado en amarillo; ninguna petición va a él." + : `No hay del proveedor sirve a los ${n} modelos marcados en amarillo; ninguna petición va a ellos.`, + sameModel: "El mismo modelo en otras del proveedor", + sameModelWhat: "Reconocido por nombre. Compruebe uno después de confirmar que es el mismo modelo.", + hideOriginals: "Mostrar sólo el alias en las listas de modelos de clientes", + hideOriginalsHint: "Ocultar los nombres originales mapeados de las listas de modelos de clientes. Otros alias no se ven afectados. Los nombres originales se pueden llamar con los permisos existentes; los clientes pueden necesitar actualizar sus listas de modelo.", + hideOriginalsUpgrade: "El núcleo conectado no admite esta configuración. Actualizar núcleo para usarlo.", + hiddenOriginals: (names: string) => `Nombres originales para ocultar: ${names}. Las listas de clientes siguen aplicando permisos de protocolo y clave.`, + hiddenOriginalsEmpty: "Actualmente no hay nombres originales disponibles para ocultar.", + sentTo: "Enviada a cada río arriba", + sentHead: (name: string) => `Cuando un cliente solicita ${name}`, + sentHeadUnnamed: "Cuando un cliente solicita este alias", + notServing: "(no servido; compruebe la entrada de arriba para servirlo)", + noLongerReceives: (name: string) => `(ya no recibe solicitudes de ${name})`, + sentNone: "No hay del proveedor que sirva a los modelos listados.", + sentEmpty: "Una vez añadidos los modelos ascendentes, el nombre que recibe cada uno de ellos se indica aquí.", + sentWhat: "Enrutamiento decide a qué del proveedor va una solicitud.", + previewFailed: (reason: string) => `Vista previa no disponible: ${reason}`, + modelListsUpdate: (clients: string, creating: boolean) => `${creating ? "Una vez creado" : "Una vez guardado"}, el conectado ${clients} se ofrecerá una actualización de la lista de modelos`, + needName: "Introduce un nombre.", + needModels: "Añadir un modelo ascendente", + needOtherName: "Añadir el nombre de este modelo en otras del proveedor", + create: "Crear", + renamed: (old: string, name: string) => `Alias ${old} renombrado a ${name}`, + renamedIn: (refs: string) => `Actualizado en ${refs} también.`, + }, + }, ); diff --git a/src/aliases/aliases.i18n.ts b/src/aliases/aliases.i18n.ts index 0bde6c81..4ed59661 100644 --- a/src/aliases/aliases.i18n.ts +++ b/src/aliases/aliases.i18n.ts @@ -128,4 +128,89 @@ export const aliasesText = messages( kept: (models: readonly string[]) => `The upstream ${models.length === 1 ? "model" : "models"} ${enList(models)} remain${models.length === 1 ? "s" : ""} available. The alias can be restored from the backups.`, }, + { + "zh-Hant": { + tab: "別名", + tabDot: "有可建為別名的模型", + newAlias: "新建別名", + loadFailed: "別名讀取失敗", + alias: "別名", + aliasOnly: "用戶端僅展示別名", + day: "24 小時", + notOffered: "沒有上游提供這個名稱", + unserved: (models: number): string => models === 1 + ? "沒有上游提供這個模型,使用這個別名的請求會失敗" + : "沒有上游提供列表中的任何一個模型,使用這個別名的請求會失敗", + shadowed: (providers: readonly string[], name: string) => `${providers.join("、")} 也有名為 ${name} 的模型,未列入,不會被使用`, + copyName: "複製名稱", + traffic: "檢視流量", + oneSuggestion: (label: string, providers: readonly string[]) => `${label} 在 ${providers.join("、")} 上的名稱各不相同。建為別名後,這幾個上游可以互為備用。`, + manySuggestions: (n: number) => `${n} 個模型在幾個上游的名稱各不相同。建為別名後,這些上游可以互為備用。`, + createFrom: "建為別名…", + view: "檢視…", + empty: "尚無別名", + emptyDesc: "別名是用戶端使用的一個名稱,指向一個模型。同一個模型在幾個上游的名稱不同時,把這些名稱列在一個別名下,這幾個上游就能互為備用。", + emptySuggestions: "這些模型在幾個上游的名稱不同", + suggestTitle: "同一模型的不同名稱", + suggestDesc: "這些模型在幾個上游的名稱各不相同。建為別名後,這幾個上游可以互為備用。", + suggestScope: "只認 Claude 模型在官方、Bedrock、Vertex、OpenRouter 上的名稱,日期版本不同的不算同一個。", + deleteTitle: (name: string) => `刪除別名「${name}」`, + inUse: "以下地方在用這個名稱。刪除後,使用它的請求會失敗,按它寫的規則和可見範圍不再起作用。", + unused: "刪除後,此別名將從配置檔案中移除。", + usageFailed: (reason: string) => `使用情況讀取失敗:${reason}`, + usedByRequests: (n: number) => `過去 24 小時 ${n.toLocaleString()} 次請求`, + usedByKey: (key: string) => `金鑰「${key}」的可見模型`, + usedByCondition: (route: string, rule: string) => `路由「${route}」· 規則「${rule}」的條件`, + usedByRewrite: (route: string, rule: string) => `路由「${route}」· 規則「${rule}」的模型改寫`, + usedByRule: (route: string, rule: string) => `路由「${route}」· 規則「${rule}」`, + show: "檢視", + kept: (models: readonly string[]) => `上游模型 ${models.join("、")} 照常可用。可從備份中恢復。`, + }, + ko: { + actionsColumn: "작업", + }, + es: { + tab: "Alias", + tabDot: "Algunos modelos podrían convertirse en alias", + newAlias: "Nuevo alias", + loadFailed: "No se pudieron cargar los alias", + aliasOnly: "Alias sólo en las listas de clientes", + models: "Modelos ascendentes", + context: "Contexto", + day: "24 horas", + actionsColumn: "Acciones", + actions: (name: string) => `Acciones en relación con ${name}`, + requests: (n: number) => (n === 1 ? "1 solicitud" : `${n.toLocaleString()} solicitudes`), + notOffered: "Ningún río arriba ofrece este nombre", + unserved: (models: number) => models === 1 + ? "Ningún modelo anterior ofrece este modelo; las solicitudes para este alias fallarán" + : "Ningún modelo anterior ofrece ninguno de estos modelos; las solicitudes para este alias fallarán", + shadowed: (providers: readonly string[], name: string) => `${enList(providers)} también ${providers.length === 1 ? "tiene" : "tener"} un modelo denominado ${name}; no está enumerado, por lo que no se utiliza`, + copyName: "Copiar nombre", + traffic: "Ver tráfico", + oneSuggestion: (label: string, providers: readonly string[]) => `${label} tiene un nombre diferente en cada uno de ${enList(providers)}. Como un alias, estas del proveedor pueden estar el uno para el otro.`, + manySuggestions: (n: number) => `${n} los modelos tienen nombres diferentes en diferentes del proveedor. Como alias, esas del proveedor pueden apoyarse mutuamente.`, + createFrom: "Crear alias…", + view: "Ver…", + ignore: "Desestimar", + empty: "Sin alias", + emptyDesc: "Un alias es un nombre que los clientes usan para un modelo. Cuando un modelo tiene nombres diferentes en diferentes del proveedor, lista esos nombres bajo un alias y los del proveedor pueden estar el uno para el otro.", + emptySuggestions: "Estos modelos tienen nombres diferentes en diferentes del proveedor", + suggestTitle: "Un modelo, nombres diferentes", + suggestDesc: "Estos modelos tienen nombres diferentes en diferentes del proveedor. Como alias, esas del proveedor pueden estar el uno para el otro.", + suggestScope: "Solo se reconocen los nombres de modelos de Claude en Anthropic, Bedrock, Vertex y OpenRouter; los nombres con fechas diferentes cuentan como modelos diferentes.", + deleteTitle: (name: string) => `Suprímase el alias “${name}”`, + inUse: "Este nombre se utiliza en los siguientes lugares. Después de la eliminación, las solicitudes que lo utilizan fallan, y las reglas y listas de modelos visibles que nombre ya no se aplican.", + unused: "Eliminar elimina este alias del archivo de configuraciónuración.", + usageFailed: (reason: string) => `No se pudo cargar donde se utiliza este nombre: ${reason}`, + usedByRequests: (n: number) => n === 1 ? "1 solicitud en las últimas 24 horas" : `${n.toLocaleString()} solicitudes en las últimas 24 horas`, + usedByKey: (key: string) => `Modelos visibles de clave “${key}”`, + usedByCondition: (route: string, rule: string) => `Ruta “${route}” · condición de la regla “${rule}”`, + usedByRewrite: (route: string, rule: string) => `Ruta “${route}” · reescritura del modelo de la regla “${rule}”`, + usedByRule: (route: string, rule: string) => `Ruta “${route}” · regla “${rule}”`, + usedByClients: (names: readonly string[]) => `El modelo ${names.length === 1 ? "lista" : "listas"} de ${enList(names)} (conectado)`, + show: "Mostrar", + kept: (models: readonly string[]) => `El principio ${models.length === 1 ? "modelo" : "modelos"} ${enList(models)} permanece disponible${models.length === 1 ? "s" : ""}. El alias se puede restaurar de las copias de seguridad.`, + }, + }, ); diff --git a/src/backup/backup.i18n.ts b/src/backup/backup.i18n.ts index 487ffb21..a14e095e 100644 --- a/src/backup/backup.i18n.ts +++ b/src/backup/backup.i18n.ts @@ -437,4 +437,410 @@ export const backupText = messages( dropHere: "Drop to import the config pack", }, + { + "zh-Hant": { + heading: "備份", + importConfig: "匯入配置…", + exportConfig: "匯出配置…", + time: "時間", + origin: "來源", + contents: "內容", + current: "當前", + restore: "恢復…", + saveAs: "另存為…", + local: "本機", + counts: (providers: number, plugins: number) => `${providers} 個上游,${plugins} 個外掛`, + keeps: "本機保留最近 10 個版本;同步位置保留最新與上一個版本。", + listFailed: "備份列表讀取失敗", + noBackups: "暫無備份版本", + noBackupsHint: "每次配置變更都會在此生成一個版本。", + dialogTitle: "備份", + dialogDescription: "恢復前列出該版本與當前配置的差異。恢復本身也會生成一個版本,可再次恢復。", + restoreTitle: "從備份恢復", + origins: { + ui: "介面修改", + cli: "命令列", + external: "手動編輯檔案", + defaults: "預設外掛", + sync: "同步", + syncFrom: (device: string) => `同步自 ${device}`, + import: "匯入", + restore: "恢復", + repair: "一鍵修復", + export: "匯出", + share: "分享", + rotation: "憑據輪換", + other: "其他", + }, + kinds: { + provider: "上游", + proxy: "出站代理", + key: "閘道器金鑰", + alias: "別名", + group: "策略組", + route: "路由", + price_sheet: "價目表", + security_rule: "安全規則", + plugin: "外掛", + global: "全域性設定", + provider_order: "上游順序", + route_order: "路由順序", + plugin_order: "外掛順序", + client_prefs: "Lite 通用偏好", + }, + globals: { + failover: "故障轉移", + security: "防護狀態", + default_route: "預設路由", + default_key: "預設金鑰", + client_probes: "輔助請求", + pricing: "價目表設定", + }, + guards: { + redact: "金鑰與隱私", + inspect_tools: "危險命令", + content: "內容過濾", + }, + units: { + conn: "連線", + models: "模型", + billing: "計費", + other: "其他設定", + all: "內容", + script: "指令碼", + settings: "設定", + enabled: "啟用狀態", + }, + exportTitle: "匯出配置", + scope: "範圍", + scopeItems: "選擇專案", + total: (providers: number, keys: number, routes: number, plugins: number) => `${providers} 個上游、${keys} 把閘道器金鑰、${routes} 條路由、${plugins} 個外掛。`, + selected: (n: number) => `已選 ${n} 項。`, + noneSelected: "未選擇專案。", + along: "隨附", + alongTip: "被所選專案引用,隨之匯出", + itemsFailed: "配置專案讀取失敗", + secrets: "包含金鑰", + secretsWhat: "上游金鑰、閘道器金鑰與代理密碼", + encryptWhat: "以口令加密檔案", + encryptHint: "加密後,匯入時需輸入口令。", + passphraseAgain: "再次輸入", + passphraseShort: "口令至少 8 個字元。", + passphraseMismatch: "兩次輸入的口令不一致。", + omitted: "不隨檔案匯出", + omitLogins: (n: number) => `ChatGPT 帳號與 OAuth 的登入憑據(${n} 個上游),匯入後需重新登入或填寫。`, + omitSecrets: "上游金鑰、閘道器金鑰與代理密碼。匯入後上遊為停用狀態,須補填金鑰;閘道器金鑰重新生成。", + omitLocal: "監聽、遠端控制與同步設定。", + omitData: "請求記錄。", + plaintext: "檔案包含明文金鑰,請妥善保管。", + exportAction: "匯出…", + exported: (path: string) => `已匯出到 ${path}`, + importTitle: "匯入配置", + reading: "正在讀取配置包", + readFailed: "無法讀取配置包", + encrypted: "此配置包已加密,須輸入匯出時設定的口令。", + continue: "繼續", + withSecrets: "包含金鑰", + withoutSecrets: "不含金鑰", + exportedBy: (at: string, version: string) => `${at} 由 Core ${version} 匯出`, + countConflict: (n: number) => `衝突 ${n}`, + countError: (n: number) => `錯誤 ${n}`, + overwriteAll: "全部覆蓋", + renameAll: "全部改名匯入", + skipAll: "全部跳過", + name: "名稱", + status: "狀態", + action: "處理", + statusConflict: "衝突", + statusError: "錯誤", + flags: { + missing_key: "缺少金鑰", + needs_login: "需要登入", + plugin_disabled: "外掛", + }, + flagHints: { + missing_key: "匯入後為停用狀態,須補填金鑰", + needs_login: "匯入後為停用狀態,須重新登入", + plugin_disabled: "匯入後為停用狀態;可改寫工具呼叫的外掛啟用時須批准", + }, + doImport: "匯入", + overwrite: "覆蓋", + rename: "改名匯入", + skip: "跳過", + cannotImport: "不可匯入", + newName: (name: string) => `${name} 的新名稱`, + nameEmpty: "名稱不能為空。", + nameTaken: "名稱已被使用。", + unresolved: (n: number) => `尚有 ${n} 項衝突未選擇處理方式。`, + badNames: "改名匯入的名稱有誤。", + nothing: "沒有要匯入的專案。", + allSame: "配置包中的專案與當前配置相同。", + sameHidden: (n: number) => `另有 ${n} 項與當前配置相同,不再列出。`, + imported: (n: number) => `已匯入 ${n} 項`, + refSkipped: (kind: string, name: string) => `引用的${kind}「${name}」不匯入`, + rowNotes: { + destination: "地址與本機不同,不沿用本機金鑰。匯入後為停用狀態,需填寫金鑰。", + renameKey: "改名匯入不沿用本機金鑰。匯入後為停用狀態,需填寫金鑰。", + renamePass: "改名匯入不沿用本機的代理密碼,匯入後需填寫。", + renameLogin: "改名匯入不沿用本機的登入。匯入後為停用狀態,需重新登入。", + renamePlugin: "改名匯入的外掛匯入後為停用狀態。", + }, + repaired: (n: number) => `${n} 處內容由較舊版本寫入,已按一鍵修復的規則修正:`, + stale: "配置在預覽之後已被修改,須重新預覽。", + previewAgain: "重新預覽", + restoreVersion: (at: string) => `恢復 ${at} 的版本`, + restoreDescription: "勾選的專案恢復為該版本的內容,未勾選的保持當前內容。本機設定保留當前值。", + previewFailed: "無法讀取該版本與當前配置的差異", + item: "專案", + change: "變化", + changes: { + add: "新增", + remove: "刪除", + modify: "修改", + }, + keptInUse: "保留:本機用戶端正在使用", + keptReferenced: "保留:仍被保留的專案引用", + unchanged: "該版本與當前配置相同。", + syncNote: (n: number) => `恢復後的配置將同步到其他 ${n} 臺裝置。`, + restoreAction: "恢復", + restored: (at: string, n: number, kept: number) => `已恢復 ${at} 的版本中的 ${n} 項${kept > 0 ? `,保留 ${kept} 項` : ""}`, + replanning: "正在按所選專案計算", + untouched: "保持當前內容", + along2: "隨所選專案一併恢復", + nothingChecked: "未勾選專案。", + saveAction: "另存為…", + saved: (path: string) => `已儲存到 ${path}`, + dropHere: "鬆開以匯入配置包", + }, + ko: { + heading: "백업", + time: "시간", + origin: "출처", + actionsColumn: "작업", + current: "현재", + counts: (providers: number, plugins: number) => `${s(providers, "업스트림", "upstreams")}, ${s(plugins, "plugin", "plugins")}`, + dialogTitle: "백업", + kinds: { + provider: "업스트림", + proxy: "Outbound proxies", + key: "Gateway keys", + alias: "Aliases", + group: "Groups", + route: "Routes", + price_sheet: "Price sheets", + security_rule: "Security rules", + plugin: "플러그인", + global: "Global settings", + provider_order: "Upstream order", + route_order: "Route order", + plugin_order: "Plugin order", + client_prefs: "Lite preferences", + }, + total: (providers: number, keys: number, routes: number, plugins: number) => `${s(providers, "업스트림", "upstreams")}, ${s(keys, "gateway key", "gateway keys")}, ${s(routes, "route", "routes")}, ${s(plugins, "plugin", "plugins")}.`, + omitLogins: (n: number) => `ChatGPT account and OAuth sign-ins (${s(n, "업스트림", "upstreams")}); sign in or fill them in again after importing.`, + name: "이름", + status: "상태", + flags: { + missing_key: "Key missing", + needs_login: "Sign-in required", + plugin_disabled: "플러그인", + }, + changes: { + add: "Add", + remove: "제거", + modify: "Change", + }, + }, + es: { + heading: "Copias de seguridad", + importConfig: "Importar configuración…", + exportConfig: "Exportar configuración…", + time: "Hora", + origin: "Origen", + location: "Almacenado en", + contents: "Sumario", + coreVersion: "Recursos básicos", + actionsColumn: "Acciones", + actionsFor: (at: string) => `Acciones para la versión de ${at}`, + current: "Actual", + restore: "Restaurar…", + saveAs: "Guardar como…", + local: "Locales", + synced: "Sincronizar ubicación", + counts: (providers: number, plugins: number) => `${s(providers, "proveedor", "del proveedor")}, ${s(plugins, "complemento", "complementos")}`, + keeps: "Este dispositivo mantiene las últimas 10 versiones; la ubicación de sincronización mantiene la última y la anterior.", + listFailed: "No se pudieron leer las copias de seguridad", + noBackups: "No hay copias de seguridad todavía", + noBackupsHint: "Cada cambio en la configuración crea una versión aquí.", + dialogTitle: "Copias de seguridad", + dialogDescription: "Restaurar la primera lista de cómo la versión difiere de la configuración actual. La restauración misma crea una versión que también puede ser restaurada.", + restoreTitle: "Restaurar desde la copia de seguridad", + origins: { + ui: "Editado en la aplicación", + cli: "Línea de comandos", + external: "Archivo editado a mano", + defaults: "Complementos predeterminados", + sync: "Sincronización", + syncFrom: (device: string) => `Sincronizado a partir de ${device}`, + import: "Importar", + restore: "Restaurar", + repair: "Reparación", + export: "Exportar", + share: "Compartir", + rotation: "Rotación de credenciales", + other: "Otros", + }, + kinds: { + provider: "Proveedores", + proxy: "Proximos salientes", + key: "Teclas de acceso", + alias: "Alias", + group: "Grupos", + route: "Rutas", + price_sheet: "Fichas de precios", + security_rule: "Normas de seguridad", + plugin: "Complementos", + global: "Ajustes mundiales", + provider_order: "Orden ascendente", + route_order: "Orden de la ruta", + plugin_order: "Pedido del complemento", + client_prefs: "Preferencias Lite", + }, + globals: { + failover: "Fallo", + security: "Modos de protección", + default_route: "Ruta predeterminada", + default_key: "Tecla predeterminada", + client_probes: "Solicitudes auxiliares", + pricing: "Ajustes de la hoja de precios", + }, + guards: { + redact: "Secretos y privacidad", + inspect_tools: "Comandos peligrosos", + content: "Filtro de contenido", + }, + units: { + conn: "conexión", + models: "modelos", + billing: "facturación", + other: "otros ajustes", + all: "Contenido", + script: "script", + settings: "ajustes", + enabled: "estado habilitado", + }, + differ: (what: string, n: number) => `${what.charAt(0).toUpperCase()}${what.slice(1)} ${n === 1 ? "diferencias" : "diferenciar"}`, + exportTitle: "Exportar configuración", + scope: "Ámbito de aplicación", + scopeAll: "Configuración completa", + scopeItems: "Elementos seleccionados", + total: (providers: number, keys: number, routes: number, plugins: number) => `${s(providers, "proveedor", "del proveedor")}, ${s(keys, "tecla de acceso", "Teclas de acceso")}, ${s(routes, "ruta", "rutas")}, ${s(plugins, "complemento", "complementos")}.`, + selected: (n: number) => `${n} seleccionado.`, + noneSelected: "No se han seleccionado elementos.", + along: "Incluido", + alongTip: "Referenciado por un elemento seleccionado y exportado con él", + itemsFailed: "No se pudieron leer los elementos de configuración", + secrets: "Incluir teclas", + secretsWhat: "Claves ascendentes, claves de pasarela y contraseñas de proxy", + encrypt: "Cifrado", + encryptWhat: "Cifrar el archivo con una frase de paso", + encryptHint: "Un archivo cifrado pide la frase de paso cuando se importa.", + passphrase: "Frase de paso", + passphraseAgain: "Repetir", + passphraseShort: "La frase de paso tiene al menos 8 caracteres.", + passphraseMismatch: "Las dos frases de paso difieren.", + omitted: "Sin exportar", + omitLogins: (n: number) => `Cuenta ChatGPT y inicios de sesión OAuth (${s(n, "proveedor", "del proveedor")}); iniciar sesión o rellenarlos de nuevo después de la importación.`, + omitSecrets: "Las teclas de Upstream, gateway y contraseñas de proxy. Los upstream importados permanecen desactivados hasta que sus claves se rellenan; las claves de gategateway se generan de nuevo.", + omitLocal: "Escucha, control remoto y configuración de sincronización.", + omitData: "Solicito historial.", + plaintext: "El archivo contiene claves en texto plano. Manténgalo seguro.", + exportAction: "Exportar…", + exported: (path: string) => `Exportado a ${path}`, + importTitle: "Importar configuración", + reading: "Leyendo el paquete de configuración", + readFailed: "No se pudo leer el paquete de configuración", + encrypted: "Este paquete de configuración está cifrado. Introduzca el conjunto de frases de paso cuando se exportó.", + continue: "Continuar", + packFull: "Paquete de configuración completo", + packPartial: "Paquete de configuración parcial", + withSecrets: "Incluye teclas", + withoutSecrets: "Sin llaves", + packEncrypted: "Cifrado", + exportedBy: (at: string, version: string) => `Exportado por el núcleo ${version} al ${at}`, + countNew: (n: number) => `${n} nuevo`, + countConflict: (n: number) => s(n, "conflicto armado", "conflictos armados"), + countSame: (n: number) => `${n} Lo mismo`, + countError: (n: number) => s(n, "error", "errores"), + overwriteAll: "Sobrescribir todo", + renameAll: "Cambiar el nombre de todos", + skipAll: "Omitir todo", + name: "Nombre", + status: "Estado", + action: "Medidas adoptadas", + statusNew: "Nuevo", + statusConflict: "Conflicto", + flags: { + missing_key: "Falta la clave", + needs_login: "Se requiere registro", + plugin_disabled: "Complemento", + }, + flagHints: { + missing_key: "Importado desactivado hasta que la llave se llena", + needs_login: "Importado desactivado hasta que se inscriba de nuevo", + plugin_disabled: "Importado desactivado; un complemento que reescribe llamadas de la herramienta necesita aprobación cuando está habilitado", + }, + doImport: "Importar", + overwrite: "Sobrescribir", + rename: "Cambiar nombre", + skip: "Saltar", + cannotImport: "No se puede importar", + newName: (name: string) => `Nuevo nombre para ${name}`, + nameEmpty: "El nombre está vacío.", + nameTaken: "El nombre está en uso.", + unresolved: (n: number) => n === 1 ? "1 conflicto no tiene acción seleccionada." : `${n} Los conflictos no tienen acción seleccionada.`, + badNames: "Un nuevo nombre no es válido.", + nothing: "Nada que importar.", + allSame: "Cada elemento del paquete coincide con la configuración actual.", + sameHidden: (n: number) => n === 1 ? "1 elemento más coincide con la configuración actual y no aparece en la lista." : `${n} más elementos coinciden con la configuración actual y no están listados.`, + imported: (n: number) => `Importado ${s(n, "Tema", "elementos")}`, + refSkipped: (kind: string, name: string) => `Referencias ${name} ${kind.toLowerCase()}, que no se importa`, + rowNotes: { + destination: "La dirección difiere de la de aquí, por lo que la clave aquí no se reutiliza. Importado desactivado hasta que una clave se rellena.", + renameKey: "Importada bajo un nuevo nombre, la clave aquí no se reutiliza. Importado desactivado hasta que una clave se llena.", + renamePass: "Importado bajo un nuevo nombre, la contraseña proxy aquí no se reutiliza; llénela después de importar.", + renameLogin: "Importado bajo un nuevo nombre, el inicio de sesión aquí no se reutiliza. Importada deshabilitada hasta que se inicie de nuevo.", + renamePlugin: "Un plugin importado bajo un nuevo nombre está deshabilitado.", + }, + repaired: (n: number) => n === 1 + ? "1 entrada escrita por una versión anterior fue fijada por las reglas Reparar utiliza:" + : `${n} las entradas escritas por una versión anterior fueron fijadas por las reglas Reparar usos:`, + stale: "La configuración cambió después de la vista previa. Vista previa de nuevo.", + previewAgain: "Vista previa de nuevo", + restoreVersion: (at: string) => `Restaurar la versión de ${at}`, + restoreDescription: "Los elementos comprobados se restauran en esta versión; los elementos no marcados mantienen su contenido actual. Los ajustes vinculados a este dispositivo mantienen sus valores actuales.", + previewFailed: "No se pudo comparar esta versión con la configuración actual", + item: "Tema", + change: "Cambio", + changes: { + add: "Añadir", + remove: "Quitar", + modify: "Cambio", + }, + keptInUse: "Mantenido: en uso por un cliente en este dispositivo", + keptReferenced: "Se mantuvo: todavía se refiere a los elementos que permanecen", + unchanged: "Esta versión es la misma que la configuración actual.", + syncNote: (n: number) => `La configuración restaurada se sincronizará con ${s(n, "otro dispositivo", "otros dispositivos")}.`, + restoreAction: "Restaurar", + restored: (at: string, n: number, kept: number) => `Restaurado ${s(n, "Tema", "elementos")} de la versión de ${at}${kept > 0 ? `; mantenido ${kept}` : ""}`, + replanning: "Cómo determinar qué cambia la selección", + untouched: "Se queda como está.", + along2: "Restaurado con los elementos seleccionados", + nothingChecked: "No hay elementos comprobados.", + saveTitle: "Guardar versión", + saveAction: "Guardar como…", + saved: (path: string) => `Guardado en ${path}`, + dropHere: "Abandonar para importar el paquete de configuración", + }, + }, ); diff --git a/src/clients/clients.i18n.tsx b/src/clients/clients.i18n.tsx index b3607727..ee5a50fd 100644 --- a/src/clients/clients.i18n.tsx +++ b/src/clients/clients.i18n.tsx @@ -470,4 +470,555 @@ export const clientsText = messages( keysKept: "Each keeps its key, which is used again on the next connection.", confirmRestoreAll: "Restore all", }, + { + "zh-Hant": { + restoreAll: "全部還原…", + modelsStale: (name: string) => `${name} 的模型列表需要更新:閘道器上可用的模型已有變化。`, + configNeedsUpdate: (name: string) => `${name} 的連線配置缺少必要設定或與當前要求不一致,請更新配置並重啟用戶端。`, + configUpdateReason: "連線配置需要更新", + loadFailed: "無法讀取本機的用戶端", + noneTitle: "未檢測到可接管的用戶端", + noneHint: "已安裝的用戶端執行一次、生成配置檔案後會出現在這裡;也可以按下方的配置方法手動接入。", + manualTitle: "需要手動配置", + manualIntro: "以下用戶端無法自動接管,按步驟填入閘道器地址和金鑰即可。", + absentTitle: "未檢測到", + absentIntro: "配置檔案不在預設位置時,可以更改路徑,或按配置方法手動接入。", + noneConnected: "尚未接管用戶端", + nDetected: (_n: number, n: ReactNode) => <>檢測到 {n} 個, + nWaiting: "等待首個請求", + nOther: "由另一個 ThinkWatch Lite 接管", + client: "用戶端", + status: "狀態", + key: "金鑰", + last24h: "24 小時", + waiting: "等待首個請求", + absent: "未檢測到", + otherInstance: "由另一個 ThinkWatch Lite 接管", + otherInstanceHint: "需在接管它的 ThinkWatch Lite 中還原", + moved: (host: string) => `配置中的地址已改為 ${host}`, + pointsAtLocal: (host: string) => `指向本機閘道器 ${host}`, + shadowed: (file: string) => `被 ${file} 覆蓋`, + silent: "接管五分鐘仍無請求", + restart: "重新啟動後生效", + pointsTo: (host: string) => `當前指向 ${host}`, + ownService: "使用自帶的服務", + seeWhy: "檢視原因", + restore: "還原…", + details: "詳情…", + reveal: isWindows + ? "在檔案資源管理器中顯示配置檔案" + : isLinux + ? "在檔案管理器中顯示配置檔案" + : "在訪達中顯示配置檔案", + changePath: "更改路徑…", + traffic: "檢視流量", + dragClient: (name: string) => `拖動調整 ${name} 的位置`, + orderFailed: "無法儲存用戶端順序", + restoredAll: (n: number) => `已還原 ${n} 個用戶端`, + restoreFailed: (failures: { + client: string; + detail: string; + }[]) => `${failures.length} 個用戶端還原失敗:` + failures.map((r) => `${r.client}(${r.detail})`).join(";"), + restoreSkipped: (names: string[]) => `未還原由另一個 ThinkWatch Lite 接管的用戶端:${names.join("、")}。需在接管它們的 ThinkWatch Lite 中還原。`, + file: "配置檔案", + realFile: (path: string) => `實際檔案:${path}`, + revealShort: isWindows ? "在資源管理器中顯示" : isLinux ? "在檔案管理器中顯示" : "在訪達中顯示", + pointsHere: "指向本閘道器", + notHere: "未指向本閘道器", + noEndpoint: "未設定,使用自帶的服務", + keyOnAdopt: "接管時生成", + usage: "24 小時", + usageLine: (n: number, at: string) => `${n.toLocaleString()} 次請求 · 最近一次 ${at}`, + noUsage: "尚無請求", + costs: "接管的影響", + check: "配置鏈檢查", + recheck: "重新檢查", + checkFailed: "配置鏈檢查未能完成", + restoreTitle: (name: string) => `還原 ${name}`, + modifies: (path: ReactNode) => <>將修改 {path},寫入前完整備份原檔案。, + creates: (path: ReactNode) => <>將新建 {path}。, + alsoModifies: (path: ReactNode) => <>同時修改 {path},同樣先完整備份。, + alsoCreates: (path: ReactNode) => <>同時新建 {path}。, + alsoDeletes: (path: ReactNode) => <>同時刪除 {path}(接管時新建,還原後為空)。, + noop: "配置已是目標狀態,無需修改。", + stale: "配置檔案在檢視改動期間已被修改,未寫入任何內容。以下改動已按當前內容重新計算,核對後請再次確認。", + field: "欄位", + written: "寫入", + change: "改動", + newKey: (name: string) => `新金鑰「${name}」`, + keyNamed: (name: string) => `金鑰「${name}」`, + remove: "刪除", + restoreTo: (v: string) => `恢復為 ${v}`, + notes: "說明", + keepsKey: (name: string) => `金鑰「${name}」保留,再次接管時直接使用。`, + diff: "完整改動", + secretMasked: "改動中的金鑰已遮蓋,寫入的是配置中的金鑰原文。", + confirmRestore: "還原", + bedrockNone: (client: string) => `閘道器中尚無 Amazon Bedrock 上游,接管後 ${client} 的請求需要它。`, + bedrockSome: (names: string[]) => `閘道器中已有 Amazon Bedrock 上游:${names.join("、")}。`, + bedrockDraft: (client: string, parts: string[]) => `按 ${client} 原來的設定新建:${parts.join(",")}。`, + bedrockRegion: (region: string) => `區域 ${region}`, + bedrockKey: (ref: string) => `API 金鑰 ${ref}`, + bedrockKeys: (ref: string) => `訪問金鑰 ${ref}`, + bedrockNoCredential: "憑據在新建時填寫", + staleGateway: "閘道器可用的模型在檢視改動期間發生了變化,未寫入任何內容。以下改動已按當前情況重新計算,核對後請再次確認。", + desktopModelHint: "閘道器中沒有上游提供 Claude 模型,而 Claude Desktop 只接受 Claude 的模型名。接管時在它的金鑰上新增一條路由規則,它的請求都發給所選模型;其他用戶端不受影響。", + desktopNoModels: "閘道器中沒有該金鑰可用的上游模型,接管後 Claude Desktop 的請求無法完成。新增上游後重新接管。", + gatewayChange: "閘道器配置", + rulePlace: (route: string, n: number) => `路由「${route}」第 ${n} 條`, + ruleText: (name: string, key: ReactNode, to: ReactNode) => (<> + 規則「{name}」:金鑰 {key} → 指定模型 {to} + ), + ruleDelete: (name: string, key: ReactNode, to: ReactNode) => (<> + 刪除規則「{name}」:金鑰 {key} → 指定模型 {to} + ), + ruleAdded: "取消接管時刪除這條規則。", + ruleChanged: "這條規則已存在,改為指定所選模型;取消接管時刪除。", + ruleUnneeded: "閘道器中已有上游提供 Claude 模型,接管時新增的這條規則不再需要。", + keyGoesBelow: "金鑰(見下方)", + endpointLabel: "閘道器地址", + keyLabel: "金鑰", + newKeyFor: (name: string) => `為 ${name} 新建專用金鑰`, + createAndCopy: "建立並複製", + thisComputer: "這臺電腦", + wslUnreadable: "無法讀取", + wslSummary: { + wsl1: (host: string) => `WSL 1,與 Windows 共用網路,經由 ${host} 連線閘道器。`, + mirrored: (host: string) => `mirrored 網路,經由 ${host} 連線閘道器。`, + nat: (host: string) => `NAT 網路,經由 ${host} 連線閘道器。`, + natBlocked: "NAT 網路,尚未找到可用的閘道器地址。", + restart: "NAT 網路,重啟 WSL 後改用 mirrored 網路。", + fallback: "NAT 網路,未能改用 mirrored 網路。", + }, + wslLeft: (summary: string, n: number) => `${summary}${n} 個已接管的用戶端仍指向本機閘道器。`, + natBody: "尚未找到可用的 NAT 主機地址。請檢查 WSL 預設路由和 Windows 網絡卡,也可選擇切換到 mirrored 網路模式。", + natVersion: "WSL 的 mirrored 網路模式需要 WSL 2.0.5 或更高版本,可在終端中執行 wsl --update 更新。", + toMirrored: "改為 mirrored 模式…", + restartBody: "已在 .wslconfig 中將 WSL 設為 mirrored 網路模式,重啟 WSL 後生效。", + fallbackBody: "WSL 重啟後仍在使用 NAT 網路。接管將嘗試使用 NAT 主機地址;若需要 mirrored 網路,請檢查 WSL 設定。", + restartWsl: "重啟 WSL…", + oldWindowsBody: "這臺電腦不支援 mirrored 網路模式。接管可使用 NAT 主機地址,請檢查 WSL 預設路由和 Windows 網絡卡。", + oldWslBody: (version: string) => `WSL ${version} 不支援 mirrored 網路模式,需先在終端中執行 wsl --update。`, + unreachable: "WSL 中無法訪問閘道器", + gatewayChanged: "閘道器地址已變化,請重新接管", + listenerUnavailable: "閘道器當前不可達,請檢查監聽或防火牆", + wslNeedsAttention: "已接管的用戶端當前無法連線。原配置已保留,重新接管前會展示需要的改動。", + mirroredTitle: "將 WSL 改為 mirrored 網路模式", + mirroredAllDistros: "對這臺電腦上所有 WSL 2 發行版生效。", + mirroredRestart: "重啟 WSL 後才會生效。", + mirroredKept: "完全解除安裝時不會改回。", + mirroredNoop: "已是 mirrored 網路模式,無需修改。", + confirmMirrored: "改為 mirrored", + mirroredSet: "已將 WSL 改為 mirrored 網路模式,重啟 WSL 後生效", + restartTitle: "重啟 WSL", + restartWhat: "將執行 wsl --shutdown:所有正在執行的 WSL 發行版都會停止,其中執行的程式隨之退出。", + confirmRestart: "重啟 WSL", + wslRestarted: "已重啟 WSL", + locDesc: "接管、MCP 管理和安全掃描讀寫的位置。", + locRole: { config: "接管", mcp: "MCP 管理", scan: "安全掃描" }, + locDefaultFile: (path: string) => `預設位置:${path}`, + locDefaultFolder: (path: string) => `預設資料夾:${path}`, + locAdopted: "已接管,需先還原才能更改位置。", + locRestore: "恢復預設", + locRestoreTitle: "恢復預設位置", + locConfirmBody: "接管、MCP 管理和安全掃描使用同一個配置目錄,以下幾處一起更改。", + enterPath: "填寫路徑", + restoreAllTitle: "還原全部用戶端", + restoreAllBody: (n: number) => `以下 ${n} 個用戶端將還原到接管之前的配置,之後它們的請求不再經過閘道器。`, + keysKept: "各自的金鑰保留,再次接管時直接使用。", + confirmRestoreAll: "全部還原", + }, + ja: { + restoreAll: "すべて復元…", + modelsStale: (name: string) => `ゲートウェイで利用できるモデルが変わりました。${name} のモデル一覧を更新してください。`, + updateModels: "モデル一覧を更新…", + configNeedsUpdate: (name: string) => `${name} の接続設定に不足または不一致があります。設定を更新してクライアントを再起動してください。`, + updateConfig: "設定を更新…", + configUpdateReason: "接続設定の更新が必要です", + loadFailed: "この端末のクライアントを読み込めませんでした", + noneTitle: "接続できるクライアントが見つかりませんでした", + noneHint: "インストール済みのクライアントを一度実行すると、設定ファイルが作成されてここに表示されます。下の手順で手動設定することもできます。", + manualTitle: "手動設定が必要", + manualIntro: "以下のクライアントは自動で設定できません。手順に従ってゲートウェイのアドレスとキーを入力してください。", + absentTitle: "未検出", + absentIntro: "設定ファイルが既定の場所にない場合は、パスを変更するか、手動で接続を設定してください。", + noneConnected: "接続済みのクライアントはありません", + nDetected: (_n: number, n: ReactNode) => <>{n} 件検出, + nInUse: "使用中", + nWaiting: "初回リクエスト待ち", + nBroken: "未適用", + nIdle: "未接続", + nOther: "別の ThinkWatch Lite で接続", + client: "クライアント", + status: "状態", + key: "キー", + last24h: "過去 24 時間", + actions: "操作", + inUse: "使用中", + waiting: "初回リクエスト待ち", + broken: "未適用", + idle: "未接続", + absent: "未検出", + notSet: "未設定", + otherInstance: "別の ThinkWatch Lite で接続", + otherInstanceHint: "接続を設定した ThinkWatch Lite で復元してください", + moved: (host: string) => `設定のアドレスが ${host} に変更されました`, + pointsAtLocal: (host: string) => `ローカルゲートウェイ ${host} を参照`, + shadowed: (file: string) => `${file} が優先されています`, + silent: "接続設定から 5 分間リクエストがありません", + restart: "再起動後に有効になります", + pointsTo: (host: string) => `現在の接続先:${host}`, + ownService: "クライアント固有のサービスを使用", + seeWhy: "原因を表示", + adopt: "接続…", + reconnect: "再接続…", + reconnectTitle: (name: string) => `${name} を再接続`, + confirmReconnect: "再接続", + restore: "復元…", + manual: "設定手順…", + details: "詳細…", + reveal: isWindows ? "エクスプローラーで設定ファイルを表示" : isLinux ? "ファイルマネージャーで設定ファイルを表示" : "Finder で設定ファイルを表示", + changePath: "パスを変更…", + traffic: "トラフィックを表示", + actionsFor: (name: string) => `${name} の操作`, + moveUp: "上に移動", + moveDown: "下に移動", + dragClient: (name: string) => `ドラッグして ${name} を移動`, + orderFailed: "クライアントの順序を保存できませんでした", + restoredAll: (n: number) => `${n} 件のクライアント設定を復元しました`, + restoreFailed: (failures: { + client: string; + detail: string; + }[]) => `${failures.length} 件のクライアント設定を復元できませんでした:${failures.map((r) => `${r.client}(${r.detail})`).join("、")}`, + restoreSkipped: (names: string[]) => `別の ThinkWatch Lite が接続したクライアントはスキップしました:${names.join("、")}。接続を設定したアプリで復元してください。`, + file: "設定ファイル", + realFile: (path: string) => `実際のファイル:${path}`, + revealShort: isWindows ? "エクスプローラーで表示" : isLinux ? "ファイルマネージャーで表示" : "Finder で表示", + endpoint: "アドレス", + pointsHere: "このゲートウェイを参照", + notHere: "別の接続先を参照", + noEndpoint: "未設定。クライアント固有のサービスを使用します", + keyOnAdopt: "接続時に作成", + effect: "適用", + usage: "過去 24 時間", + usageLine: (n: number, at: string) => `リクエスト ${n.toLocaleString("ja")} 件 · 最終 ${at}`, + lastSeenLine: (at: string) => `最終 ${at}`, + noUsage: "リクエストなし", + costs: "接続設定の影響", + check: "設定の適用順序を確認", + recheck: "再確認", + checkFailed: "設定の適用順序を確認できませんでした", + adoptTitle: (name: string) => `${name} を接続`, + restoreTitle: (name: string) => `${name} の設定を復元`, + modifies: (path: ReactNode) => <>{path} を変更します。保存前に元のファイル全体をバックアップします。, + creates: (path: ReactNode) => <>{path} を作成します。, + alsoModifies: (path: ReactNode) => <>{path} も変更します。保存前に元のファイル全体をバックアップします。, + alsoCreates: (path: ReactNode) => <>{path} も作成します。, + alsoDeletes: (path: ReactNode) => <>{path} も削除します。接続時に作成され、復元すると空になります。, + noop: "設定はすでに目的の状態です。", + stale: "確認中に設定ファイルが変わったため、書き込みを中止しました。最新の内容で再計算した変更を確認してください。", + field: "項目", + written: "設定値", + change: "変更", + newKey: (name: string) => `新しいキー「${name}」`, + keyNamed: (name: string) => `キー「${name}」`, + remove: "削除", + restoreTo: (v: string) => `${v} に復元`, + notes: "詳細", + keepsKey: (name: string) => `キー「${name}」は保持され、再接続時に使用されます。`, + diff: "変更内容の全体", + secretMasked: "変更プレビューではキーを伏せています。保存時は元のキーを書き込みます。", + confirmAdopt: "接続", + confirmRestore: "復元", + bedrockNone: (client: string) => `ゲートウェイに Amazon Bedrock のアップストリームがありません。接続後に ${client} がリクエストを送信するには必要です。`, + bedrockSome: (names: string[]) => `既存の Amazon Bedrock アップストリーム:${names.join("、")}。`, + bedrockDraft: (client: string, parts: string[]) => `${client} の既存設定に基づいて作成:${parts.join("、")}。`, + bedrockRegion: (region: string) => `リージョン ${region}`, + bedrockAddress: (url: string) => `アドレス ${url}`, + bedrockKey: (ref: string) => `API キー ${ref}`, + bedrockKeys: (ref: string) => `アクセスキー ${ref}`, + bedrockProfile: (name: string) => `AWS プロファイル ${name}`, + bedrockNoCredential: "作成時に認証情報を入力", + bedrockCreate: "Bedrock アップストリームを追加…", + staleGateway: "確認中に利用できるモデルが変わったため、書き込みを中止しました。最新の状態で再計算した変更を確認してください。", + desktopModel: "Claude Desktop が使用するモデル", + desktopModelHint: "利用できる Claude モデルがありません。Claude Desktop は Claude のモデル名のみ受け付けるため、接続時にこのキー専用のルーティングルールを追加し、リクエストを選択したモデルに転送します。", + desktopNoModels: "このキーで利用できるモデルがありません。アップストリームを追加してから Claude Desktop を再接続してください。", + desktopChoice: (model: string, providers: string[]) => `${model} · ${providers.join("、")}`, + gatewayChange: "ゲートウェイ設定", + rulePlace: (route: string, n: number) => `ルート「${route}」の ${n} 番目`, + ruleText: (name: string, key: ReactNode, to: ReactNode) => <>ルール「{name}」:キー {key} → 指定モデル {to}, + ruleDelete: (name: string, key: ReactNode, to: ReactNode) => <>ルール「{name}」を削除:キー {key} → 指定モデル {to}, + pinnedJoin: "、", + ruleAdded: "接続設定を復元すると、このルールを削除します。", + ruleChanged: "既存のルールを選択したモデルに変更します。接続設定を復元すると削除します。", + ruleUnneeded: "Claude モデルを利用できるため、接続時に追加したこのルールは不要になりました。", + manualDialogTitle: (name: string) => `${name} を設定`, + keyGoesBelow: "キー(下記参照)", + endpointLabel: "ゲートウェイアドレス", + keyLabel: "キー", + newKeyFor: (name: string) => `${name} の専用キーを作成`, + createAndCopy: "作成してコピー", + done: "完了", + thisComputer: "この端末", + wslGroup: (distro: string) => `WSL · ${distro}`, + inWsl: (name: string, distro: string) => `${name}(WSL · ${distro})`, + wslUnreadable: "読み取り不可", + wslSummary: { + wsl1: (host: string) => `WSL 1 は Windows とネットワークを共有します。${host} 経由でゲートウェイに接続します。`, + mirrored: (host: string) => `ミラーモード。${host} 経由でゲートウェイに接続します。`, + nat: (host: string) => `NAT。${host} 経由でゲートウェイに接続します。`, + natBlocked: "NAT。利用できるゲートウェイアドレスが見つかりません。", + restart: "NAT。WSL の再起動後にミラーモードに切り替わります。", + fallback: "NAT。ミラーモードに切り替えられませんでした。", + }, + wslLeft: (summary: string, n: number) => `${summary}${n} 件のクライアントは引き続きローカルゲートウェイを参照しています。`, + natBody: "利用できる NAT ホストアドレスが見つかりませんでした。WSL の既定ルートと Windows のネットワークを確認するか、ミラーモードに切り替えてください。", + natVersion: "ミラーモードには WSL 2.0.5 以降が必要です。ターミナルで wsl --update を実行して更新できます。", + toMirrored: "ミラーモードに変更…", + restartBody: ".wslconfig にミラーモードを設定しました。WSL を再起動すると適用されます。", + fallbackBody: "再起動後も WSL は NAT を使用しています。接続設定では NAT のホストアドレスを使用します。ミラーモードが必要な場合は WSL の設定を確認してください。", + restartWsl: "WSL を再起動…", + oldWindowsBody: "この端末ではミラーモードを利用できません。NAT のホストアドレスを使用するには、WSL の既定ルートと Windows のネットワークを確認してください。", + oldWslBody: (version: string) => `WSL ${version} はミラーモードに対応していません。ターミナルで wsl --update を実行してください。`, + unreachable: "WSL からゲートウェイに到達できません", + gatewayChanged: "ゲートウェイのアドレスが変わりました。再接続してください", + listenerUnavailable: "ゲートウェイに到達できません。リッスン設定とファイアウォールを確認してください", + wslNeedsAttention: "クライアントを接続できません。既存設定は保持され、再接続前に必要な変更を確認できます。", + mirroredTitle: "WSL をミラーモードに変更", + mirroredAllDistros: "この端末のすべての WSL 2 ディストリビューションに適用します。", + mirroredRestart: "WSL を再起動すると適用されます。", + mirroredKept: "完全にアンインストールした後も、この設定は残ります。", + mirroredNoop: "すでにミラーモードです。", + confirmMirrored: "ミラーモードに変更", + mirroredSet: "WSL のミラーモードを設定しました。WSL の再起動後に適用されます", + restartTitle: "WSL を再起動", + restartWhat: "wsl --shutdown を実行します。実行中のすべての WSL ディストリビューションとそのプログラムが終了します。", + confirmRestart: "WSL を再起動", + wslRestarted: "WSL を再起動しました", + locTitle: (name: string) => `${name} の設定ファイルの場所`, + locDesc: "接続設定、MCP 管理、セキュリティスキャンで使用する場所です。", + locRole: { config: "接続設定", mcp: "MCP 管理", scan: "セキュリティスキャン" }, + locJoin: "、", + locDefaultFile: (path: string) => `既定の場所:${path}`, + locDefaultFolder: (path: string) => `既定のフォルダー:${path}`, + locAdopted: "場所を変更するには先に接続設定を復元してください。", + locRestore: "初期設定に戻す", + locConfirmTitle: "設定ファイルの場所を変更", + locRestoreTitle: "既定の場所に戻す", + locConfirmBody: "接続設定、MCP 管理、セキュリティスキャンは設定ディレクトリを共有するため、以下の場所をまとめて変更します。", + locConfirm: "変更", + enterPath: "パスを入力", + restoreAllTitle: "すべてのクライアント設定を復元", + restoreAllBody: (n: number) => `以下の ${n} 件のクライアントを接続前の設定に戻します。その後のリクエストはゲートウェイを経由しません。`, + keysKept: "各クライアントのキーは保持され、再接続時に使用されます。", + confirmRestoreAll: "すべて復元", + }, + ko: { + client: "클라이언트", + status: "상태", + key: "키", + actions: "작업", + idle: "연결 안 됨", + confirmReconnect: "다시 연결", + endpoint: "주소", + confirmAdopt: "연결", + keyLabel: "키", + thisComputer: "이 컴퓨터", + confirmMirrored: "전환", + locRole: { config: "연결 중", mcp: "MCP management", scan: "Security scan" }, + }, + es: { + restoreAll: "Restaurar todo…", + modelsStale: (name: string) => `La lista de modelos en ${name} necesita actualización: los modelos disponibles en la pasarela han cambiado.`, + updateModels: "Actualizar la lista de modelos…", + configNeedsUpdate: (name: string) => `${name} la configuración de la conexión tiene configuraciones faltantes o incorrectas. Actualícela y luego reinicie el cliente.`, + updateConfig: "Actualizar la configuración…", + configUpdateReason: "La configuración de la conexión necesita actualización", + loadFailed: "No se pudo leer a los clientes en este ordenador", + noneTitle: "No se encontró ningún cliente para conectar", + noneHint: "Un cliente instalado aparece aquí una vez que se ha ejecutado y ha creado su archivo de configuraciónuración. Cada uno también se puede configurar a mano a continuación.", + manualTitle: "Montado a mano", + manualIntro: "Estos clientes no se pueden conectar automáticamente; siga los pasos para introducir la dirección y la clave de la puerta de enlace.", + absentTitle: "No detectado", + absentIntro: "Cuando el archivo de configuraciónuración no esté en su ubicación predeterminada, cambie la ruta o establezca el cliente a mano.", + noneConnected: "Ningún cliente conectado todavía", + nDetected: (count: number, n: ReactNode) => <>{n} {count === 1 ? "cliente" : "clientes"} detectada, + nInUse: "en uso", + nWaiting: "esperando la primera solicitud", + nBroken: "no está en vigor", + nIdle: "Desconectado", + nOther: "conectado por otro ThinkWatch Lite", + client: "Cliente", + status: "Estado", + key: "Clave", + last24h: "Las últimas 24 horas", + actions: "Acciones", + inUse: "En uso", + waiting: "Esperando la primera solicitud", + broken: "Sin efecto", + idle: "Sin conexión", + absent: "No detectado", + notSet: "Sin configurar", + otherInstance: "Conectado por otro ThinkWatch Lite", + otherInstanceHint: "Restaurarlo de la ThinkWatch Lite que lo conectaba", + moved: (host: string) => `La dirección en su configuración es ahora ${host}`, + pointsAtLocal: (host: string) => `Puntos a la puerta de enlace local ${host}`, + shadowed: (file: string) => `Derogado por ${file}`, + silent: "Ninguna solicitud cinco minutos después de la conexión", + restart: "Toma efecto después de un reinicio", + pointsTo: (host: string) => `Puntos a ${host}`, + ownService: "Utiliza su propio servicio", + seeWhy: "A ver por qué", + adopt: "Conectar…", + reconnect: "Reconecta…", + reconnectTitle: (name: string) => `Reconectar ${name}`, + confirmReconnect: "Volver a conectar", + restore: "Restaurar…", + manual: "Prepárate…", + details: "Detalles…", + reveal: isWindows + ? "Mostrar archivo de configuraciónuración en el Explorador de archivos" + : isLinux + ? "Mostrar archivo de configuraciónuración en el gestor de archivos" + : "Mostrar archivo de configuraciónuración en Finder", + changePath: "Cambiar la ruta…", + traffic: "Mostrar tráfico", + actionsFor: (name: string) => `Acciones en relación con ${name}`, + moveUp: "Subir", + moveDown: "Bajar", + dragClient: (name: string) => `Arrastre para reordenar ${name}`, + orderFailed: "La orden del cliente no se pudo guardar", + restoredAll: (n: number) => `${count(n, "cliente", "clientes")} restaurado`, + restoreFailed: (failures: { + client: string; + detail: string; + }[]) => `${count(failures.length, "cliente", "clientes")} No se pudo restablecer: ` + + failures.map((r) => `${r.client} (${r.detail})`).join("; "), + restoreSkipped: (names: string[]) => `No restaurado, conectado por otro ThinkWatch Lite: ${names.join(", ")}. Restaurarlos desde el ThinkMirante Lite que los conectaba.`, + file: "Configuración", + realFile: (path: string) => `Archivo real: ${path}`, + revealShort: isWindows ? "Mostrar en el explorador de archivos" : isLinux ? "Mostrar en el gestor de archivos" : "Mostrar en buscador", + endpoint: "Dirección", + pointsHere: "Puntos a esta puerta de enlace", + notHere: "No apunta a esta puerta de entrada", + noEndpoint: "No set; utiliza su propio servicio", + keyOnAdopt: "Generado cuando se conecta", + effect: "Sucede", + usage: "Las últimas 24 horas", + usageLine: (n: number, at: string) => `${n === 1 ? "1 solicitud" : `${n.toLocaleString()} solicitudes`} · último en ${at}`, + lastSeenLine: (at: string) => `Por último en ${at}`, + noUsage: "Todavía no hay solicitudes.", + costs: "¿Qué cambia?", + check: "Comprobación de configuración", + recheck: "Comprobar de nuevo", + checkFailed: "La comprobación de configuración no pudo terminar", + adoptTitle: (name: string) => `Conectar ${name}`, + restoreTitle: (name: string) => `Restaurar ${name}`, + modifies: (path: ReactNode) => <>{path} se cambiará; el original se copia de seguridad en su totalidad primero., + creates: (path: ReactNode) => <>{path} será creado., + alsoModifies: (path: ReactNode) => <>{path} es cambiado junto con él, y respaldado en su totalidad también., + alsoCreates: (path: ReactNode) => <>{path} se crea junto con él., + alsoDeletes: (path: ReactNode) => <>{path} se elimina junto con él (fue creado al conectar y está vacío una vez restaurado)., + noop: "La configuración ya es como debería ser; nada que cambiar.", + stale: "El archivo de configuraciónuración cambió mientras se revisaba el cambio, así que no se escribió nada. El cambio de abajo se recompuso del archivo actual; revíselo y confírmelo de nuevo.", + field: "Campo", + written: "Valor", + change: "Cambio", + newKey: (name: string) => `Nueva clave “${name}”`, + keyNamed: (name: string) => `Clave “${name}”`, + remove: "Eliminado", + restoreTo: (v: string) => `Volver a ${v}`, + notes: "Notas", + keepsKey: (name: string) => `La tecla “${name}” se mantiene y se utiliza de nuevo en la siguiente conexión.`, + diff: "Cambio completo", + secretMasked: "Las teclas se enmascaran en el cambio; la clave de la configuración es lo que se escribe.", + confirmAdopt: "Conectar", + confirmRestore: "Restaurar", + bedrockNone: (client: string) => `La puerta de enlace no tiene Amazon Bedrock del proveedor todavía, y ${client} las solicitudes necesitan una vez conectado.`, + bedrockSome: (names: string[]) => `El portal tiene Amazon Bedrock del proveedor: ${names.join(", ")}.`, + bedrockDraft: (client: string, parts: string[]) => `De la configuración anterior de ${client}: ${parts.join(", ")}.`, + bedrockRegion: (region: string) => `región ${region}`, + bedrockAddress: (url: string) => `dirección ${url}`, + bedrockKey: (ref: string) => `Clave API ${ref}`, + bedrockKeys: (ref: string) => `claves de acceso ${ref}`, + bedrockProfile: (name: string) => `Perfil AWS ${name}`, + bedrockNoCredential: "credenciales que deben introducirse", + bedrockCreate: "Nuevo Bedrock del proveedor…", + staleGateway: "Los modelos disponibles en la puerta de enlace cambiaron mientras el cambio estaba siendo revisado, así que nada fue escrito. El cambio de abajo fue recomputado; revíselo y confirme de nuevo.", + desktopModel: "Modelo para escritorio Claude", + desktopModelHint: "Claude Desktop solo acepta nombres de modelos de Claude. Conectar añade una regla de enrutamiento en su clave que envía todas sus peticiones al modelo seleccionado; otros clientes no se ven afectados.", + desktopNoModels: "La puerta de enlace no tiene ningún modelo ascendente para esta clave, por lo que las peticiones de Claude Desktop no pueden ser atendidas una vez conectadas.", + gatewayChange: "Configuración de la pasarela", + rulePlace: (route: string, n: number) => `Ruta «${route}», regla ${n}`, + ruleText: (name: string, key: ReactNode, to: ReactNode) => (<> + Artículo “{name}”: clave {key} → modelo especificado {to} + ), + ruleDelete: (name: string, key: ReactNode, to: ReactNode) => (<> + Suprímase la regla “{name}”: clave {key} → modelo especificado {to} + ), + ruleAdded: "La regla se elimina cuando se restablece la conexión.", + ruleChanged: "La regla ya existe y ahora especifica el modelo seleccionado; se elimina cuando se restablece la conexión.", + ruleUnneeded: "Las corrientes ascendentes en la pasarela ahora ofrecen modelos de Claude, por lo que la regla añadida sobre la conexión ya no es necesaria.", + manualDialogTitle: (name: string) => `Montar ${name}`, + keyGoesBelow: "La clave (abajo)", + endpointLabel: "Dirección de la pasarela", + keyLabel: "Clave", + newKeyFor: (name: string) => `Una nueva clave para ${name}`, + createAndCopy: "Crear y copiar", + done: "Hecho", + thisComputer: "Este equipo", + wslUnreadable: "No se pudo leer", + wslSummary: { + wsl1: (host: string) => `WSL 1 comparte la red con Windows; los clientes llegan a la puerta de enlace en ${host}.`, + mirrored: (host: string) => `Redes reflejadas; los clientes llegan a la puerta de enlace en ${host}.`, + nat: (host: string) => `NAT networking; los clientes llegan a la puerta de enlace en ${host}.`, + natBlocked: "NAT networking; todavía no se ha encontrado ninguna dirección de pasarela utilizable.", + restart: "NAT networking; red reflejada toma el control una vez que WSL reinicia.", + fallback: "NAT networking; no se pudo activar la red reflejada.", + }, + wslLeft: (summary: string, n: number) => n === 1 + ? `${summary} 1 connected client still points to the local gateway.` + : `${summary} ${n} Los clientes conectados siguen apuntando a la puerta de enlace local.`, + natBody: "No se encontró ninguna dirección de host NAT utilizable. Compruebe la ruta predeterminada de WSL y las interfaces de Windows, o elija redes reflejadas.", + natVersion: "El modo de red espejo de WSL necesita WSl 2.0.5 o posterior; wsl --update en un terminal lo actualiza.", + toMirrored: "Cambiar a espejo…", + restartBody: "El modo de red espejo de WSL se establece en .wslconfig y tiene efecto una vez que WSl se reinicia.", + fallbackBody: "WSL todavía utiliza redes NAT después de reiniciar. Conectar probará la dirección de host NAT; compruebe la configuración de WSl si se requiere una red reflejada.", + restartWsl: "Reiniciar WSL…", + oldWindowsBody: "Esta computadora no admite la creación de redes reflejadas. Los clientes pueden utilizar la dirección de host NAT; compruebe la ruta predeterminada de WSL y las interfaces Windows.", + oldWslBody: (version: string) => `WSL ${version} no admite redes reflejadas. Ejecute wsl --update en una terminal primero.`, + unreachable: "No se puede llegar a la puerta de entrada desde WSL", + gatewayChanged: "La dirección de la pasarela cambió. Reconéctese para revisar la actualización.", + listenerUnavailable: "Puerta de enlace no disponible. Compruebe el oyente o el cortafuegos.", + wslNeedsAttention: "Los clientes gestionados no pueden conectarse actualmente. Se preserva su configuración; vuelva a conectarse para revisar los cambios requeridos.", + mirroredTitle: "Cambiar WSL a redes reflejadas", + mirroredAllDistros: "Se aplica a cada distribución de WSL 2 en este ordenador.", + mirroredRestart: "Tiene efecto una vez que WSL se reinicia.", + mirroredKept: "Una desinstalación completa no lo cambia de nuevo.", + mirroredNoop: "La red reflejada ya está configurada; nada que cambiar.", + confirmMirrored: "Cambiar", + mirroredSet: "Cambiar WSL a redes reflejadas; tiene efecto una vez que WSl se reinicia", + restartTitle: "Reiniciar WSL", + restartWhat: "Esto ejecuta wsl --shutdown: cada distribución WSL en ejecución se detiene, y los programas que se ejecutan en él salen.", + confirmRestart: "Reiniciar WSL", + wslRestarted: "WSL reiniciado", + locTitle: (name: string) => `${name} ubicaciones de configuración`, + locDesc: "Donde la conexión, la gestión de MCP y el escaneo de seguridad leer y escribir.", + locRole: { config: "Conectando", mcp: "Gestión del MCP", scan: "Exploración de seguridad" }, + locDefaultFile: (path: string) => `Situación de la zona: ${path}`, + locDefaultFolder: (path: string) => `Carpeta predeterminada: ${path}`, + locAdopted: "Conectado. Restaurarlo antes de cambiar sus ubicaciones.", + locRestore: "Restaurar valores predeterminados", + locConfirmTitle: "Cambiar la ubicación", + locRestoreTitle: "Restaurar ubicaciones predeterminadas", + locConfirmBody: "La conexión, la gestión MCP y el escaneo de seguridad comparten una carpeta de configuración, por lo que estos cambios juntos.", + locConfirm: "Cambio", + enterPath: "Introduzca una ruta", + restoreAllTitle: "Restaurar todos los clientes", + restoreAllBody: (n: number) => `${count(n, "cliente", "clientes")} volverá a la configuración de antes de conectarse, y sus solicitudes ya no pasarán a través de la puerta de enlace.`, + keysKept: "Cada uno mantiene su llave, que se utiliza de nuevo en la siguiente conexión.", + confirmRestoreAll: "Restaurar todo", + }, + }, ); diff --git a/src/connection/ConnectionsSection.tsx b/src/connection/ConnectionsSection.tsx index 8e3ec036..40fff0bb 100644 --- a/src/connection/ConnectionsSection.tsx +++ b/src/connection/ConnectionsSection.tsx @@ -19,7 +19,7 @@ import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; import { Segmented } from "@/ui/segmented"; import { StatusLabel, type StatusTone } from "@/ui/status-dot"; import { cn } from "@/lib/utils"; -import { useLang, useText } from "@/i18n"; +import { localeTag, useLang, useText, type Lang } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { ListSkeleton } from "@/ui/states"; import { Skeleton } from "@/ui/skeleton"; @@ -31,9 +31,9 @@ import { profileName } from "./describe"; import { remoteStatus, type Tone } from "./Switcher"; /** 「9 月 20 日」/「Sep 20」 */ -function day(ms: number, lang: "zh" | "en"): string { - return new Date(ms).toLocaleDateString(lang === "zh" ? "zh-CN" : "en-US", { - month: lang === "zh" ? "long" : "short", +function day(ms: number, lang: Lang): string { + return new Date(ms).toLocaleDateString(localeTag(lang), { + month: lang === "en" ? "short" : "long", day: "numeric", }); } diff --git a/src/connection/connection.i18n.tsx b/src/connection/connection.i18n.tsx index 4d2415c5..82effb1c 100644 --- a/src/connection/connection.i18n.tsx +++ b/src/connection/connection.i18n.tsx @@ -349,4 +349,481 @@ export const connText = messages( lastUsed: "Last used", connect: "Connect", }, + { + "zh-Hant": { + local: ("本機"), + localNote: (dir: string) => `${dir} · 內建,不可刪除`, + switcherTip: "切換連線", + menuTitle: "連線", + addRemote: "新增遠端連線…", + manage: "管理連線…", + connected: "已連線", + connecting: "正在連線", + unlinked: "未連線", + title: "連線", + add: "新增遠端連線", + intro: isMac + ? "應用同一時間連線一個 core。連線到遠端 core 時,本機 core 停止執行,本機資料保留。" + : "應用同一時間連線一個 core。連線到遠端 core 時,本機的 core 停止執行,本機資料保留。", + current: "當前", + switchTo: "切換到此連線", + switchShort: "切換", + lastConnected: (when: string) => `上次連線 ${when}`, + neverConnected: "尚未連線", + startupLabel: "啟動時連線", + startupLast: "上次使用的連線", + startupLocal: ("本機"), + startupHint: isLinux + ? "連續兩次啟動未能完成時,下次啟動先顯示連線選擇。" + : `按住 ${holdZh} 鍵啟動應用時,先顯示連線選擇。`, + deleteTitle: (name: string) => `刪除連線「${name}」`, + deleteBody: "儲存在本機的金鑰一併刪除。伺服器上的 core 不受影響。", + addTitle: "新增遠端連線", + editTitle: "編輯連線", + dialogDesc: "連線到執行在另一臺機器上的 ThinkWatch core。", + name: "名稱", + hostHint: "主機名或 IP 地址。", + port: "控制埠", + portHint: (code: Code) => <>伺服器配置中 {code("listen.control.remote.port")} 的值。, + key: "金鑰", + keyHint: (code: Code) => (<> + 在伺服器上執行 {code("twcore control-key")} 獲取。僅儲存在本機,只有當前使用者可以讀取。 + ), + test: "測試連線", + testOk: (version: string, gateway: string | null) => `連線成功 · core ${version}${gateway ? ` · 閘道器 ${gateway}` : ""}`, + saveAndSwitch: "儲存並切換", + enterName: "填寫名稱", + nameTaken: "已有同名的連線", + enterHost: "填寫地址", + badHost: "地址格式不正確", + badPort: "埠應為 1–65535 之間的整數", + enterKey: "填寫金鑰", + badKey: "金鑰應為 64 位十六進位制字元", + unreachable: (addr: string) => `無法連線到 ${addr}`, + unreachableNext: (code: Code) => (<>檢查地址和埠,以及伺服器配置中 {code("listen.control.remote")} 是否已啟用。), + timeoutNext: (code: Code) => (<>連線超時。檢查地址和埠,以及伺服器配置中 {code("listen.control.remote")} 是否已啟用。), + closed: "連線被伺服器關閉", + closedNext: (code: Code) => (<>本機地址可能不在伺服器配置 {code("listen.control.remote.allow_from")} 中。), + wrongKey: "金鑰不正確", + wrongKeyNext: (code: Code) => <>在伺服器上執行 {code("twcore control-key")} 檢視當前金鑰。, + mismatch: (theirs: string, ours: string) => `版本不一致:伺服器 core ${theirs},本應用需要 ${ours}`, + mismatchNext: (code: Code, command: string) => (<>在伺服器上執行 {code(command)} 安裝本應用需要的版本,然後重新連線。), + reasonTimeout: "連線超時", + reasonUnreachable: "無法訪問該地址", + testingTitle: (name: string) => `正在連線 ${name}…`, + failedTitle: (name: string) => `無法切換到 ${name}`, + confirmTitle: (name: string) => `切換到 ${name}`, + switchedTo: (name: string) => `已切換到 ${name}`, + adoptedWarn: (a: Adopted) => { + const at = a.local_addr ? ` ${a.local_addr}` : ""; + if (!anyInWsl(a)) + return `已接管的 ${a.count} 個用戶端仍指向本機閘道器${at}。`; + const parts = a.places.map((p) => `${p.distro === null ? (isMac ? "這臺 Mac" : "這臺電腦") : `WSL · ${p.distro}`} ${p.count} 個`); + return `已接管的用戶端仍指向本機閘道器${at}:${parts.join("、")}。`; + }, + adoptedWarnNext: (name: string) => `切換後本機閘道器停止,這些用戶端的請求會失敗,直到重新連線本機,或在用戶端頁將它們改為指向 ${name}。`, + retarget: (name: string) => `同時將這些用戶端改為指向 ${name}`, + localStops: "本機 core 將在在途請求結束後停止", + localKept: ",本機的配置、金鑰和請求歷史保留。", + remoteConfig: (name: string) => `切換後,上游、路由、金鑰等頁面顯示和修改的是 ${name} 上的配置。`, + switchAction: "切換", + editConnection: "編輯連線", + keyUnreadable: "無法讀取儲存在本機的金鑰,請在編輯連線時重新填寫。", + gone: "該連線已被刪除。", + cannotConnect: (name: string) => `無法連線到 ${name}`, + connectingTo: (name: string) => `正在連線 ${name}`, + retry: "重試", + retryIn: (attempt: number, secs: number) => `第 ${attempt} 次,${secs} 秒後`, + retrying: (attempt: number) => `第 ${attempt} 次,正在連線`, + retryNow: "立即重試", + switchToLocal: "切換到本機", + autoResume: "連線恢復後自動回到上次開啟的頁面。", + mismatchTitle: (name: string) => `${name} 上的 core 版本與本應用不一致`, + server: "伺服器", + appNeeds: "本應用需要", + runOnServer: (version: string) => `伺服器需要執行 core ${version}。在伺服器上執行以下命令安裝此版本,伺服器上現有的版本較新或較舊均適用:`, + reconnect: "重新連線", + configBroken: "配置檔案有誤,閘道器未啟動", + configBrokenLead: "core 無法讀取配置檔案,用戶端的請求暫不轉發。修正配置檔案或從備份恢復可用的版本即可恢復轉發。", + file: "檔案", + lineAt: (line: number, stage: string) => `第 ${line} 行 · ${stage}錯誤`, + stageOnly: (stage: string) => `${stage}錯誤`, + openConfigFile: "開啟配置檔案", + restoreFromBackup: "從備份恢復…", + configBrokenResume: "儲存修正後的配置後,閘道器自動恢復。", + configBrokenHeldTitle: "更新後的配置檔案有誤", + configBrokenHeld: "新版本無法讀取配置檔案。閘道器暫按更新前的配置執行,用戶端的請求照常轉發;修正配置檔案或從備份恢復可用的版本後,自動切換到新版本。", + configBrokenHeldResume: "儲存修正後的配置後,自動切換到新版本。", + lostBanner: (name: string, attempt: number) => attempt > 0 + ? `與 ${name} 的連線已斷開,正在重連(第 ${attempt} 次)。頁面內容為斷開前的狀態,暫不可修改。` + : `與 ${name} 的連線已斷開,正在重連。頁面內容為斷開前的狀態,暫不可修改。`, + pickTitle: "選擇連線", + pickOption: `按住 ${holdZh} 鍵啟動。選擇這次要連線的 core。`, + pickUnfinished: "上次啟動未能完成。選擇這次要連線的 core。", + connect: "連線", + }, + ja: { + local: isMac ? "この Mac" : "この端末", + localNote: (dir: string) => `${dir} · 組み込みの接続(削除不可)`, + localCore: "ローカル core", + localStopped: "ローカル core · 停止中", + switcherTip: "接続を切り替え", + menuTitle: "接続", + addRemote: "リモート接続を追加…", + manage: "接続を管理…", + connected: "接続済み", + connecting: "接続中", + unlinked: "未接続", + title: "接続", + add: "リモート接続を追加", + intro: "同時に接続できる core は 1 つです。リモート core に接続している間はローカル core が停止します。ローカルのデータは保持されます。", + current: "現在の接続", + switchTo: "この接続に切り替え", + switchShort: "切り替え", + actionsFor: (name: string) => `「${name}」の操作`, + lastConnected: (when: string) => `最終接続:${when}`, + neverConnected: "接続履歴なし", + coreVersion: (v: string) => `core ${v}`, + startupLabel: "起動時の接続", + startupLast: "最後に使った接続", + startupLocal: isMac ? "この Mac" : "この端末", + startupHint: isLinux + ? "起動に 2 回続けて失敗すると、次回の起動時に接続の選択画面が表示されます。" + : `${holdZh} キーを押しながらアプリを開くと、接続を選択できます。`, + deleteTitle: (name: string) => `接続「${name}」を削除`, + deleteBody: "この端末に保存したキーも削除します。サーバー上の core には影響しません。", + addTitle: "リモート接続を追加", + editTitle: "接続を編集", + dialogDesc: "別の端末で実行中の ThinkWatch core に接続します。", + name: "名前", + namePlaceholder: "例:home-server", + host: "アドレス", + hostHint: "ホスト名または IP アドレス。", + port: "制御ポート", + portHint: (code: Code) => <>サーバーの設定にある {code("listen.control.remote.port")} の値です。, + key: "制御キー", + keyHint: (code: Code) => <>サーバーで {code("twcore control-key")} を実行して取得します。この端末に保存され、現在のユーザーだけが読み取れます。, + test: "接続をテスト", + testOk: (version: string, gateway: string | null) => `接続成功 · core ${version}${gateway ? ` · ゲートウェイ ${gateway}` : ""}`, + saveAndSwitch: "保存して切り替え", + enterName: "名前を入力してください", + nameTaken: "同じ名前の接続がすでにあります", + enterHost: "アドレスを入力してください", + badHost: "アドレスが無効です", + badPort: "ポートには 1〜65535 の整数を入力してください", + enterKey: "キーを入力してください", + badKey: "キーは 64 桁の16進数で入力してください", + unreachable: (addr: string) => `${addr} に接続できません`, + unreachableNext: (code: Code) => <>アドレスとポート、およびサーバーの設定で {code("listen.control.remote")} が有効か確認してください。, + timeoutNext: (code: Code) => <>接続がタイムアウトしました。アドレスとポート、およびサーバーの設定で {code("listen.control.remote")} が有効か確認してください。, + closed: "サーバーが接続を閉じました", + closedNext: (code: Code) => <>サーバーの設定の {code("listen.control.remote.allow_from")} に、この端末のアドレスが登録されているか確認してください。, + wrongKey: "キーが正しくありません", + wrongKeyNext: (code: Code) => <>サーバーで {code("twcore control-key")} を実行して現在のキーを確認してください。, + mismatch: (theirs: string, ours: string) => `バージョンが一致しません。サーバーは core ${theirs}、このアプリには ${ours} が必要です。`, + mismatchNext: (code: Code, command: string) => <>サーバーで {code(command)} を実行して必要なバージョンをインストールし、再接続してください。, + reasonTimeout: "接続がタイムアウトしました", + reasonUnreachable: "アドレスに到達できません", + testingTitle: (name: string) => `${name} に接続中…`, + failedTitle: (name: string) => `${name} に切り替えられませんでした`, + confirmTitle: (name: string) => `${name} に切り替え`, + switchedTo: (name: string) => `${name} に切り替えました`, + adoptedWarn: (a: Adopted) => { + const at = a.local_addr ? ` ${a.local_addr}` : ""; + const lead = `${a.count} 件のクライアントは引き続きローカルゲートウェイ${at}を参照しています`; + if (!anyInWsl(a)) + return `${lead}。`; + const parts = a.places.map((p) => `${p.distro === null ? "この端末" : `WSL · ${p.distro}`}:${p.count} 件`); + return `${lead}(${parts.join("、")})。`; + }, + adoptedWarnNext: (name: string) => `切り替えるとローカルゲートウェイが停止します。ローカルに戻すか、クライアントページで接続先を ${name} に変えるまで、これらのリクエストは失敗します。`, + retarget: (name: string) => `これらのクライアントの接続先も ${name} に変更する`, + localStops: "処理中のリクエストが完了するとローカル core が停止します", + localKept: "。ローカルの設定、キー、リクエスト履歴は保持されます。", + remoteConfig: (name: string) => `切り替え後は、アップストリーム、ルーティング、キーなどのページで ${name} の設定を表示・変更します。`, + switchAction: "切り替え", + editConnection: "接続を編集", + keyUnreadable: "この端末に保存されたキーを読み取れませんでした。接続を編集して再入力してください。", + gone: "この接続は削除されました。", + cannotConnect: (name: string) => `${name} に接続できません`, + connectingTo: (name: string) => `${name} に接続しています`, + address: "アドレス", + reason: "原因", + retry: "再試行", + retryIn: (attempt: number, secs: number) => `${secs} 秒後に再試行(${attempt} 回目)`, + retrying: (attempt: number) => `接続中(${attempt} 回目)`, + retryNow: "今すぐ再試行", + switchToLocal: "ローカルに切り替え", + autoResume: "接続が復旧すると、開いていたページに戻ります。", + mismatchTitle: (name: string) => `${name} の core のバージョンがこのアプリと一致しません`, + server: "サーバー", + appNeeds: "アプリが必要とするバージョン", + runOnServer: (version: string) => `サーバーには core ${version} が必要です。現在のバージョンにかかわらず、サーバーで次のコマンドを実行してインストールしてください。`, + reconnect: "再接続", + configBroken: "設定ファイルにエラーがあり、ゲートウェイが停止しています", + safeMode: "セーフモード", + configBrokenLead: "core が設定ファイルを読み取れないため、リクエストを転送していません。設定を修正するか、正常なバックアップを復元してください。", + file: "ファイル", + location: "場所", + lineAt: (line: number, stage: string) => `${line} 行目 · ${stage}エラー`, + stageOnly: (stage: string) => `${stage}エラー`, + openConfigFile: "設定ファイルを開く", + restoreFromBackup: "バックアップから復元…", + configBrokenResume: "修正した設定を保存すると、ゲートウェイが自動的に再開します。", + configBrokenHeldTitle: "更新後の設定ファイルにエラーがあります", + configBrokenHeld: "新しいバージョンで設定ファイルを読み取れません。更新前の設定で転送を続けています。設定を修正するか、正常なバックアップを復元すると新しいバージョンに切り替わります。", + configBrokenHeldResume: "修正した設定を保存すると、新しいバージョンに自動で切り替わります。", + lostBanner: (name: string, attempt: number) => `${name} との接続が切断されました。再接続中${attempt > 0 ? `(${attempt} 回目)` : ""}。復旧するまでは切断前のデータを表示し、変更はできません。`, + pickTitle: "接続を選択", + pickOption: `起動時に ${holdZh} キーが押されました。接続する core を選んでください。`, + pickUnfinished: "前回の起動が完了しませんでした。接続する core を選んでください。", + lastUsed: "最後に使用", + connect: "接続", + }, + ko: { + local: (isMac ? "이 Mac" : "이 컴퓨터"), + localNote: (dir: string) => `${dir} · 기본 연결(삭제할 수 없음)`, + localCore: "로컬 core", + localStopped: "로컬 core · 중지됨", + switcherTip: "연결 전환", + menuTitle: "연결", + addRemote: "원격 연결 추가…", + manage: "연결 관리…", + connected: "연결됨", + connecting: "연결 중", + unlinked: "연결 안 됨", + title: "연결", + add: "원격 연결 추가", + current: "현재", + switchTo: "이 연결로 전환", + switchShort: "전환", + actionsFor: (name: string) => `「${name}」 작업`, + lastConnected: (when: string) => `마지막 연결: ${when}`, + neverConnected: "연결 기록 없음", + startupLabel: "시작 시 연결", + startupLast: "마지막으로 사용한 연결", + startupLocal: (isMac ? "이 Mac" : "이 컴퓨터"), + startupHint: isLinux + ? "두 번 연속 시작에 실패하면 다음 실행 시 연결 선택 화면이 열립니다." + : `앱을 열 때 ${holdZh} 키를 누르고 있으면 연결을 먼저 선택할 수 있습니다.`, + deleteTitle: (name: string) => `연결 「${name}」 삭제`, + deleteBody: "이 컴퓨터에 저장된 키도 삭제됩니다. 서버의 core에는 영향이 없습니다.", + addTitle: "원격 연결 추가", + editTitle: "연결 편집", + dialogDesc: "다른 컴퓨터에서 실행 중인 ThinkWatch core에 연결합니다.", + name: "이름", + namePlaceholder: "예: home-server", + host: "주소", + hostHint: "호스트 이름 또는 IP 주소.", + port: "제어 포트", + key: "키", + test: "연결 테스트", + saveAndSwitch: "저장 후 전환", + enterName: "이름을 입력하세요.", + nameTaken: "같은 이름의 연결이 이미 있습니다.", + enterHost: "주소를 입력하세요.", + badHost: "주소가 올바르지 않습니다.", + badPort: "포트는 1~65535 사이의 정수여야 합니다.", + enterKey: "키를 입력하세요.", + badKey: "키는 16진수 64자리여야 합니다.", + unreachable: (addr: string) => `${addr}에 연결할 수 없습니다.`, + closed: "서버가 연결을 끊었습니다.", + wrongKey: "키가 올바르지 않습니다.", + reasonTimeout: "연결 시간이 초과되었습니다.", + reasonUnreachable: "주소에 연결할 수 없습니다.", + testingTitle: (name: string) => `${name}에 연결 중…`, + failedTitle: (name: string) => `${name}(으)로 전환할 수 없습니다.`, + confirmTitle: (name: string) => `${name}(으)로 전환`, + switchedTo: (name: string) => `${name}(으)로 전환했습니다.`, + switchAction: "전환", + editConnection: "연결 편집", + gone: "삭제된 연결입니다.", + cannotConnect: (name: string) => `${name}에 연결할 수 없습니다.`, + address: "주소", + reason: "원인", + retry: "다시 시도", + retryNow: "지금 다시 시도", + server: "서버", + reconnect: "다시 연결", + safeMode: "안전 모드", + file: "파일", + location: "위치", + openConfigFile: "설정 파일 열기", + restoreFromBackup: "백업에서 복원…", + pickTitle: "연결 선택", + lastUsed: "최근 사용", + connect: "연결", + intro: "앱은 한 번에 core 하나에 연결합니다. 원격 core에 연결하면 이 컴퓨터의 core가 중지됩니다. 로컬 데이터는 유지됩니다.", + portHint: (code: Code) => <>서버 설정의 {code("listen.control.remote.port")} 값입니다., + keyHint: (code: Code) => <>서버에서 {code("twcore control-key")} 명령을 실행하면 키를 확인할 수 있습니다. 키는 이 컴퓨터에만 저장되며 현재 사용자만 읽을 수 있습니다., + testOk: (version: string, gateway: string | null) => `연결 성공 · core ${version}${gateway ? ` · 게이트웨이 ${gateway}` : ""}`, + unreachableNext: (code: Code) => <>주소와 포트가 맞는지, 서버 설정의 {code("listen.control.remote")}이(가) 켜져 있는지 확인하세요., + timeoutNext: (code: Code) => <>연결 시간이 초과되었습니다. 주소와 포트가 맞는지, 서버 설정의 {code("listen.control.remote")}이(가) 켜져 있는지 확인하세요., + closedNext: (code: Code) => <>서버 설정의 {code("listen.control.remote.allow_from")}에 이 컴퓨터의 주소가 들어 있는지 확인하세요., + wrongKeyNext: (code: Code) => <>서버에서 {code("twcore control-key")} 명령으로 현재 키를 확인하세요., + mismatch: (theirs: string, ours: string) => `버전이 일치하지 않습니다. 서버는 core ${theirs}을(를) 실행 중이며, 앱에는 ${ours}이(가) 필요합니다.`, + mismatchNext: (code: Code, command: string) => <>서버에서 {code(command)} 명령으로 필요한 버전을 설치한 후 다시 연결하세요., + adoptedWarn: (a: Adopted) => { + const at = a.local_addr ? ` ${a.local_addr}` : ""; + const lead = `연결된 클라이언트 ${a.count}개가 여전히 로컬 게이트웨이${at}을(를) 사용합니다`; + if (!anyInWsl(a)) return `${lead}.`; + const places = a.places.map((p) => `${p.distro === null ? "이 컴퓨터" : `WSL · ${p.distro}`}: ${p.count}개`); + return `${lead}(${places.join(", ")}).`; + }, + adoptedWarnNext: (name: string) => ` 전환하면 로컬 게이트웨이가 중지됩니다. 로컬로 돌아오거나 클라이언트 페이지에서 ${name}(으)로 설정하기 전까지 이 클라이언트의 요청은 실패합니다.`, + retarget: (name: string) => `이 클라이언트의 연결 대상도 ${name}(으)로 변경`, + localStops: "진행 중인 요청을 처리한 뒤 로컬 core가 중지됩니다", + localKept: ". 설정, 키 및 요청 기록은 유지됩니다.", + remoteConfig: (name: string) => `전환 후에는 업스트림, 라우팅, 키 등의 페이지에서 ${name}의 설정을 확인하고 변경할 수 있습니다.`, + keyUnreadable: "이 컴퓨터에 저장된 키를 읽을 수 없습니다. 연결을 편집하여 키를 다시 입력하세요.", + connectingTo: (name: string) => `${name}에 연결 중`, + retryIn: (attempt: number, secs: number) => `${secs}초 후 다시 시도(${attempt}번째)`, + retrying: (attempt: number) => `연결 중(${attempt}번째 시도)`, + switchToLocal: isMac ? "이 Mac으로 전환" : "이 컴퓨터로 전환", + autoResume: "연결이 복구되면 현재 열려 있던 페이지로 돌아갑니다.", + mismatchTitle: (name: string) => `${name}의 core 버전이 앱과 일치하지 않습니다`, + appNeeds: "앱에 필요한 버전", + runOnServer: (version: string) => `서버에 core ${version}이(가) 필요합니다. 현재 버전과 관계없이 서버에서 다음 명령을 실행하세요.`, + configBroken: "설정 파일 오류로 게이트웨이가 중지되었습니다", + configBrokenLead: "core가 설정 파일을 읽을 수 없어 클라이언트 요청을 전달하지 않습니다. 설정을 수정하거나 정상적인 백업을 복원하세요.", + lineAt: (line: number, stage: string) => `${line}번째 줄 · ${stage} 오류`, + stageOnly: (stage: string) => `${stage} 오류`, + configBrokenResume: "수정한 설정을 저장하면 게이트웨이가 자동으로 다시 작동합니다.", + configBrokenHeldTitle: "업데이트 후 설정 파일에 오류가 있습니다", + configBrokenHeld: "새 버전이 설정 파일을 읽을 수 없습니다. 업데이트 이전 설정으로 요청을 계속 전달합니다. 설정을 수정하거나 정상적인 백업을 복원하면 새 버전으로 전환됩니다.", + configBrokenHeldResume: "수정한 설정을 저장하면 새 버전으로 자동 전환합니다.", + lostBanner: (name: string, attempt: number) => `${name} 연결이 끊겼습니다. 다시 연결 중${attempt > 0 ? `(${attempt}번째 시도)` : ""}입니다. 연결이 복구될 때까지 이전 상태를 표시하며 변경할 수 없습니다.`, + pickOption: `시작할 때 ${holdZh} 키를 눌렀습니다. 연결할 core를 선택하세요.`, + pickUnfinished: "지난 번 실행이 완료되지 않았습니다. 연결할 core를 선택하세요.", + }, + es: { + local: (isMac ? "Este Mac" : "Este equipo"), + localNote: (dir: string) => `${dir} · Conexión integrada, no se puede eliminar`, + localCore: "Core local", + localStopped: "Core local · Detenido", + switcherTip: "Cambiar de conexión", + menuTitle: "Conexión", + addRemote: "Añadir conexión remota…", + manage: "Gestionar conexiones…", + connected: "Conectado", + connecting: "Conectando", + unlinked: "Sin conexión", + title: "Conexión", + add: "Añadir conexión remota", + intro: isMac + ? "La aplicación se conecta a un núcleo a la vez. Mientras que está conectado a un centro remoto, el núcleo en este Mac deja de funcionar; sus datos se mantienen." + : "La aplicación se conecta a un núcleo a la vez. Si bien está conectada a un centro remoto, el núcleo de este equipo deja de funcionar; sus datos se mantienen.", + current: "Actual", + switchTo: "Cambiar a esta conexión", + switchShort: "Cambiar", + actionsFor: (name: string) => `Acciones para «${name}»`, + lastConnected: (when: string) => `Última conexión: ${when}`, + neverConnected: "Sin conexiones anteriores", + coreVersion: (v: string) => `Núcleo ${v}`, + startupLabel: "Conexión al iniciar", + startupLast: "Última conexión utilizada", + startupLocal: (isMac ? "Este Mac" : "Este equipo"), + startupHint: isLinux + ? "Si el inicio falla dos veces seguidas, la próxima vez se mostrará el selector de conexión." + : `Mantén pulsada la tecla ${(isMac ? "Opción" : "Alt")} al abrir la aplicación para elegir una conexión.`, + deleteTitle: (name: string) => `Eliminar la conexión «${name}»`, + deleteBody: "También se elimina la clave guardada en este equipo. El core del servidor sigue funcionando.", + addTitle: "Añadir conexión remota", + editTitle: "Editar conexión", + dialogDesc: "Conéctate a un core de ThinkWatch en otro equipo.", + name: "Nombre", + namePlaceholder: "p. ej., home-server", + host: "Dirección", + hostHint: "Nombre del equipo o dirección IP.", + port: "Puerto de control", + portHint: (code: Code) => <>El valor de {code("listen.control.remote.port")} en la configuración del servidor., + key: "Clave", + keyHint: (code: Code) => (<> + Corre {code("twcore control-key")} en el servidor para conseguirlo. Guardado sólo en este equipo, legible por el usuario actual solo. + ), + test: "Probar conexión", + testOk: (version: string, gateway: string | null) => `· núcleo conectado ${version}${gateway ? ` · puerta de entrada ${gateway}` : ""}`, + saveAndSwitch: "Guardar y cambiar", + enterName: "Introduce un nombre.", + nameTaken: "Ya existe una conexión con ese nombre.", + enterHost: "Introduce una dirección.", + badHost: "La dirección no es válida.", + badPort: "El puerto debe ser un entero entre 1 y 65535.", + enterKey: "Introduce la clave.", + badKey: "La clave debe tener 64 caracteres hexadecimales.", + unreachable: (addr: string) => `No se puede conectar con ${addr}.`, + unreachableNext: (code: Code) => (<>Compruebe la dirección y el puerto, y si {code("listen.control.remote")} está activado en la configuración del servidor.), + timeoutNext: (code: Code) => (<> + El tiempo de conexión se ha agotado. Compruebe la dirección y el puerto, y si {code("listen.control.remote")} is + enabled in the server's config. + ), + closed: "El servidor cerró la conexión.", + closedNext: (code: Code) => (<>La dirección de esta computadora puede faltar de {code("listen.control.remote.allow_from")} en la configuración del servidor.), + wrongKey: "La clave no es correcta.", + wrongKeyNext: (code: Code) => <>Corre {code("twcore control-key")} en el servidor para ver la clave actual., + mismatch: (theirs: string, ours: string) => `Desajuste de versiones: el servidor ejecuta el núcleo ${theirs}; esta aplicación necesita ${ours}`, + mismatchNext: (code: Code, command: string) => (<>Corre {code(command)} en el servidor para instalar la versión que necesita esta aplicación, luego vuelva a conectarse.), + reasonTimeout: "Se agotó el tiempo de conexión.", + reasonUnreachable: "No se puede acceder a la dirección.", + testingTitle: (name: string) => `Conectando con ${name}…`, + failedTitle: (name: string) => `No se puede cambiar a ${name}.`, + confirmTitle: (name: string) => `Cambiar a ${name}`, + switchedTo: (name: string) => `Se cambió a ${name}.`, + adoptedWarn: (a: Adopted) => { + const at = a.local_addr ? ` ${a.local_addr}` : ""; + const lead = a.count === 1 + ? `1 cliente conectado sigue apuntando a la puerta de enlace local${at}` + : `${a.count} Los clientes conectados todavía apuntan a la puerta de enlace local${at}`; + if (!anyInWsl(a)) + return `${lead}.`; + const parts = a.places.map((p) => (p.distro === null ? `${p.count} el ${(isMac ? "este Mac" : "esta computadora")}` : `${p.count} en WSL · ${p.distro}`)); + return `${lead}: ${parts.join(", ")}.`; + }, + adoptedWarnNext: (name: string) => ` Después del interruptor, la puerta de enlace local se detiene y sus solicitudes fallan hasta que la aplicación se desplace hacia atrás, o hasta que se apunten a ${name} en la página Clientes.`, + retarget: (name: string) => `También señale a estos clientes en ${name}`, + localStops: "El núcleo local se detiene una vez finalizadas las solicitudes en curso", + localKept: "; su configuración, claves e historial de peticiones se mantienen.", + remoteConfig: (name: string) => `Después del conmutador, los Upstreams, Routing, Keys y otras páginas muestran y cambian la configuración en ${name}.`, + switchAction: "Cambiar", + editConnection: "Editar conexión", + keyUnreadable: "La clave guardada en este equipo no se pudo leer. Ingrese de nuevo editando la conexión.", + gone: "Se eliminó esta conexión.", + cannotConnect: (name: string) => `No se puede conectar con ${name}.`, + connectingTo: (name: string) => `Conectando a ${name}`, + address: "Dirección", + reason: "Motivo", + retry: "Reintentar", + retryIn: (attempt: number, secs: number) => `Intento ${attempt}, en ${secs} s`, + retrying: (attempt: number) => `Intento ${attempt}, conexión`, + retryNow: "Reintentar ahora", + switchToLocal: isMac ? "Cambiar a este Mac" : "Cambiar a este ordenador", + autoResume: "Una vez restaurada la conexión, la aplicación vuelve a la página que estaba abierta.", + mismatchTitle: (name: string) => `El núcleo en ${name} no coincide con esta aplicación`, + server: "Servidor", + appNeeds: "Esta aplicación necesita", + runOnServer: (version: string) => `El servidor necesita núcleo ${version}. Ejecute este comando en el servidor para instalar esa versión, ya sea que el instalado sea más nuevo o más antiguo:`, + reconnect: "Volver a conectar", + configBroken: "El archivo de configuraciónuración tiene un error; la puerta de enlace no se está ejecutando", + safeMode: "Modo seguro", + configBrokenLead: "Core no puede leer su archivo de configuraciónuración, por lo que las solicitudes del cliente no se reenvían. Corrija el archivo o restaurar una versión de trabajo de las copias de seguridad para recuperar.", + file: "Archivo", + location: "Ubicación", + lineAt: (line: number, stage: string) => `Error en la línea ${line} · ${stage}`, + stageOnly: (stage: string) => `Error ${stage}`, + openConfigFile: "Abrir archivo de configuración", + restoreFromBackup: "Restaurar desde una copia…", + configBrokenResume: "Una vez que se guarda una configuración corregida, la puerta de enlace se reanuda por sí sola.", + configBrokenHeldTitle: "El archivo de configuraciónuración tiene un error después de la actualización", + configBrokenHeld: "La nueva versión no puede leer el archivo de configuraciónuración. La puerta de enlace se ejecuta con la configuración de antes de la actualización y sigue reenviando peticiones del cliente; arreglar el archivo o restaurar una versión de trabajo de las copias de seguridad para cambiar a la nueva versión.", + configBrokenHeldResume: "Una vez que se guarda una configuración corregida, la nueva versión se hace cargo por sí sola.", + lostBanner: (name: string, attempt: number) => attempt > 0 + ? `Desconectado de ${name}. Reconectar (intento ${attempt}). La página muestra el estado anterior a la desconexión y no se puede cambiar por ahora.` + : `Desconectado de ${name}. Reconectar. La página muestra el estado antes de la desconexión y no se puede cambiar por ahora.`, + pickTitle: "Elegir una conexión", + pickOption: `${(isMac ? "Opción" : "Alt")} se celebró en el inicio. Elija el núcleo para conectarse a esta vez.`, + pickUnfinished: "La última startup no terminó. Elija el núcleo para conectarse a esta vez.", + lastUsed: "Última usada", + connect: "Conectar", + }, + }, ); diff --git a/src/connection/remote.i18n.tsx b/src/connection/remote.i18n.tsx index e5218233..a48ca064 100644 --- a/src/connection/remote.i18n.tsx +++ b/src/connection/remote.i18n.tsx @@ -89,4 +89,94 @@ export const remoteText = messages( "Reads this profile from the AWS credential files of the user running core on the server (~/.aws/credentials, ~/.aws/config). Only profiles that hold access keys are supported.", systemProxy: "The server's system proxy", }, + { + "zh-Hant": { + clientsNote: (name: string, gateway: string) => `此處檢查和修改的是${(isMac ? "這臺 Mac 上" : "這臺電腦上")}的用戶端配置,使其指向 ${name} 的閘道器 ${gateway};伺服器上的用戶端不受影響。`, + mcpNote: (name: string) => `此處檢查和修改的是${(isMac ? "這臺 Mac 上" : "這臺電腦上")}用戶端的 MCP 配置、技能與鉤子;${name} 上的不受影響。`, + localLeft: (n: number, addr: string) => `${n} 個已接管的用戶端仍指向本機閘道器 ${addr}。本機閘道器已停止,這些用戶端的請求會失敗。`, + localLeftHere: (n: number, addr: string) => `${(isMac ? "這臺 Mac 上" : "這臺電腦上")}有 ${n} 個已接管的用戶端仍指向本機閘道器 ${addr}。本機閘道器已停止,這些用戶端的請求會失敗。`, + retargetTo: (name: string) => `改為指向 ${name}`, + retargeted: (name: string, clients: string[]) => `已改為指向 ${name}:${clients.join("、")}。`, + retargetFailedTitle: (name: string) => `以下用戶端未能改為指向 ${name}`, + retargetNone: "無需修改任何用戶端。", + appGroup: `${(isMac ? "這臺 Mac 上" : "這臺電腦上")}的應用`, + controlReadOnly: "遠端控制的監聽與金鑰只能在伺服器上修改。", + connection: "連線", + serverCore: "伺服器 core", + uninstallServer: (name: string) => `隻影響${(isMac ? "這臺 Mac" : "這臺電腦")}:${name} 上的配置和資料不受影響。`, + deviceOnly: (name: string) => `瀏覽器登入完成後會回到執行 core 的那臺機器,而當前連線的是 ${name},因此只能用裝置碼登入。`, + headersHint: "隨每個請求傳送。值中的 ${變數名} 讀取伺服器上 core 程序的環境變數。", + keyHint: "${變數名} 讀取伺服器上 core 程序的環境變數。", + profileHint: "讀取伺服器上執行 core 的使用者的 AWS 憑證檔案(~/.aws/credentials、~/.aws/config)中的這個 profile,只支援寫有訪問金鑰的 profile。", + systemProxy: "伺服器的系統代理", + }, + ja: { + clientsNote: (name: string, gateway: string) => `この端末のクライアント設定を確認・変更し、${name} のゲートウェイ(${gateway})に接続します。サーバー上のクライアントには影響しません。`, + mcpNote: (name: string) => `この端末のクライアントの MCP 設定、スキル、フックを確認・変更します。${name} 上の設定には影響しません。`, + localLeft: (n: number, addr: string) => `${n} 件のクライアントがローカルゲートウェイ ${addr} を参照しています。ゲートウェイが停止しているため、リクエストは失敗します。`, + localLeftHere: (n: number, addr: string) => `この端末の ${n} 件のクライアントがローカルゲートウェイ ${addr} を参照しています。ゲートウェイが停止しているため、リクエストは失敗します。`, + retargetTo: (name: string) => `接続先を ${name} に変更`, + retargeted: (name: string, clients: string[]) => `接続先を ${name} に変更しました:${clients.join("、")}。`, + retargetFailedTitle: (name: string) => `次のクライアントの接続先を ${name} に変更できませんでした`, + retargetNone: "変更が必要なクライアントはありません。", + sep: ":", + appGroup: "この端末のアプリ", + serverGroup: (name: string) => `${name} の設定`, + controlReadOnly: "リモート制御のリッスン設定とキーはサーバーで変更してください。", + connection: "接続", + serverCore: "サーバーの core", + uninstallServer: (name: string) => `この端末のみに適用されます。${name} 上の設定やデータには影響しません。`, + deviceOnly: (name: string) => `ブラウザーでのログインは core を実行する端末に戻ります。現在は ${name} に接続しているため、デバイスコードでログインしてください。`, + headersHint: "リクエストごとに送信します。値に ${NAME} を指定すると、サーバーの core プロセスの環境変数を参照します。", + keyHint: "${NAME} はサーバーの core プロセスの環境変数を参照します。", + profileHint: "サーバー上で core を実行しているユーザーの AWS 認証情報ファイル(~/.aws/credentials、~/.aws/config)からプロファイルを読み込みます。アクセスキーを含むプロファイルに対応しています。", + systemProxy: "サーバーのシステムプロキシ", + }, + ko: { + connection: "연결", + uninstallServer: (name: string) => `${(isMac ? "이 Mac" : "이 컴퓨터")} only: the configuration and data on ${name} are not affected.`, + clientsNote: (name: string, gateway: string) => `이 컴퓨터의 클라이언트 설정을 확인하고 수정해 ${name}의 게이트웨이(${gateway})에 연결할 수 있습니다. 서버의 클라이언트에는 영향이 없습니다.`, + mcpNote: (name: string) => `이 컴퓨터에서 클라이언트의 MCP 설정, 스킬 및 훅을 확인하고 수정합니다. ${name}의 설정에는 영향이 없습니다.`, + localLeft: (n: number, addr: string) => `연결된 클라이언트 ${n}개가 여전히 로컬 게이트웨이 ${addr}을(를) 사용합니다. 로컬 게이트웨이가 중지되어 요청이 실패합니다.`, + localLeftHere: (n: number, addr: string) => `이 컴퓨터의 클라이언트 ${n}개가 여전히 로컬 게이트웨이 ${addr}을(를) 사용합니다. 로컬 게이트웨이가 중지되어 요청이 실패합니다.`, + retargetTo: (name: string) => `연결 대상을 ${name}(으)로 변경`, + retargeted: (name: string, clients: string[]) => `연결 대상을 ${name}(으)로 변경했습니다: ${clients.join(", ")}.`, + retargetFailedTitle: (name: string) => `다음 클라이언트를 ${name}(으)로 변경하지 못했습니다`, + retargetNone: "변경할 클라이언트가 없습니다.", + appGroup: "이 컴퓨터의 앱", + serverGroup: (name: string) => `${name}의 설정`, + controlReadOnly: "원격 제어 수신 설정과 키는 서버에서 변경할 수 있습니다.", + serverCore: "서버의 core", + deviceOnly: (name: string) => `브라우저 로그인은 core를 실행하는 컴퓨터로 돌아옵니다. 현재 ${name}에 연결되어 있어 기기 코드로만 로그인할 수 있습니다.`, + headersHint: "요청마다 전송합니다. 값에 ${NAME}을 사용하면 서버의 core 프로세스 환경 변수를 읽습니다.", + keyHint: "${NAME}은 서버의 core 프로세스 환경 변수를 읽습니다.", + profileHint: "서버에서 core를 실행하는 사용자의 AWS 인증 정보 파일(~/.aws/credentials, ~/.aws/config)에서 프로필을 읽습니다. 액세스 키가 있는 프로필을 지원합니다.", + systemProxy: "서버의 시스템 프록시", + }, + es: { + clientsNote: (name: string, gateway: string) => `Esta página comprueba y cambia la configuración del cliente en ${(isMac ? "este Mac" : "esta computadora")}, apuntando a la puerta de enlace de ${name} (${gateway}). Los clientes en el servidor no se ven afectados.`, + mcpNote: (name: string) => `Esta página comprueba y cambia la configuración de MCP, las habilidades y los ganchos de los clientes en ${(isMac ? "este Mac" : "esta computadora")}. Aquellos en ${name} no se ven afectados.`, + localLeft: (n: number, addr: string) => n === 1 + ? `1 cliente conectado sigue apuntando a la puerta de enlace local ${addr}. La puerta de entrada local se ha detenido, por lo que sus peticiones fallan.` + : `${n} los clientes conectados todavía apuntan a la puerta local ${addr}. La puerta local se ha detenido, por lo que sus solicitudes fallan.`, + localLeftHere: (n: number, addr: string) => n === 1 + ? `1 cliente conectado en ${(isMac ? "este Mac" : "esta computadora")} sigue apuntando a la puerta local ${addr}. La puerta local se ha detenido, por lo que sus solicitudes fallan.` + : `${n} clientes conectados en ${(isMac ? "este Mac" : "esta computadora")} todavía apuntan a la puerta local ${addr}. La puerta local se ha detenido, por lo que sus solicitudes fallan.`, + retargetTo: (name: string) => `Punto de ${name}`, + retargeted: (name: string, clients: string[]) => `Ahora apunta a ${name}: ${clients.join(", ")}.`, + retargetFailedTitle: (name: string) => `Estos clientes no pudieron señalarse a ${name}`, + retargetNone: "Ningún cliente necesitaba cambiar.", + appGroup: `La aplicación en ${(isMac ? "este Mac" : "esta computadora")}`, + serverGroup: (name: string) => `Configuración en ${name}`, + controlReadOnly: "El oyente de control remoto y su llave sólo se pueden cambiar en el servidor.", + connection: "Conexión", + serverCore: "Núcleo del servidor", + uninstallServer: (name: string) => `${(isMac ? "Este Mac" : "Este equipo")} únicamente: la configuración y los datos en ${name} no se verán afectados.`, + deviceOnly: (name: string) => `Un inicio de sesión del navegador vuelve a la máquina que ejecuta el núcleo, y esta aplicación está conectada a ${name}, por lo que sólo está disponible el inicio de entrada del código del dispositivo.`, + headersHint: "Enviado con cada petición. ${NAME} En un valor se lee una variable de entorno del proceso de núcleo en el servidor.", + keyHint: "${NAME} lee una variable de entorno del proceso central en el servidor.", + profileHint: "Lee este perfil desde los archivos de credencial AWS del usuario que ejecuta el núcleo en el servidor (~/.aws/credentials, ~/.aws/config). Sólo se admiten perfiles que contienen claves de acceso.", + systemProxy: "El proxy del sistema del servidor", + }, + }, ); diff --git a/src/format.i18n.ts b/src/format.i18n.ts index efe805f4..bf5feab4 100644 --- a/src/format.i18n.ts +++ b/src/format.i18n.ts @@ -36,4 +36,43 @@ export const formatText = messages( days: (n: number) => (n === 1 ? "in 1 day" : `in ${n} days`), }, }, + { + "zh-Hant": { + span: { + seconds: (n: number) => `${n} 秒`, + minutes: (n: number) => `${n} 分`, + hours: (n: string) => `${n} 小時`, + }, + resetIn: { + now: "剛剛", + underMinute: "1 分鐘內", + minutes: (n: number) => `${n} 分鐘後`, + hours: (n: number) => `${n} 小時後`, + days: (n: number) => `${n} 天后`, + }, + }, + ja: { + span: { + seconds: (n: number) => `${n} 秒`, + minutes: (n: number) => `${n} 分`, + hours: (n: string) => `${n} 時間`, + }, + resetIn: { + now: "今", + underMinute: "1 分以内", + minutes: (n: number) => `${n} 分後`, + hours: (n: number) => `${n} 時間後`, + days: (n: number) => `${n} 日後`, + }, + }, + es: { + resetIn: { + now: "Ahora", + underMinute: "en un plazo de 1 min", + minutes: (n: number) => `en ${n} min`, + hours: (n: number) => `en ${n} h`, + days: (n: number) => (n === 1 ? "en 1 día" : `en ${n} días`), + }, + }, + }, ); diff --git a/src/guide/guide.i18n.ts b/src/guide/guide.i18n.ts index b7a43d55..8e3e27ff 100644 --- a/src/guide/guide.i18n.ts +++ b/src/guide/guide.i18n.ts @@ -114,4 +114,77 @@ export const guideText = messages( hintsReset: "Show again", hintsResetDone: "Hints will show again", }, + { + "zh-Hant": { + hide: "不再顯示", + setupTitle: "開始使用", + stepUpstream: "新增上游", + stepUpstreamTodo: "API 金鑰、中轉服務、本機模型,或 ChatGPT、Z.ai 帳號。", + stepUpstreamDone: (n: number) => `已新增 ${n} 個上游`, + stepClient: "接管用戶端", + stepClientFound: (names: string) => `檢測到 ${names}。接管前會先列出要改動的配置。`, + stepClientNone: "未檢測到可自動接管的用戶端,可按說明手動配置。", + stepClientManual: "已按說明手動配置", + goClients: "前往用戶端", + stepRequest: "發出第一條請求", + stepRequestTodo: "在已接管的用戶端中發一條訊息。", + waiting: "等待請求", + probes: (n: number) => `已直接應答 ${n} 次用戶端探測,用戶端已連線閘道器。`, + nextClientsTitle: "下一步:接管用戶端", + nextClientsBody: "接管後,用戶端的請求經閘道器發往上游。", + nextUpstreamTitle: "尚未新增上游", + nextUpstreamBody: "接管的用戶端發出的請求,需要有上游才能送達。", + nextRequestTitle: "下一步:發出第一條請求", + nextRequestBody: (names: string) => `在 ${names} 中發一條訊息,流量頁即會顯示這條請求。`, + firstRequestTitle: "第一條請求已經過閘道器", + firstRequestBody: "它的路由、嘗試過的上游、用量與費用已記錄在流量頁。", + viewRequest: "檢視這條請求", + openRowTitle: "點開一條請求檢視詳情", + openRowBody: "命中的路由規則、嘗試過的上游、用量與費用,以及被替換的敏感值,都在詳情中。", + observeTitle: (n: number) => `${n} 項防護處於「監控」`, + observeBody: "命中時只記錄併發出通知。在日誌中確認沒有誤報後,再切換為「開啟」。", + hintsLabel: "引導提示", + hintsHint: "設為「不再顯示」的提示和忽略過的提醒將重新出現。", + hintsReset: "重新顯示", + hintsResetDone: "提示將重新顯示", + }, + es: { + hide: "No mostrar de nuevo", + setupTitle: "Empieza.", + stepUpstream: "Añadir un curso ascendente", + stepUpstreamTodo: "Una clave de API, un servicio de relé, un modelo local, o una cuenta de ChatGPT o Z.ai.", + stepUpstreamDone: (n: number) => (n === 1 ? "1 añadido en la fase anterior" : `${n} del proveedor añadidas`), + newUpstream: "Nuevo río arriba…", + stepClient: "Conectar un cliente", + stepClientFound: (names: string) => `Se encuentra ${names}. Los cambios de configuración se enumeran antes de que se escriba nada.`, + stepClientNone: "No se encontró ningún cliente que pueda conectarse automáticamente; las instrucciones de configuración manual están disponibles.", + stepClientDone: (names: string) => `Conectado: ${names}`, + stepClientManual: "Configurar manualmente", + goClients: "Ir a los clientes", + stepRequest: "Enviar una primera solicitud", + stepRequestTodo: "Enviar un mensaje de un cliente conectado.", + waiting: "Esperando una solicitud", + probes: (n: number) => n === 1 + ? "1 sonda cliente fue respondida directamente; un cliente está conectado a la puerta de entrada." + : `${n} Las sondas del cliente fueron respondidas directamente; un cliente está conectado a la puerta de entrada.`, + nextClientsTitle: "Siguiente: conectar un cliente", + nextClientsBody: "Una vez conectadas, las peticiones de un cliente pasan por la puerta de entrada a las del proveedor.", + nextUpstreamTitle: "No hay del proveedor todavía", + nextUpstreamBody: "Las solicitudes de los clientes conectados necesitan una corriente hacia arriba para llegar a un modelo.", + nextRequestTitle: "Siguiente: enviar una primera solicitud", + nextRequestBody: (names: string) => `Enviar un mensaje de ${names}; la solicitud aparece en la página de Tráfico.`, + goTraffic: "Ir al tráfico", + firstRequestTitle: "La primera petición pasó por la puerta de entrada", + firstRequestBody: "Su ruta, las del proveedor que intentó, su uso y costo se registran en la página de Tráfico.", + viewRequest: "Ver solicitud", + openRowTitle: "Abrir una solicitud para sus detalles", + openRowBody: "La regla de enrutamiento coincide, las del proveedor que intentó, su uso y costo, y cualquier valor redactado.", + observeTitle: (n: number) => (n === 1 ? "1 protección se establece en Monitor" : `${n} Las protecciones están configuradas en Monitor`), + observeBody: "Las coincidencias solo se registran y se notifican. Una vez que el registro no muestra falsos positivos, cambie a Activar.", + hintsLabel: "Orientación", + hintsHint: "Las sugerencias se fijan en “No mostrar de nuevo” y las advertencias ignoradas reaparecen.", + hintsReset: "Mostrar de nuevo", + hintsResetDone: "Las pistas se mostrarán de nuevo", + }, + }, ); diff --git a/src/i18n.test.ts b/src/i18n.test.ts index 81e34f97..844511f2 100644 --- a/src/i18n.test.ts +++ b/src/i18n.test.ts @@ -2,12 +2,13 @@ import { readFileSync, readdirSync } from "node:fs"; import { join, relative } from "node:path"; import ts from "typescript"; import { describe, expect, it } from "vitest"; -import { getLang, messages, setLang, textOf } from "./i18n"; +import { getLang, localeTag, messages, preferredLanguage, setLang, textOf } from "./i18n"; describe("界面语言", () => { const m = messages( { title: "用量概览", failed: (n: number) => `${n} 次失败` }, { title: "Usage", failed: (n: number) => `${n} failed` }, + { ja: { title: "使用量" }, "zh-Hant": { title: "用量總覽" }, ko: { title: "사용량" }, es: { title: "Uso" } }, ); it("按当前语言取文案,换了语言立刻换", () => { @@ -17,8 +18,31 @@ describe("界面语言", () => { setLang("en"); expect(getLang()).toBe("en"); expect(textOf(m).failed(3)).toBe("3 failed"); + setLang("ja"); + expect(localeTag(getLang())).toBe("ja"); + expect(textOf(m).title).toBe("使用量"); + expect(textOf(m).failed(3)).toBe("3 failed"); + setLang("ko"); + expect(textOf(m).title).toBe("사용량"); + setLang("es"); + expect(textOf(m).title).toBe("Uso"); + setLang("zh-Hant"); + expect(localeTag(getLang())).toBe("zh-Hant"); + expect(textOf(m).title).toBe("用量總覽"); + expect(textOf(m).failed(3)).toBe("3 次失败"); setLang("zh"); }); + + it("matches the first supported system language and falls back to English", () => { + expect(preferredLanguage(["fr-FR", "ja-JP", "en-US"])).toBe("ja"); + expect(preferredLanguage(["en-GB", "ja-JP"])).toBe("en"); + expect(preferredLanguage(["zh-Hant-TW", "ja-JP"])).toBe("zh-Hant"); + expect(preferredLanguage(["zh_HK.UTF-8"])).toBe("zh-Hant"); + expect(preferredLanguage(["zh-Hans-TW"])).toBe("zh"); + expect(preferredLanguage(["ko-KR", "en-US"])).toBe("ko"); + expect(preferredLanguage(["fr-CA", "es-419", "en-US"])).toBe("es"); + expect(preferredLanguage(["fr-FR", "de-DE"])).toBe("en"); + }); }); /** @@ -28,7 +52,7 @@ describe("界面语言", () => { * 你,直到有人正好看见那一屏。这里用 TypeScript 自己的语法树找字符串和 * JSX 文本,注释不算(注释是写给开发者的,照样用中文)。 */ -const CJK = /[\u3400-\u9fff\u3000-\u303f\uff00-\uffef]/; +const CJK = /[\u3400-\u9fff\u3000-\u30ff\uff00-\uffef]/; /** * 还没迁到词表里的文件。**现在是空的 —— 全都迁完了。**清单留着当守卫: diff --git a/src/i18n/common.i18n.ts b/src/i18n/common.i18n.ts index e1d3a023..7122ca1a 100644 --- a/src/i18n/common.i18n.ts +++ b/src/i18n/common.i18n.ts @@ -29,4 +29,53 @@ export const commonText = messages( confirm: "Confirm", none: "None", }, + { + "zh-Hant": { + close: "關閉", + save: "儲存", + delete: "刪除", + edit: "編輯", + retry: "重試", + copy: "複製", + copied: "已複製", + confirm: "確認", + none: "無", + }, + ja: { + cancel: "キャンセル", + close: "閉じる", + save: "保存", + delete: "削除", + edit: "編集", + retry: "再試行", + copy: "コピー", + copied: "コピーしました", + confirm: "確認", + none: "なし", + }, + ko: { + cancel: "취소", + close: "닫기", + save: "저장", + delete: "삭제", + edit: "편집", + retry: "다시 시도", + copy: "복사", + copied: "복사됨", + confirm: "확인", + none: "없음", + }, + es: { + cancel: "Cancelar", + close: "Cerrar", + save: "Guardar", + delete: "Eliminar", + edit: "Editar", + retry: "Reintentar", + copy: "Copiar", + copied: "Copiado", + confirm: "Confirmar", + none: "Ninguno", + }, + }, ); diff --git a/src/i18n/core.es.json b/src/i18n/core.es.json new file mode 100644 index 00000000..9daa46d0 --- /dev/null +++ b/src/i18n/core.es.json @@ -0,0 +1,80 @@ +{ + "tables": { + "kind": { + "upstream": "proveedor", + "proxy": "proxy", + "price sheet": "tabla de precios", + "route": "ruta", + "rule": "regla", + "group": "grupo", + "gateway key": "clave de la puerta de enlace", + "redaction rule": "regla de ocultación", + "tool-call rule": "regla de llamadas a herramientas", + "content rule": "regla de contenido", + "plugin": "complemento", + "alias": "alias" + }, + "guard": { + "redact": "Claves y privacidad", + "inspect_tools": "Comandos peligrosos", + "content": "Filtro de contenido" + } + }, + "messages": { + "gw.internal": "Un error interno de la puerta de enlace interrumpió la solicitud.", + "gw.internal_panic": "Un error interno de la puerta de enlace interrumpió la solicitud: {detail}", + "gw.auth.no_key": "Falta la clave de la puerta de enlace en la solicitud. Configura en el cliente una clave de clients en config.yaml.", + "gw.auth.key_invalid": "La clave de la puerta de enlace no es válida. Comprueba que la clave del cliente coincida con config.yaml.", + "gw.auth.key_disabled": "La clave «{key}» está desactivada. Actívala en la página Claves.", + "gw.auth.source_not_allowed": "No se permiten conexiones desde {peer}.", + "gw.config.no_upstreams": "No hay proveedores configurados. Añade uno en ThinkWatch Lite o en providers en config.yaml.", + "gw.config.http_client": "No se pudo crear el cliente HTTP: {detail}", + "gw.oauth.not_configured": "OAuth no está configurado para «{upstream}».", + "gw.oauth.unreachable": "No se puede conectar con el punto de acceso de tokens {endpoint}: {detail}", + "gw.oauth.held": "La puerta de enlace se está actualizando. Vuelve a intentarlo para renovar el token.", + "gw.probe.timeout": "No hubo respuesta en {secs} s. Comprueba la dirección de la API y la configuración del proxy.", + "gw.balance.timeout": "No se pudo consultar el saldo. No hubo respuesta en {secs} s.", + "gw.request.aborted": "La solicitud se interrumpió manualmente.", + "gw.request.body_unreadable": "No se pudo leer el cuerpo de la solicitud: {detail}", + "gw.upstream.timeout": "Se agotó el tiempo de espera de respuesta del proveedor.", + "gw.upstream.unreachable": "No se pudo conectar con el proveedor {url}. Comprueba la dirección de la API, la red y el proxy.", + "gw.upstream.forward_failed": "No se pudo reenviar la solicitud: {detail}", + "gw.upstream.rate_limited": "Se alcanzó el límite de solicitudes de «{upstream}».", + "gw.upstream.status": "El proveedor «{upstream}» devolvió {status}.", + "gw.upstream.status_message": "El proveedor «{upstream}» devolvió {status}: {message}", + "gw.upstream.response_error": "El proveedor «{upstream}» devolvió un error en la respuesta: {message}", + "gw.upstream.idle_timeout": "El proveedor «{upstream}» no envió datos durante {secs} s.", + "control.upstream_not_found": "No se encontró el proveedor «{upstream}».", + "control.balance_none": "No se puede consultar el saldo de «{upstream}».", + "control.proxy_not_found": "No se encontró el proxy «{proxy}».", + "control.route_not_found": "No se encontró la ruta «{route}».", + "control.sheet_not_found": "No se encontró la tabla de precios «{sheet}».", + "control.key_not_found": "No se encontró la clave de la puerta de enlace «{key}».", + "control.listen.bad_port": "El puerto debe estar entre 1 y 65535.", + "control.request_not_found": "No se encontró la solicitud #{id}.", + "control.request_not_running": "La solicitud #{id} no está en curso.", + "control.session_not_found": "No se encontró la sesión {id}.", + "control.session_not_running": "La sesión {id} no tiene solicitudes en curso.", + "control.client_unknown": "No se reconoce al cliente «{client}».", + "control.store_off": "El registro de solicitudes está desactivado.", + "control.store_unavailable": "No se puede acceder al historial de solicitudes. Comprueba la base de datos o el disco. El reenvío continúa.", + "control.no_keys": "No hay claves de la puerta de enlace en config.yaml. Crea una clave antes de conectar un cliente.", + "control.key_create_failed": "No se pudo crear la clave de la puerta de enlace: {detail}", + "control.name_empty": "Introduce un nombre para {kind:kind}.", + "control.name_whitespace": "El nombre de {kind:kind} no puede empezar ni terminar con espacios.", + "control.name_is_builtin": "«{name}» es un nombre reservado. Usa otro nombre.", + "control.shutdown": "La puerta de enlace se está cerrando.", + "control.base_url_empty": "Introduce la dirección de la API.", + "control.api_key_empty": "Introduce la clave de API.", + "control.user_empty": "Introduce el nombre de usuario.", + "control.header_no_value": "Introduce el valor de la cabecera «{header}».", + "control.proxy_addr_form": "Usa el formato host:puerto para la dirección del proxy «{addr}».", + "control.request_body_gone": "El cuerpo de la solicitud #{id} ya no está disponible. Es posible que haya vencido el plazo de conservación.", + "control.response_body_gone": "El cuerpo de respuesta de la solicitud #{id} ya no está disponible. Es posible que haya vencido el plazo de conservación.", + "control.signin_response_unusable": "No se pudo iniciar sesión: {detail}", + "control.signin_gone": "La solicitud de inicio de sesión no está disponible o se sustituyó por otra.", + "config.edit.name_taken": "Ya existe {what:kind} con el nombre «{name}».", + "config.credential.empty_key": "Falta la clave de API.", + "config.secret.env_missing": "La variable de entorno {var} no está definida." + } +} diff --git a/src/i18n/core.i18n.ts b/src/i18n/core.i18n.ts index 7122b6af..03222878 100644 --- a/src/i18n/core.i18n.ts +++ b/src/i18n/core.i18n.ts @@ -1,20 +1,17 @@ import type { Msg } from "@/types"; import { localizedPluginNames, pluginName } from "@/plugins/defaults"; -import { getLang } from "./index"; +import { getLang, type Lang } from "./index"; import CORE_ZH from "./core.zh.json"; +import CORE_HANT from "./core.zh-Hant.json"; +import CORE_JA from "./core.ja.json"; +import CORE_KO from "./core.ko.json"; +import CORE_ES from "./core.es.json"; +import { guardTables } from "./guard.i18n"; import { render, wordsOf, type Args, type Tables } from "./template"; /** - * core 发来的那些码,中文怎么说。 - * - * **只有中文一份,没有英文那一份。**core 给的 `text` 已经是英文了 —— - * 再在这里抄一份英文,core 一改措辞两边就对不上,而那份抄本没有任何 - * 东西在守着它。所以英文界面直接用 `text`,这张表只回答一个问题: - * 「这句话中文怎么说」。 - * - * **表在 `core.zh.json`,不在这里。**系统通知的正文是 Rust 写的(`notices::rules`), - * 也要按码说中文;表写成数据,两边读同一份(Rust 那边 `include_str!`),不会一边 - * 改了一边没改。句子的写法见 `template.ts`:参数、查词表、可有可无的一段。 + * Core 消息按稳定的码翻译。界面和 Rust 系统通知共用 JSON 词表。 + * 句子的写法见 `template.ts`:参数、查词表、可有可无的一段。 * * **码不在表里就显示 `text`。**两种情况会走到这条退路,而且都该走: * 这句还没进词表,或者这条消息只是把更深一层的原话原样带出来(`{detail}` @@ -24,8 +21,14 @@ import { render, wordsOf, type Args, type Tables } from "./template"; * 测速,`gw` 是网关的数据面,`control` 是控制面)。表里以 `//` 开头的键是分节的 * 标题,不是码。 */ -export const CORE_TABLES: Tables = CORE_ZH.tables; -const MESSAGES: Record = CORE_ZH.messages; +export const CORE_TABLES: Tables = { ...CORE_ZH.tables, ...guardTables("zh") }; +const CATALOGS: Partial }>> = { + zh: { tables: CORE_TABLES, messages: CORE_ZH.messages }, + "zh-Hant": { tables: { ...CORE_HANT.tables, ...guardTables("zh-Hant") }, messages: CORE_HANT.messages }, + ja: CORE_JA, + ko: CORE_KO, + es: CORE_ES, +}; /** * 原因外面套的那一层场合:哪个上游的凭据、哪个代理的密码、Z.ai 登录卡在哪一步。 @@ -37,7 +40,7 @@ const MESSAGES: Record = CORE_ZH.messages; * 自己也可能带着(`gw.oauth.not_configured` 就带),只看参数会把一句 * 「上游某某的凭据」凭空加到前面。场合可以套好几层,由外往里一层层剥。 */ -const CONTEXTS: { arg: string; en: string; zh: string }[] = CORE_ZH.contexts; +const CONTEXTS: ({ arg: string; en: string } & Partial, string>>)[] = CORE_ZH.contexts; /** * 一句没有码的话,包成 [`Msg`]。 @@ -58,8 +61,7 @@ export function plain(text: string): Msg { export function coreText(m: Msg | string | null | undefined, pluginId?: string | null): string { if (m == null) return ""; if (typeof m === "string") return m; - if (getLang() === "en") return m.text; - return zhOf(m, pluginId) ?? m.text; + return translated(m, getLang(), pluginId) ?? m.text; } /** @@ -71,29 +73,38 @@ export function coreText(m: Msg | string | null | undefined, pluginId?: string | * 插件页上也叫这个名字)。知道是哪个插件的(`pluginId`)按 id 认,不知道的按名字认。 */ export function zhOf(m: Msg, pluginId?: string | null): string | undefined { - const say = MESSAGES[m.code]; + return translated(m, "zh", pluginId); +} + +function translated(m: Msg, lang: Lang, pluginId?: string | null): string | undefined { + const catalog = CATALOGS[lang]; + if (!catalog || lang === "en") return undefined; + const { messages, tables } = catalog; + const say = messages[m.code]; if (!say || m.code.startsWith("//")) return undefined; const args: Args = m.args ?? {}; // 填进中文句子的参数。认场合比的是英文原句,那边照旧用原样的参数 - const zhArgs: Args = args.plugin === undefined ? args : { ...args, plugin: pluginName(pluginId, args.plugin, "zh") }; + const localArgs: Args = args.plugin === undefined ? args : { ...args, plugin: pluginName(pluginId, args.plugin, lang) }; const leads: string[] = []; for (let rest = m.text; ; ) { - let hit: { zh: string; en: string } | undefined; + let hit: { local: string; en: string } | undefined; for (const c of CONTEXTS) { if (args[c.arg] === undefined) continue; const en = render(c.en, args, CORE_TABLES); if (en === undefined || !rest.startsWith(`${en}: `)) continue; - const zh = render(c.zh, zhArgs, CORE_TABLES); - if (zh === undefined) return undefined; - hit = { zh, en }; + const copy = c[lang]; + if (copy === undefined) return undefined; + const local = render(copy, localArgs, tables); + if (local === undefined) return undefined; + hit = { local, en }; break; } if (!hit) break; - leads.push(`${hit.zh}:`); + leads.push(`${hit.local}:`); rest = rest.slice(hit.en.length + 2); } - const zh = render(say, zhArgs, CORE_TABLES); - return zh === undefined ? undefined : leads.join("") + zh; + const local = render(say, localArgs, tables); + return local === undefined ? undefined : leads.join("") + local; } /** @@ -111,12 +122,15 @@ export function zhOf(m: Msg, pluginId?: string | null): string | undefined { * 英文界面上看到的就是原句,交空的。`q` 已经去掉首尾空白、转了小写。 */ export function codesMatching(q: string): string[] { - if (!q || getLang() === "en") return []; - const pluginNamed = localizedPluginNames("zh").some((n) => n.toLowerCase().includes(q)); + const lang = getLang(); + const catalog = CATALOGS[lang]; + if (!q || !catalog) return []; + const { messages, tables } = catalog; + const pluginNamed = localizedPluginNames(lang).some((n) => n.toLowerCase().includes(q)); const out: string[] = []; - for (const [code, say] of Object.entries(MESSAGES)) { + for (const [code, say] of Object.entries(messages)) { if (code.startsWith("//")) continue; - if (wordsOf(say, CORE_TABLES).some((w) => w.toLowerCase().includes(q)) || (pluginNamed && say.includes("{plugin}"))) + if (wordsOf(say, tables).some((w) => w.toLowerCase().includes(q)) || (pluginNamed && say.includes("{plugin}"))) out.push(code); } return out; diff --git a/src/i18n/core.ja.json b/src/i18n/core.ja.json new file mode 100644 index 00000000..93a09e39 --- /dev/null +++ b/src/i18n/core.ja.json @@ -0,0 +1,96 @@ +{ + "tables": { + "kind": { + "upstream": "アップストリーム", + "proxy": "プロキシ", + "price sheet": "料金表", + "route": "ルート", + "rule": "ルール", + "group": "グループ", + "gateway key": "ゲートウェイキー", + "redaction rule": "機密情報の保護ルール", + "tool-call rule": "ツール呼び出しルール", + "content rule": "コンテンツルール", + "plugin": "プラグイン", + "alias": "エイリアス" + } + }, + "messages": { + "l1.timeout": "{seconds} 秒以内に完了しませんでした。", + "l1.unreachable": "プロキシに接続できません。", + "gw.internal": "ゲートウェイ内部のエラーにより、リクエストが中断されました。", + "gw.internal_panic": "ゲートウェイ内部のエラーにより、リクエストが中断されました:{detail}", + "gw.auth.no_key": "リクエストにゲートウェイキーがありません。config.yaml の clients にあるキーをクライアントに設定してください。", + "gw.auth.key_invalid": "ゲートウェイキーが無効です。クライアントのキーが config.yaml の設定と一致するか確認してください。", + "gw.auth.key_disabled": "ゲートウェイキー「{key}」は無効です。アプリのキーページで有効にしてください。", + "gw.auth.source_not_allowed": "{peer} からの接続は許可されていません。", + "gw.auth.source_not_allowed_hint": "{peer} からの接続は許可されていません。listen.gateway.allow_from を変更するか、bind を loopback に設定してください。", + "gw.config.no_upstreams": "アップストリームが設定されていません。ThinkWatch Lite または config.yaml の providers で追加してください。", + "gw.config.proxy_undefined": "「{upstream}」が使用するプロキシ「{proxy}」が proxies に定義されていません。組み込みの選択肢は direct と system です。", + "gw.config.proxy_unusable": "「{upstream}」のプロキシ「{proxy}」を使用できません:{detail}", + "gw.config.http_client": "HTTP クライアントを作成できませんでした:{detail}", + "gw.oauth.not_configured": "アップストリーム「{upstream}」に OAuth が設定されていません。", + "gw.oauth.unreachable": "トークンエンドポイント {endpoint} に接続できません:{detail}", + "gw.oauth.status": "トークンエンドポイントが {status} を返しました:{body}", + "gw.oauth.no_token": "トークンエンドポイントの応答に access_token がありません。", + "gw.oauth.expired": "OAuth 認証情報の有効期限が切れました。再ログインするか、リフレッシュトークンを交換してください。トークンエンドポイントの応答は {status} でした:{body}", + "gw.oauth.held": "ゲートウェイの更新中はトークンを更新できません。しばらくしてから再試行してください。", + "gw.probe.timeout": "{secs} 秒以内に応答がありませんでした。API アドレスとプロキシの設定を確認してください。", + "gw.balance.timeout": "残高を取得できませんでした。{secs} 秒以内に応答がありませんでした。", + "gw.request.aborted": "リクエストは手動で中止されました。", + "gw.request.body_unreadable": "リクエスト本文を読み取れません:{detail}", + "gw.upstream.timeout": "アップストリームの応答がタイムアウトしました。", + "gw.upstream.unreachable": "アップストリーム {url} に接続できません。API アドレス、ネットワーク、プロキシの設定を確認してください。", + "gw.upstream.forward_failed": "転送に失敗しました:{detail}", + "gw.upstream.body_broken": "レスポンスの受信中にアップストリームとの接続が切断されました:{detail}", + "gw.upstream.rate_limited": "アップストリーム「{upstream}」のレート制限に達しました。", + "gw.upstream.paused": "アップストリーム「{upstream}」が 429(レート制限)を返しました。送信を一時停止し、約 {secs} 秒後に再開します。", + "gw.upstream.status": "アップストリーム「{upstream}」が {status} を返しました。", + "gw.upstream.status_message": "アップストリーム「{upstream}」が {status} を返しました:{message}", + "gw.upstream.response_error": "アップストリーム「{upstream}」がエラーを返しました:{message}", + "gw.upstream.idle_timeout": "アップストリーム「{upstream}」から {secs} 秒間データが届きませんでした。", + "gw.upstream.idle_timeout_mid_stream": "レスポンスの途中で、アップストリーム「{upstream}」から {secs} 秒間データが届きませんでした。", + "gw.upstream.stream_error": "レスポンスの途中でアップストリーム「{upstream}」がエラーを返しました:{message}", + "control.upstream_not_found": "アップストリーム「{upstream}」が見つかりません。", + "control.balance_none": "アップストリーム「{upstream}」の残高は取得できません。", + "control.proxy_not_found": "プロキシ「{proxy}」が見つかりません。", + "control.route_not_found": "ルート「{route}」が見つかりません。", + "control.sheet_not_found": "料金表「{sheet}」が見つかりません。", + "control.key_not_found": "ゲートウェイキー「{key}」が見つかりません。", + "control.listen.bad_port": "ポートは 1〜65535 の範囲で指定してください。", + "control.request_not_found": "リクエスト #{id} が見つかりません。", + "control.request_not_running": "リクエスト #{id} は処理中ではありません。", + "control.session_not_found": "セッション {id} が見つかりません。", + "control.session_not_running": "セッション {id} に処理中のリクエストはありません。", + "control.client_unknown": "クライアント「{client}」を認識できません。", + "control.store_off": "リクエストの記録が無効です。", + "control.store_unavailable": "リクエスト履歴を利用できません。データベースまたはディスクを確認してください。転送は続行されます。", + "control.no_keys": "config.yaml にゲートウェイキーがありません。クライアントを接続する前にキーを作成してください。", + "control.key_create_failed": "ゲートウェイキーを作成できませんでした:{detail}", + "control.name_empty": "{kind:kind}の名前を入力してください。", + "control.name_whitespace": "{kind:kind}の名前の前後に空白を含めることはできません。", + "control.name_reserved": "{kind:kind}の名前を {prefix} で始めることはできません。この接頭辞は組み込み項目用です。", + "control.name_is_builtin": "「{name}」は組み込み項目の名前です。別の名前を使用してください。", + "control.shutdown": "ゲートウェイは終了処理中です。", + "control.handover.busy": "ログインまたは引き継ぎが進行中です。完了後に再試行してください。", + "control.handover.login_refused": "ゲートウェイを更新します。更新が完了してから再度ログインしてください。", + "control.no_such_endpoint": "制御インターフェイスに {method} {path} がありません。アプリとゲートウェイのバージョンが一致しているか確認してください。", + "control.method_not_allowed": "制御インターフェイスで {path} への {method} リクエストは使用できません。アプリとゲートウェイのバージョンを確認してください。", + "control.request_rejected": "制御インターフェイスがリクエストを読み取れませんでした:{detail}", + "control.base_url_empty": "API アドレスを入力してください。", + "control.api_key_empty": "API キーを入力してください。", + "control.user_empty": "ユーザー名を入力してください。", + "control.header_no_value": "ヘッダー「{header}」の値を入力してください。", + "control.proxy_addr_form": "プロキシアドレス「{addr}」は ホスト:ポート の形式で指定してください。", + "control.dryrun_needs_target": "ゲートウェイキーまたはルートを指定してください。", + "control.request_body_gone": "リクエスト #{id} の本文は利用できません。保持期限を過ぎて削除された可能性があります。", + "control.response_body_gone": "リクエスト #{id} のレスポンス本文は利用できません。保持期限を過ぎて削除された可能性があります。", + "control.signin_response_unusable": "ログインを開始できませんでした:{detail}", + "control.device_code_unavailable": "このアカウントではデバイスコードでのログインを利用できません。ローカルでログインしてください。", + "control.signin_gone": "このログインは見つからないか、新しいログインに置き換えられました。", + "config.edit.name_taken": "「{name}」という名前の{what:kind}はすでにあります。", + "config.credential.empty_key": "API キーが空です。", + "config.credential.empty_oauth": "OAuth の refresh と endpoint の両方を指定してください。", + "config.secret.env_missing": "環境変数 {var} が設定されていません。" + } +} diff --git a/src/i18n/core.ko.json b/src/i18n/core.ko.json new file mode 100644 index 00000000..f2511317 --- /dev/null +++ b/src/i18n/core.ko.json @@ -0,0 +1,80 @@ +{ + "tables": { + "kind": { + "upstream": "업스트림", + "proxy": "프록시", + "price sheet": "가격표", + "route": "경로", + "rule": "규칙", + "group": "그룹", + "gateway key": "게이트웨이 키", + "redaction rule": "개인정보 보호 규칙", + "tool-call rule": "도구 호출 규칙", + "content rule": "콘텐츠 규칙", + "plugin": "플러그인", + "alias": "별칭" + }, + "guard": { + "redact": "키 및 개인정보 보호", + "inspect_tools": "위험한 명령 검사", + "content": "콘텐츠 필터" + } + }, + "messages": { + "gw.internal": "게이트웨이 내부 오류로 요청이 중단되었습니다.", + "gw.internal_panic": "게이트웨이 내부 오류로 요청이 중단되었습니다: {detail}", + "gw.auth.no_key": "요청에 게이트웨이 키가 없습니다. config.yaml의 clients에 있는 키를 클라이언트에 설정하세요.", + "gw.auth.key_invalid": "게이트웨이 키가 올바르지 않습니다. 클라이언트의 키가 config.yaml과 일치하는지 확인하세요.", + "gw.auth.key_disabled": "게이트웨이 키 「{key}」이(가) 비활성화되어 있습니다. 앱의 키 페이지에서 활성화하세요.", + "gw.auth.source_not_allowed": "{peer}의 연결은 허용되지 않습니다.", + "gw.config.no_upstreams": "설정된 업스트림이 없습니다. ThinkWatch Lite 또는 config.yaml의 providers에서 추가하세요.", + "gw.config.http_client": "HTTP 클라이언트를 만들 수 없습니다: {detail}", + "gw.oauth.not_configured": "업스트림 「{upstream}」에 OAuth가 설정되지 않았습니다.", + "gw.oauth.unreachable": "토큰 엔드포인트 {endpoint}에 연결할 수 없습니다: {detail}", + "gw.oauth.held": "게이트웨이가 업데이트 중이어서 토큰을 갱신할 수 없습니다. 잠시 후 다시 시도하세요.", + "gw.probe.timeout": "{secs}초 동안 응답이 없었습니다. API 주소와 프록시 설정을 확인하세요.", + "gw.balance.timeout": "{secs}초 동안 응답이 없어 잔액을 불러올 수 없습니다.", + "gw.request.aborted": "요청을 수동으로 중단했습니다.", + "gw.request.body_unreadable": "요청 본문을 읽을 수 없습니다: {detail}", + "gw.upstream.timeout": "업스트림 응답 시간이 초과되었습니다.", + "gw.upstream.unreachable": "업스트림 {url}에 연결할 수 없습니다. API 주소, 네트워크 및 프록시 설정을 확인하세요.", + "gw.upstream.forward_failed": "요청을 전달하지 못했습니다: {detail}", + "gw.upstream.rate_limited": "업스트림 「{upstream}」의 요청 한도에 도달했습니다.", + "gw.upstream.status": "업스트림 「{upstream}」에서 {status}을(를) 반환했습니다.", + "gw.upstream.status_message": "업스트림 「{upstream}」에서 {status}을(를) 반환했습니다: {message}", + "gw.upstream.response_error": "업스트림 「{upstream}」의 응답에 오류가 있습니다: {message}", + "gw.upstream.idle_timeout": "업스트림 「{upstream}」에서 {secs}초 동안 데이터가 오지 않았습니다.", + "control.upstream_not_found": "업스트림 「{upstream}」을(를) 찾을 수 없습니다.", + "control.balance_none": "업스트림 「{upstream}」의 잔액을 조회할 수 없습니다.", + "control.proxy_not_found": "프록시 「{proxy}」을(를) 찾을 수 없습니다.", + "control.route_not_found": "경로 「{route}」을(를) 찾을 수 없습니다.", + "control.sheet_not_found": "가격표 「{sheet}」을(를) 찾을 수 없습니다.", + "control.key_not_found": "게이트웨이 키 「{key}」을(를) 찾을 수 없습니다.", + "control.listen.bad_port": "포트 번호는 1~65535 사이여야 합니다.", + "control.request_not_found": "요청 #{id}을(를) 찾을 수 없습니다.", + "control.request_not_running": "요청 #{id}은(는) 처리 중이 아닙니다.", + "control.session_not_found": "세션 {id}을(를) 찾을 수 없습니다.", + "control.session_not_running": "세션 {id}에 진행 중인 요청이 없습니다.", + "control.client_unknown": "클라이언트 「{client}」을(를) 인식할 수 없습니다.", + "control.store_off": "요청 기록이 비활성화되어 있습니다.", + "control.store_unavailable": "요청 기록을 사용할 수 없습니다. 데이터베이스나 디스크에 문제가 있을 수 있습니다. 요청 전달은 계속됩니다.", + "control.no_keys": "config.yaml에 게이트웨이 키가 없습니다. 클라이언트를 연결하기 전에 키를 만드세요.", + "control.key_create_failed": "게이트웨이 키를 만들 수 없습니다: {detail}", + "control.name_empty": "{kind:kind} 이름을 입력하세요.", + "control.name_whitespace": "{kind:kind} 이름의 앞뒤에 공백이 있으면 안 됩니다.", + "control.name_is_builtin": "「{name}」은(는) 기본 제공 항목의 이름입니다. 다른 이름을 사용하세요.", + "control.shutdown": "게이트웨이를 종료하는 중입니다.", + "control.base_url_empty": "API 주소를 입력하세요.", + "control.api_key_empty": "API 키를 입력하세요.", + "control.user_empty": "사용자 이름을 입력하세요.", + "control.header_no_value": "헤더 「{header}」의 값을 입력하세요.", + "control.proxy_addr_form": "프록시 주소 「{addr}」을(를) 호스트:포트 형식으로 입력하세요.", + "control.request_body_gone": "요청 #{id}의 본문을 사용할 수 없습니다. 보존 기간이 지나 삭제되었을 수 있습니다.", + "control.response_body_gone": "요청 #{id}의 응답 본문을 사용할 수 없습니다. 보존 기간이 지나 삭제되었을 수 있습니다.", + "control.signin_response_unusable": "로그인을 시작할 수 없습니다: {detail}", + "control.signin_gone": "이 로그인 요청을 찾을 수 없거나 새 요청으로 대체되었습니다.", + "config.edit.name_taken": "이름이 「{name}」인 {what:kind}이(가) 이미 있습니다.", + "config.credential.empty_key": "API 키가 비어 있습니다.", + "config.secret.env_missing": "환경 변수 {var}이(가) 설정되지 않았습니다." + } +} diff --git a/src/i18n/core.test.ts b/src/i18n/core.test.ts index ce019e3f..22242706 100644 --- a/src/i18n/core.test.ts +++ b/src/i18n/core.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; -import { setLang } from "./index"; -import { coreText, errorText, plain } from "./core.i18n"; +import { setLang, type Lang } from "./index"; +import { codesMatching, coreText, errorText, plain } from "./core.i18n"; import CORE_ZH from "./core.zh.json"; import CASE_FILE from "./core.zh.cases.json"; import { compile } from "./template"; @@ -10,7 +10,7 @@ import type { Msg } from "@/types"; const CASES = CASE_FILE as unknown as { msg: Msg; zh: string }[]; /** 每条用例自己说用哪种语言 —— 全局的那个在测试之间是共享的 */ -function inLang(lang: "zh" | "en", f: () => T): T { +function inLang(lang: Lang, f: () => T): T { setLang(lang); try { return f(); @@ -20,6 +20,31 @@ function inLang(lang: "zh" | "en", f: () => T): T { } describe("core 发来的消息", () => { + it.each([ + ["zh-Hant", "上游回應超時。", "超時"], + ["ko", "업스트림 응답 시간이 초과되었습니다.", "초과"], + ["es", "Se agotó el tiempo de espera de respuesta del proveedor.", "tiempo de espera"], + ] as const)("uses and searches the %s Core error catalog", (lang, expected, query) => { + const code = "gw.upstream.timeout"; + expect(inLang(lang, () => coreText({ code, text: "The upstream timed out." }))).toBe(expected); + expect(inLang(lang, () => codesMatching(query))).toContain(code); + expect(inLang(lang, () => coreText({ code: "future.code", text: "Original English" }))).toBe("Original English"); + }); + + it("translates and searches Japanese errors, using English for missing translations", () => { + const m = { + code: "gw.oauth.unreachable", + text: "the credential of upstream `example`: Cannot reach https://example.com: timeout", + args: { upstream: "example", endpoint: "https://example.com", detail: "timeout" }, + }; + expect(inLang("ja", () => coreText(m))).toBe( + "アップストリーム「example」の認証情報:トークンエンドポイント https://example.com に接続できません:timeout", + ); + expect(inLang("ja", () => codesMatching("接続できません"))).toContain(m.code); + expect(inLang("ja", () => coreText({ code: "control.name_empty", text: "Name is required" }))).toBe("Name is required"); + expect(inLang("ja", () => coreText({ code: "l1.tcp.refused", text: "Connection refused" }))).toBe("Connection refused"); + }); + it("中文界面按码说自己那句话", () => { const m = { code: "l1.tcp.refused", diff --git a/src/i18n/core.zh-Hant.json b/src/i18n/core.zh-Hant.json new file mode 100644 index 00000000..e2dab397 --- /dev/null +++ b/src/i18n/core.zh-Hant.json @@ -0,0 +1,1085 @@ +{ + "tables": { + "kind": { + "upstream": "上游", + "proxy": "代理", + "price sheet": "價目表", + "route": "路由", + "rule": "規則", + "group": "策略組", + "gateway key": "閘道器金鑰", + "redaction rule": "金鑰與隱私規則", + "tool-call rule": "危險命令規則", + "content rule": "內容過濾規則", + "plugin": "外掛", + "alias": "別名" + }, + "setting_kind": { + "string": "字串", + "number": "數字", + "boolean": "true 或 false" + }, + "rule_line": { + "redaction": "金鑰與隱私", + "tool-call": "危險命令", + "content": "內容過濾" + }, + "pattern_of": { + "content": "匹配內容", + "redaction": "正規表示式", + "tool-call": "正規表示式" + }, + "stage": { + "syntax": "語法", + "schema": "欄位", + "semantics": "語義" + }, + "price_field": { + "input price": "輸入價格", + "output price": "輸出價格", + "cache-read price": "快取讀取價格", + "cache-write price (5 minutes)": "快取寫入價格(5 分鐘)", + "cache-write price (1 hour)": "快取寫入價格(1 小時)", + "long-context input price": "長上下文輸入價格", + "long-context output price": "長上下文輸出價格" + }, + "takes_effect": { + "immediately": "下一個請求即使用新配置。", + "on_restart": "重新開啟終端後生效,在此之前閘道器不會收到該用戶端的請求。" + }, + "cloud": { + "bedrock": "Amazon Bedrock", + "mantle": "Amazon Bedrock(Mantle)", + "vertex": "Google Cloud Agent Platform", + "foundry": "Microsoft Foundry", + "anthropic_aws": "Claude Platform on AWS" + }, + "aws_how": { + "credential_export": "awsCredentialExport 命令", + "sso": "IAM Identity Center 登入", + "credential_helper": "憑據指令碼", + "idp": "經代理的身份提供方登入" + }, + "source_in": { + "hooks": "hook 中", + "mcp": "MCP server 中", + "skill": "skill 中", + "command": "斜槓命令中", + "agent": "subagent 中", + "instructions": "專案指令中" + }, + "source_why": { + "hooks": "hook 在工具呼叫前後直接執行 shell 命令,無需模型參與即可獲得執行許可權。", + "mcp": "MCP server 配置指定了可執行程式及其引數,相當於直接執行該程式。", + "skill": "SKILL.md 的內容會被注入模型上下文,成為指令。", + "command": "斜槓命令的內容會被注入模型上下文,成為指令。", + "agent": "subagent 定義會被注入模型上下文,並可能宣告寬鬆的工具許可權。", + "instructions": "該檔案會被自動讀入模型上下文。" + }, + "hidden_why": { + "zero_width": "零寬字元:在編輯器中不可見,但會被模型讀取。", + "tag": "Unicode 標籤字元:在編輯器中完全不可見,但會原樣進入模型上下文,可用於隱藏整段指令。", + "bidi": "雙向控制符:可使螢幕上的顯示順序與實際字元順序不一致。", + "homoglyph": "同形字元:外觀與拉丁字母相同,實際是其他字元,常用於偽裝命令和域名。", + "private_use": "私用區碼位:沒有標準含義,出現在指令檔案中即屬可疑。" + }, + "hidden_name": { + "zero_width": "零寬字元", + "tag": "Unicode 標籤字元", + "bidi": "雙向控制符", + "homoglyph": "同形字元", + "private_use": "私用區碼位" + }, + "guard": { + "redact": "金鑰與隱私", + "inspect_tools": "危險命令", + "content": "內容過濾" + }, + "zai_step": { + "authorize_url": "獲取授權地址", + "wait_authorization": "等待授權", + "exchange_token": "用登入結果換取帳號令牌", + "read_account": "讀取帳號資訊", + "list_keys": "列出帳號的 API 金鑰", + "create_key": "建立 API 金鑰", + "read_key": "讀取 API 金鑰" + }, + "zai_step_en": { + "authorize_url": "Asking for an authorization address", + "wait_authorization": "Waiting for the authorization", + "exchange_token": "Exchanging the sign-in for an account token", + "read_account": "Reading the account", + "list_keys": "Listing the account's API keys", + "create_key": "Creating an API key", + "read_key": "Reading the API key" + }, + "limit_per": { + "minute": "分鐘", + "hour": "小時", + "day": "天", + "week": "周", + "month": "月" + }, + "limit_measure": { + "requests": "請求數", + "tokens": "token 數", + "cost": "費用" + }, + "limit_measures": { + "requests and tokens": "requests 和 tokens", + "requests and cost": "requests 和 cost", + "tokens and cost": "tokens 和 cost", + "requests and tokens and cost": "requests、tokens 和 cost" + }, + "item_kind": { + "provider": "上游", + "proxy": "代理", + "key": "閘道器金鑰", + "alias": "別名", + "group": "策略組", + "route": "路由", + "price_sheet": "價目表", + "security_rule": "安全規則", + "plugin": "外掛", + "provider_order": "上游順序", + "route_order": "路由順序", + "plugin_order": "外掛順序", + "global": "全域性設定", + "client_prefs": "通用偏好" + } + }, + "messages": { + "// ── l1:链路测速 ────────────────────────────────────────────────": "", + "l1.timeout": "{seconds} 秒內未完成", + "l1.unreachable": "無法連線該代理。", + "l1.config.system_proxy": "該上游使用系統代理,代理地址在建立連線時才由環境決定,鏈路測速無法測量。將代理配置為命名條目後即可測速。", + "l1.config.proxy_undefined": "上游「{upstream}」使用的代理「{proxy}」未在 proxies 中定義。", + "l1.config.bad_url": "介面地址不是合法的 URL:{detail}", + "l1.config.unsupported_scheme": "介面地址使用了 {scheme} 協議,僅支援 http 和 https。", + "l1.config.no_host": "介面地址中缺少主機名。", + "l1.config.proxy_addr_form": "代理地址應寫成 主機:埠 的形式。", + "l1.config.proxy_addr_ipv6_form": "IPv6 代理地址應寫成 [::1]:1080 的形式。", + "l1.config.proxy_addr_ipv6_brackets": "{addr} 中的 IPv6 地址需要加方括號,應寫成 [{host}]:{port}。", + "l1.config.proxy_port_not_a_number": "埠「{port}」不是數字。", + "l1.dns.timeout": "解析 {host} 超過 {seconds} 秒未完成,DNS 伺服器可能無法訪問。", + "l1.dns.failed": "無法解析 {host}。請檢查域名拼寫;如果該地址需要經代理訪問,請先配置代理。", + "l1.dns.no_records": "{host} 解析成功,但結果中沒有地址。", + "l1.tcp.refused": "{addr} 拒絕連線,該埠上沒有服務在監聽。請檢查地址和埠。", + "l1.tcp.timeout": "連線 {addr} 沒有回應。請檢查網路,或確認該地址是否需要經代理訪問。", + "l1.tcp.unreachable": "無法訪問 {addr} 所在的網路,請檢查本機網路。", + "l1.tcp.failed": "無法連線 {addr}:{detail}", + "// 读写失败按系统给的种类说;其余种类(`l1.io`)只有系统原话,不在表里": "", + "l1.io.refused": "連線被拒絕。", + "l1.io.reset": "連線被對端重置。", + "l1.io.aborted": "連線被中止。", + "l1.io.timed_out": "連線超時。", + "l1.io.addr_not_available": "該地址在本機不可用。", + "l1.io.not_found": "未找到目標。", + "l1.io.permission_denied": "作業系統不允許該連線,可能被防火牆或網路許可權設定阻止。", + "l1.io.eof": "對端在回應前關閉了連線。", + "l1.io.broken_pipe": "傳送資料時對端關閉了連線。", + "l1.io.host_unreachable": "無法訪問該主機。", + "l1.io.network_unreachable": "無法訪問該網路,請檢查本機網路。", + "l1.tls.bad_hostname": "{host} 不是有效的 TLS 主機名。", + "l1.tls.failed": "TLS 握手失敗:{detail}", + "l1.tls.cert_expired": "證書驗證未透過:{detail}。證書已過期或尚未生效,也可能是本機時間不準確,請先核對系統時間。", + "l1.tls.cert_untrusted_issuer": "證書驗證未透過:{detail}。證書的簽發者不在系統信任列表中。如果本機安裝了抓包工具或企業根證書,證書鏈可能已被替換。", + "l1.tls.cert_invalid": "證書驗證未透過:{detail}。如果網路中有抓包工具或企業代理攔截 TLS 連線,也會出現此錯誤。", + "l1.socks5.not_socks5": "代理的回應不是 SOCKS5 協議(版本位元組 {byte}),該埠上可能是 HTTP 代理。", + "l1.socks5.auth_required": "代理要求使用者名稱和密碼認證,但該代理未配置認證資訊。", + "l1.socks5.credentials_too_long": "SOCKS5 的使用者名稱和密碼均不能超過 255 位元組。", + "l1.socks5.auth_rejected": "代理拒絕了使用者名稱和密碼。", + "l1.socks5.no_acceptable_auth": "代理不接受所提供的認證方式。", + "l1.socks5.unsupported_auth": "代理要求的認證方式 {method} 不受支援。", + "l1.socks5.host_too_long": "域名超過 255 位元組,無法透過 SOCKS5 傳送。", + "l1.socks5.unknown_address_type": "代理返回了無法識別的地址型別 {kind}。", + "l1.socks5.general_failure": "代理內部錯誤。", + "l1.socks5.not_allowed": "代理規則不允許連線該地址。", + "l1.socks5.network_unreachable": "代理無法訪問該網路。", + "l1.socks5.host_unreachable": "代理無法訪問該主機。", + "l1.socks5.connection_refused": "目標拒絕連線。", + "l1.socks5.ttl_expired": "TTL 已過期。", + "l1.socks5.command_unsupported": "代理不支援 CONNECT。", + "l1.socks5.address_type_unsupported": "代理不支援該地址型別。", + "l1.socks5.rejected": "代理拒絕了連線(應答碼 {reply})。", + "l1.http_proxy.headers_too_large": "代理的回應頭超過 8 KB,該埠上可能不是 HTTP 代理。", + "l1.http_proxy.auth_required": "代理要求認證(HTTP 407),請檢查使用者名稱和密碼。", + "l1.http_proxy.unreadable_response": "代理返回了無法識別的回應:{line}", + "l1.http_proxy.connect_rejected": "代理拒絕了 CONNECT 請求(HTTP {status}):{line}", + "// ── l3:推理测速 ────────────────────────────────────────────────": "", + "l3.refused": "上游返回 {status}:{detail}", + "l3.stream_failed": "上游在回答過程中報錯:{detail}", + "l3.not_streamed": "上游沒有以流式回答,無法測得首 token 時間。", + "l3.sign_failed": "無法用 AWS 訪問金鑰為請求籤名:{detail}", + "// ── lite:桌面版自己说的。core 停了,没法再替那些请求说话 ─────────": "", + "lite.core_stopped": "core 在請求完成前停止執行,請求已中斷。", + "// ── gw:网关的数据面。这些话同时发给 AI 客户端和界面 ──────────────": "", + "gw.internal": "請求被閘道器內部的錯誤中斷。", + "gw.internal_panic": "請求被閘道器內部的錯誤中斷:{detail}", + "gw.auth.no_key": "請求未攜帶閘道器金鑰。請將 config.yaml 的 clients 中的閘道器金鑰配置到用戶端。", + "gw.auth.key_invalid": "閘道器金鑰無效。請檢查用戶端配置中的金鑰與 config.yaml 是否一致。", + "gw.auth.key_disabled": "閘道器金鑰「{key}」已停用。在應用的金鑰頁啟用它即可恢復。", + "gw.auth.source_not_allowed": "{peer} 不在允許的來源地址中。", + "gw.auth.source_not_allowed_hint": "{peer} 不在允許的來源地址中。請修改 listen.gateway.allow_from,或將 bind 改為 loopback。", + "gw.key_limit.requests_per_period": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 次請求的上限,已使用 {used} 次,將於 {resets} 重置。", + "gw.key_limit.tokens_per_period": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 個 token 的上限,已使用 {used} 個 token,將於 {resets} 重置。", + "gw.key_limit.cost_per_period": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 的費用上限,已產生費用 {used},將於 {resets} 重置。", + "gw.key_limit.requests_rolling": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 次請求的上限,最近一{per:limit_per}內已有 {used} 次,請於 {retry} 秒後重試。", + "gw.key_limit.tokens_rolling": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 個 token 的上限,最近一{per:limit_per}內已使用 {used} 個 token,請於 {retry} 秒後重試。", + "gw.key_limit.cost_rolling": "閘道器金鑰「{key}」已達到每{per:limit_per} {max} 的費用上限,最近一{per:limit_per}內已產生費用 {used},請於 {retry} 秒後重試。", + "gw.key_limit.requests_every": "閘道器金鑰「{key}」已達到每 {every} {per:limit_per} {max} 次請求的上限,最近 {every} {per:limit_per}內已有 {used} 次,請於 {retry} 秒後重試。", + "gw.key_limit.tokens_every": "閘道器金鑰「{key}」已達到每 {every} {per:limit_per} {max} 個 token 的上限,最近 {every} {per:limit_per}內已使用 {used} 個 token,請於 {retry} 秒後重試。", + "gw.key_limit.cost_every": "閘道器金鑰「{key}」已達到每 {every} {per:limit_per} {max} 的費用上限,最近 {every} {per:limit_per}內已產生費用 {used},請於 {retry} 秒後重試。", + "gw.config.no_upstreams": "尚未配置任何上游。請在 ThinkWatch Lite 中新增上游,或在 config.yaml 的 providers 中新增。", + "gw.config.proxy_undefined": "上游「{upstream}」使用的代理「{proxy}」未在 proxies 中定義,內建選項只有 direct 和 system。", + "gw.config.proxy_unusable": "上游「{upstream}」的代理「{proxy}」不可用:{detail}", + "gw.config.http_client": "無法建立 HTTP 用戶端:{detail}", + "gw.config.allow_from": "listen.gateway.allow_from:{detail}", + "// ── gw.plugin:插件拒绝请求、插件出错、加载插件、试运行。{plugin} 在请求上是插件的名字,在文件上是 id ──": "", + "gw.plugin.rejected": "外掛「{plugin}」拒絕了此請求:{reason}", + "gw.plugin.request_failed": "外掛「{plugin}」出錯,請求未傳送:{detail}", + "gw.plugin.reply_failed": "外掛「{plugin}」處理回答時出錯:{detail}", + "gw.plugin.reply_busy": "外掛「{plugin}」未處理此回答:同時處理回答的外掛已達上限({max} 個)。", + "gw.plugin.changed": "外掛「{plugin}」的檔案已更改且尚未重新確認,請求未傳送。", + "gw.plugin.unavailable": "外掛「{plugin}」無法載入,請求未傳送:{detail}", + "gw.plugin.cannot_read_body": "外掛「{plugin}」無法讀取此請求:{detail}", + "gw.plugin.model_not_allowed": "外掛「{plugin}」將模型改為 {model},而閘道器金鑰「{key}」不允許使用該模型,請求未傳送。", + "gw.plugin.alias_unserved": "外掛「{plugin}」將模型改為別名 {model},而上游「{upstream}」不提供它列出的任何模型,請求未發往該上游。", + "gw.plugin.file_changed": "外掛「{plugin}」的檔案已更改,此外掛不再執行。請在應用中稽核並確認更改。", + "gw.plugin.failed": "外掛執行失敗。", + "gw.plugin.cpu_limit": "外掛使用的 CPU 時間超出上限。", + "gw.plugin.memory_limit": "外掛使用的記憶體超出上限。", + "gw.plugin.output_limit": "外掛返回的內容超出上限。", + "gw.plugin.threw": "外掛丟擲錯誤:{message}", + "gw.plugin.bad_output": "外掛返回的內容不符合要求:{detail}", + "gw.plugin.permission_violation": "外掛修改了未獲授權的內容:{detail}", + "gw.plugin.trap": "沙箱中止了外掛的執行:{detail}", + "gw.plugin.request_unreadable": "無法為外掛讀取請求:{detail}", + "gw.plugin.answer_unreadable": "無法為外掛讀取回答:{detail}", + "gw.plugin.too_large": "外掛檔案超過 {max} 位元組。", + "gw.plugin.syntax": "外掛有語法錯誤:{detail}", + "gw.plugin.syntax_at": "外掛第 {line} 行第 {column} 列有語法錯誤:{detail}", + "gw.plugin.manifest": "外掛清單無效:{detail}", + "gw.plugin.manifest_not_data": "外掛清單不是純資料:{detail}", + "gw.plugin.manifest_not_data_at": "外掛清單第 {line} 行第 {column} 列不是純資料:{detail}", + "gw.plugin.api": "此外掛按外掛 API {api} 編寫,目前只支援 API 1。", + "gw.plugin.engine": "外掛引擎無法載入外掛:{detail}", + "gw.plugin.unreadable": "無法讀取外掛檔案 {file}:{detail}", + "gw.plugin.not_located": "找不到外掛檔案:閘道器不知道配置檔案所在的位置。", + "gw.plugin.setting_type": "設定項 {key} 須為{kind:setting_kind}。", + "gw.plugin.setting_unknown": "外掛沒有宣告設定項 {key}。", + "gw.plugin.not_applicable": "外掛不處理發往 {path} 的請求。", + "gw.plugin.not_declared": "外掛「{plugin}」不處理這類請求。", + "gw.plugin.nothing_to_try": "此請求沒有儲存外掛可以處理的內容。", + "// ── gw.oauth / gw.chatgpt:换访问令牌 ──────────────────────────────": "", + "gw.oauth.not_configured": "上游「{upstream}」未配置 OAuth。", + "gw.oauth.unreachable": "無法連線令牌端點 {endpoint}:{detail}", + "gw.oauth.status": "令牌端點返回 {status}:{body}", + "gw.oauth.no_token": "令牌端點的回應中沒有 access_token。", + "gw.oauth.expired": "OAuth 憑據已過期,請重新登入或更換 refresh token。令牌端點返回 {status}:{body}", + "gw.oauth.held": "閘道器正在更新,登入令牌暫不續期。請稍後重試該請求。", + "gw.oauth.backoff.unreachable": "上一次重新整理令牌失敗,{secs} 秒後重試:無法連線令牌端點 {endpoint}:{detail}", + "gw.oauth.backoff.status": "上一次重新整理令牌失敗,{secs} 秒後重試:令牌端點返回 {status}:{body}", + "gw.oauth.backoff.no_token": "上一次重新整理令牌失敗,{secs} 秒後重試:令牌端點的回應中沒有 access_token。", + "gw.oauth.rotation_queue_full": "待寫回的憑據過多,此次換髮的憑據未寫回配置。", + "gw.oauth.rotation_no_manager": "閘道器以獨立方式執行,此次換髮的憑據未寫回配置。", + "gw.chatgpt.token_unreachable": "無法連線 {endpoint}:{detail}", + "gw.chatgpt.token_status": "令牌端點返回 {status}:{body}", + "gw.chatgpt.token_not_json": "令牌端點的回應不是 JSON。", + "gw.chatgpt.token_missing": "令牌端點的回應中沒有 {field}。", + "gw.codex_catalog.client_version": "Codex 模型目錄需要且只能指定一個 major.minor.patch 格式的 client_version。", + "gw.codex_catalog.too_large": "Codex 模型目錄超過 1 MiB,請減少此閘道器金鑰可用的模型。", + "// ── gw.models / gw.probe:获取模型清单、检查上游 ───────────────────": "", + "gw.models.check_failed": "檢查未透過。", + "gw.models.no_endpoint": "上游沒有提供模型清單的介面(HTTP {status})。", + "gw.models.unrecognized": "上游返回的模型清單格式無法識別。", + "gw.models.empty": "上游返回的模型清單為空。", + "gw.probe.timeout": "{secs} 秒內沒有回應。請檢查介面地址,或確認該上游是否需要經代理訪問。", + "gw.probe.connect": "無法連線。請檢查介面地址的拼寫和網路;如果該上游需要經代理訪問,請先配置代理。", + "gw.probe.request_failed": "請求失敗:{detail}", + "gw.probe.key_rejected": "上游拒絕了此金鑰(HTTP {status})。請檢查金鑰首尾是否有多餘的空白,以及該金鑰是否屬於此上游。", + "gw.probe.aws_token_expired": "AWS 臨時憑證已過期。請更換會話令牌,以及與它一起簽發的訪問金鑰。", + "gw.probe.bedrock_list_denied": "憑證有效,但沒有列出模型的許可權(bedrock:ListFoundationModels 和 bedrock:ListInferenceProfiles)。請求仍會照常轉發;如需按模型路由,請手動列出模型。", + "// ── gw.balance:读取上游余额 ─────────────────────────────────────": "", + "gw.balance.rejected": "無法讀取餘額:上游拒絕了此金鑰(HTTP {status})。", + "gw.balance.status": "無法讀取餘額:上游返回 HTTP {status}。", + "gw.balance.unrecognized": "無法讀取餘額:上游返回的格式無法識別。", + "gw.balance.timeout": "無法讀取餘額:{secs} 秒內沒有回應。", + "gw.balance.connect": "無法讀取餘額:無法連線上游。", + "gw.balance.request_failed": "無法讀取餘額:{detail}", + "gw.config.security_rules": "安全規則無法使用:{detail}", + "gw.model.unknown": "不存在模型 {model},可用模型請參見 GET /v1/models。", + "gw.model.no_upstream": "沒有上游提供模型 {model},可用模型請參見 GET /v1/models。", + "gw.model.not_allowed": "閘道器金鑰「{key}」無權使用模型 {model},可用模型請參見 GET /v1/models。", + "gw.model.not_allowed_rewritten": "路由規則把模型 {from} 改寫為 {model},閘道器金鑰「{key}」無權使用 {model},可用模型請參見 GET /v1/models。", + "gw.model.no_upstream_available": "沒有可用的上游提供模型 {model}:{detail}", + "gw.model.no_upstream_rewritten": "路由規則把模型 {from} 改寫為 {model},但沒有上游提供 {model},可用模型請參見 GET /v1/models。", + "gw.model.alias_unserved": "沒有上游能服務別名 {model}:{models} 均無上游提供,可用模型請參見 GET /v1/models。", + "gw.model.alias_unserved_rewritten": "路由規則把模型 {from} 改寫為別名 {model},但 {models} 均無上游提供,可用模型請參見 GET /v1/models。", + "gw.ws.alias_unserved": "這條 WebSocket 連線接到上游 `{upstream}`,它不提供別名 {model} 的任何一個模型({models}),請求未發出。", + "gw.ws.alias_unserved_rewritten": "路由規則把模型 {from} 改寫為別名 {model}。這條 WebSocket 連線接到上游 `{upstream}`,它不提供其中任何一個模型({models}),請求未發出。", + "gw.model.pinned_not_allowed": "規則「{rule}」指定了上游「{upstream}」的模型 {model},而閘道器金鑰「{key}」無權使用該模型。", + "gw.model.pinned_not_offered": "規則「{rule}」指定的以下模型,其上游並不提供:{detail}。", + "gw.route.failed": "路由失敗:{detail}", + "gw.route.rule_failed": "規則求值失敗:{detail}", + "gw.route.denied": "規則「{rule}」拒絕了此請求:{reason}", + "gw.route.no_upstream_alive": "沒有可用的上游。", + "gw.busy_upstream": "上游「{upstream}」已有 {limit} 個請求在進行,達到其併發上限(max_concurrent)。", + "gw.busy_all": "可處理此請求的上游均已達到併發上限(max_concurrent):{upstreams!names}。等待期間沒有空出位置,請稍後重試。", + "gw.wait.rate_limited": "可處理此請求的上游均因返回 429(速率限制)而暫停:{upstreams!names}。等待期間沒有恢復,請稍後重試。", + "gw.wait.window_full": "可處理此請求的上游均已達到按分鐘或小時計的用量上限:{upstreams!names}。等待期間沒有空出額度,請稍後重試。", + "gw.wait.used_up": "可處理此請求的上游均已用完當天、當週或當月的用量上限:{upstreams!names}。在最早的重置時刻之前重試無效。", + "gw.wait.mixed": "等待期間沒有可處理此請求的上游恢復可用。因 429 暫停:{rate_limited!names}。達到按分鐘或小時計的用量上限:{window_full!names}。當天、當週或當月的用量上限已用完:{used_up!names}。達到併發上限:{busy!names}。請稍後重試。", + "gw.route.upstream_missing": "配置中不存在「{upstream}」。", + "gw.route.selected_upstream_missing": "規則「{rule}」選中的上游「{upstream}」在配置中不存在。", + "gw.route.socket_target": "當前規則選中的上游與此 WebSocket 連線不同。請透過 HTTP 傳送此請求以使用當前路由。", + "gw.route.changed": "請求發出前路由已更改。請重新傳送請求以使用當前路由。", + "gw.route.history.reasoning": "無法確認當前選中的上游帳號能讀取此對話的加密推理。請在當前路由下新建對話。", + "gw.route.history.content": "無法確認當前選中的上游帳號能讀取此對話的加密歷史,例如壓縮上下文或工具結果。請在當前路由下新建對話。", + "gw.route.history.stored": "此請求引用了上游帳號儲存的歷史,無法確認當前帳號能訪問。請在當前路由下新建對話。", + "gw.route.sealed_upstream_gone": "此對話的歷史由上游「{upstream}」加密,該上游已不在配置中,其他上游無法讀取。請開始新的對話。", + "gw.route.all_selected_disabled": "路由選中的上游均已停用:{detail}", + "gw.route.protocol_mismatch": "{path} 只能由 {wanted} 格式的上游處理,而上游「{upstream}」是 {got} 格式。", + "gw.count_tokens.bedrock_upstream": "無法透過 AWS Bedrock 上游「{upstream}」計算 token 數。", + "gw.convert.reasoning_history_incompatible": "帶簽名的思考歷史無法傳送給上游「{upstream}」:來源或請求格式不相容。", + "gw.convert.failed": "無法轉換為上游「{upstream}」的格式:{detail}", + "gw.convert.tool_unsendable": "請求要求使用工具 {tool},但無法按上游「{upstream}」的格式傳送。網頁搜尋這類伺服器端工具只能由所屬的服務商執行。", + "gw.convert.tools_unsendable": "請求要求呼叫工具,但其中的工具都無法按上游「{upstream}」的格式傳送。網頁搜尋這類伺服器端工具只能由所屬的服務商執行。", + "gw.files.unsupported": "閘道器不託管檔案,圖片和文件請直接放在請求中傳送。", + "gw.method.not_forwarded": "{method} {path} 不是 API 呼叫。閘道器只向上遊轉發 POST 請求。", + "gw.request.body_declared_too_large": "請求宣告的長度為 {size} 位元組,超過上限 {max} 位元組。", + "gw.request.body_over_limit": "請求本文超過上限 {max} 位元組。", + "gw.request.decoded_body_over_limit": "請求本文解碼後超過上限 {max} 位元組。", + "gw.request.body_idle": "請求內容已連續 30 秒沒有新資料,請重新傳送請求。", + "gw.request.body_unreadable": "無法讀取請求本文:{detail}", + "gw.request.memory_busy": "閘道器正在處理其他大請求,請稍後重試。", + "gw.request.bad_encoding": "請求本文無法按 {encoding} 解碼:{detail}", + "gw.request.unsupported_encoding": "請求本文以 {encoding} 編碼,閘道器只解碼 gzip、deflate 和 zstd。", + "gw.upstream.timeout": "上游回應超時。", + "gw.upstream.unreachable": "無法連線上游 {url},請檢查介面地址、網路和代理設定。", + "gw.upstream.forward_failed": "轉發失敗:{detail}", + "gw.upstream.body_broken": "回答接收途中與上游的連線斷開:{detail}", + "gw.upstream.rate_limited": "上游「{upstream}」觸發速率限制。", + "gw.upstream.sealed_elsewhere": "上游「{upstream}」無法讀取此對話中加密的歷史:歷史由另一個上游加密,只有該上游能夠讀取。請將此對話改回原來的上游,或開始新的對話。上游返回:{message}", + "gw.upstream.paused": "上游「{upstream}」返回 429(速率限制),已暫停傳送,約 {secs} 秒後恢復。", + "gw.upstream.window_full": "上游「{upstream}」已達到一條按分鐘或小時計的用量上限,約 {secs} 秒後空出額度。", + "gw.upstream.period_used_up": "上游「{upstream}」當天、當週或當月的一條用量上限已用完,將於 {resets} 重置。", + "gw.upstream.status": "上游「{upstream}」返回 {status}。", + "gw.upstream.status_message": "上游「{upstream}」返回 {status}:{message}", + "gw.upstream.response_error": "上游「{upstream}」在回應中返回錯誤:{message}", + "gw.upstream.stream_opening_error": "上游「{upstream}」開始回答後、給出任何內容之前報錯({kind}):{message}", + "gw.upstream.stream_ended_early": "上游在給出任何內容之前結束了回答。", + "gw.upstream.idle_timeout": "上游「{upstream}」在 {secs} 秒內沒有發出內容。", + "gw.upstream.idle_timeout_mid_stream": "上游「{upstream}」回答到一半後停止傳送內容,{secs} 秒內沒有新的內容。", + "gw.upstream.too_slow": "上游「{upstream}」最近 {secs} 秒的生成速度為 {rate} token/秒,低於最低生成速度 {min} token/秒。", + "gw.request.aborted": "請求已被手動中止。", + "gw.upstream.stream_error": "上游「{upstream}」在回答過程中報錯:{message}", + "gw.upstream.stream_exception": "上游「{upstream}」以 {kind} 結束了回應流:{message}", + "gw.upstream.eventstream_broken": "上游「{upstream}」發來了損壞的 AWS eventstream 幀:{detail}", + "gw.upstream.sign_failed": "無法用 AWS 訪問金鑰為發往上游「{upstream}」的請求籤名:{detail}", + "gw.upstream.aws_token_expired": "上游「{upstream}」的 AWS 臨時憑證已過期。請更換它的會話令牌,以及與之一起簽發的訪問金鑰。", + "gw.upstream.aws_profile_expired": "上游「{upstream}」的 AWS 臨時憑證已過期。請重新整理 AWS profile「{profile}」,下一個請求會重新讀取。", + "gw.upstream.bedrock_refused": "AWS 拒絕了上游「{upstream}」的憑證(HTTP {status},{kind})。請檢查憑證是否有效、是否有權使用此模型。AWS 的原話包含帳號資訊,因此不予轉發。", + "gw.upstream.bedrock_refused_unnamed": "AWS 拒絕了上游「{upstream}」的憑證(HTTP {status})。請檢查憑證是否有效、是否有權使用此模型。AWS 的原話包含帳號資訊,因此不予轉發。", + "gw.content.refused": "請求命中內容規則「{rule:content_rule|{name}}」(「{excerpt}」),未發出。", + "gw.content.refused_invisible_message": "訊息中含有 {count} 個不可見字元,命中內容規則「{rule:content_rule|{name}}」,請求未發出。", + "gw.content.refused_invisible_tool_result": "請求中的工具結果含有 {count} 個不可見字元,命中內容規則「{rule:content_rule|{name}}」,請求未發出。", + "gw.toolcall.response_cut": "回答中的 {tool} 呼叫命中規則「{?why:{rule:scan_rule}|{name}}」{?why:({rule:rule_why})},已切斷回應。", + "gw.toolcall.response_withheld": "回答中的 {tool} 呼叫命中規則「{?why:{rule:scan_rule}|{name}}」{?why:({rule:rule_why})},整份回應已扣下。", + "gw.ws.bad_url": "上游地址不是合法的 WebSocket 地址:{detail}", + "gw.ws.bad_header": "上游的請求頭「{header}」包含請求頭中不允許的字元。", + "gw.ws.connect_failed": "無法連線上游的 WebSocket:{detail}", + "gw.ws.send_failed": "向上遊傳送資料失敗:{detail}", + "gw.ws.upstream_broke": "上游連線中斷:{detail}", + "gw.ws.upstream_closed": "上游在回答完成前關閉了連線。", + "gw.ws.proxy_unsupported": "上游「{upstream}」配置了代理({proxy}),WebSocket 連線暫不支援經代理轉發,僅支援直連的上游。", + "gw.toolcall.connection_cut": "回答中的 {tool} 呼叫命中規則「{?why:{rule:scan_rule}|{name}}」{?why:({rule:rule_why})},已切斷連線。", + "// ── control:控制面的 HTTP 错误 ──────────────────────────────────": "", + "control.upstream_not_found": "未找到名為「{upstream}」的上游。", + "control.balance_none": "上游「{upstream}」沒有可讀取的餘額。", + "control.proxy_not_found": "未找到名為「{proxy}」的代理。", + "control.route_not_found": "未找到名為「{route}」的路由。", + "control.sheet_not_found": "未找到名為「{sheet}」的價目表。", + "control.key_not_found": "未找到名為「{key}」的閘道器金鑰。", + "control.listen.bad_port": "埠須在 1 到 65535 之間。", + "control.replay_bedrock": "重放會原樣傳送記錄下的請求,而「{upstream}」是 Bedrock 上游,只接受用戶端不會傳送的 Converse 格式。請重放到與用戶端格式相同的上游。", + "control.replay_alias_unserved": "{model} 是別名,而上游「{upstream}」不提供它列出的任何模型,無法將請求重放到該上游。", + "// ── gw.listen:网关换监听地址 ────────────────────────────────────": "", + "gw.listen.port_taken": "{addr} 已被其他程式佔用。", + "gw.listen.addr_unavailable": "{addr} 當前不是本機的地址。", + "gw.listen.denied": "系統不允許監聽 {addr},1024 以下的埠需要管理員許可權。", + "gw.listen.bind_failed": "無法監聽 {addr}:{detail}", + "gw.listen.no_such_nic": "本機沒有名為 {name} 的網絡卡,現有網絡卡:{available}。", + "gw.listen.nic_offline": "網絡卡 {name} 當前未連線網路,請檢查網線或 Wi-Fi 連線。", + "control.request_not_found": "未找到第 {id} 號請求。", + "control.request_not_running": "第 {id} 號請求不在進行中。", + "// ── security:安全页的规则与档位 ──────────────────────────────────": "", + "security.unknown_guard": "「{guard}」不是一項防護,只能是 redact、inspect_tools 或 content。", + "security.unknown_rule": "沒有名為「{rule}」的內建規則。", + "security.rule_name_empty": "規則需要一個名稱。", + "security.bad_pattern": "正規表示式有誤:{detail}", + "security.unknown_action": "「{action}」不是可用的動作,只能是 cut 或 record。", + "security.content_action_bad": "「{action}」不是可用的動作,只能是 block、strip、replace 或 record。", + "security.redact_action_unknown": "「{action}」不是可用的動作,只能是 placeholder 或 record。", + "security.bad_content_pattern": "匹配內容無法使用:{detail}", + "security.bad_codepoints": "碼位寫法有誤:{detail}", + "security.bad_label": "佔位符名稱「{label}」不可用:須以大寫字母開頭,由 1 到 24 個大寫字母、數字或下劃線組成。", + "security.redact_match_bad": "金鑰與隱私規則只能按「包含」或「正則」匹配,不支援「{matching}」。", + "security.pattern_empty": "匹配內容為空。", + "security.unknown_custom_rule": "沒有名為「{rule}」的自定義規則。", + "security.rule_scope_empty": "內容規則須至少檢查請求或回答中的一項。", + "security.rule_scope_block": "檢查回答的規則不能拒絕:發現命中時,回答已在傳送途中。請選擇刪除、替換或僅記錄。", + "security.rule_scope_codepoints": "碼位只在請求中檢查,檢查回答的規則須按「包含」或「正則」匹配。", + "security.unknown_event": "安全日誌中沒有第 {id} 條記錄,可能已超過保留期。", + "security.exception_not_exceptable": "只有金鑰與隱私找到的值可以列為例外;儲存的金鑰、由幾處重疊命中合成的一段不能列為例外。", + "security.exception_forgotten": "這條記錄較早,無法從日誌列為例外。請將這個值貼上到「新增例外」中加入。", + "security.exceptions_full": "例外已有 {max} 個,達到上限。請先移出一個再新增。", + "security.exception_value_empty": "值為空。", + "security.exception_saved_secret": "這個值是 ThinkWatch 中儲存的金鑰,儲存的金鑰始終替換,不能列為例外。", + "control.session_not_found": "未找到會話 {id}。", + "control.session_not_running": "會話 {id} 沒有正在進行的請求。", + "control.client_unknown": "未知的用戶端「{client}」。", + "control.store_off": "請求記錄未啟動。", + "control.store_unavailable": "請求記錄不可用,資料庫無法開啟或磁碟出錯,轉發不受影響。", + "control.no_keys": "config.yaml 中尚無閘道器金鑰,請先建立閘道器金鑰,再接管用戶端。", + "control.key_create_failed": "無法建立閘道器金鑰:{detail}", + "control.name_empty": "{kind:kind}名稱不能為空。", + "control.name_whitespace": "{kind:kind}名稱首尾不能包含空白。", + "control.name_reserved": "{kind:kind}名稱不能以 {prefix} 開頭,該字首保留給內建項。", + "control.name_is_builtin": "「{name}」是內建選項的名稱,請使用其他名稱。", + "control.shutdown": "閘道器正在關閉。", + "control.handover.busy": "帳號登入或另一次交接正在進行,完成後再試。", + "control.handover.endpoint_failed": "無法開啟交接端點:{detail}", + "control.handover.login_refused": "閘道器即將更新,請在更新完成後重新登入。", + "control.handover.remote": "不能經遠端連線準備交接。", + "control.handover.safe_mode": "閘道器處於安全模式、沒有在轉發,無需交接。", + "control.no_such_endpoint": "控制面沒有 {method} {path} 端點,桌面應用與閘道器的版本可能不一致。", + "control.method_not_allowed": "控制面不接受對 {path} 的 {method} 請求,桌面應用與閘道器的版本可能不一致。", + "control.request_rejected": "控制面無法讀取該請求:{detail}", + "control.base_url_empty": "介面地址不能為空。", + "control.api_key_empty": "API 金鑰不能為空。", + "control.user_empty": "使用者名稱不能為空。", + "control.header_no_value": "請求頭「{header}」缺少值。", + "control.proxy_addr_form": "代理地址「{addr}」應寫成 主機:埠 的形式。", + "control.dryrun_needs_target": "請指定閘道器金鑰或路由。", + "control.request_body_gone": "第 {id} 號請求的請求本文已不存在,可能已被清理。", + "control.response_body_gone": "第 {id} 號請求的回應本文已不存在,可能已被清理。", + "control.request_body_truncated": "第 {id} 號請求的請求本文有 {original} 位元組,僅儲存了 {kept} 位元組,無法原樣重放。", + "control.signin_response_unusable": "無法開始登入:{detail}", + "control.device_code_unavailable": "此帳號尚不支援裝置碼登入,請改用在本機登入。", + "control.device_code_failed": "換裝置碼時返回 {status}:{detail}", + "control.callback_ports_busy": "登入回撥埠 {ports} 均被佔用。如果 Codex 正在登入,請先完成或關閉它。", + "control.redirect_must_be_app_scheme": "登入完成後的跳轉地址只能使用應用自己的協議,不能是網頁地址。", + "control.name_taken_not_chatgpt": "已有名為「{name}」的上游,且不是 ChatGPT 帳號上游,請使用其他名稱。", + "control.name_taken_not_zai": "已有名為「{name}」的上游,且不是該服務的帳號上游,請使用其他名稱。", + "control.not_a_chatgpt_account": "上游「{upstream}」不是 ChatGPT 帳號上游。", + "control.signin_gone": "未找到此次登入,或它已被新的登入替代。", + "control.chatgpt_backend_status": "ChatGPT 後端返回 {status}:{detail}", + "control.chatgpt_backend_not_json": "ChatGPT 後端的回應不是 JSON。", + "control.reset_cards_unreadable": "無法識別重置卡清單:{detail}", + "control.reset_card_result_unreadable": "無法識別使用重置卡的結果。", + "control.bad_idempotency_key": "冪等鍵不能為空,且不超過 128 個字元。", + "control.device_code_unreadable": "無法識別裝置碼請求的回應:{detail}", + "control.account_service_status": "帳號服務返回 {status}:{detail}", + "control.account_service_not_json": "帳號服務的回應不是 JSON:{detail}", + "control.account_service_refused": "帳號服務拒絕了請求:{why}", + "control.chatgpt_login.device_status": "登入返回 {status}:{body}", + "control.chatgpt_login.approval_unreadable": "無法識別授權結果:{detail}", + "control.chatgpt_login.expired": "15 分鐘內未完成授權。", + "control.chatgpt_login.page_error": "授權頁面返回了錯誤:{detail}", + "control.chatgpt_login.no_code": "回撥中沒有授權碼。", + "control.zai_login.refused": "授權被拒絕。", + "control.zai_login.unknown_state": "授權處於無法識別的狀態:{state}", + "control.zai_login.expired": "未在限定時間內完成授權。", + "control.zai_login.no_access_token": "授權結果中沒有訪問令牌。", + "control.zai_login.no_account_token": "帳號令牌的回應中沒有令牌。", + "control.zai_login.no_project": "該帳號沒有可用於建立 API 金鑰的組織和專案。", + "control.zai_login.key_without_id": "新建的 API 金鑰缺少 ID。", + "control.zai_login.key_id_unexpected": "API 金鑰的 ID 中含有無法識別的字元。", + "control.zai_login.key_without_secret": "返回的 API 金鑰缺少金鑰值。", + "control.provider_test.oauth_unsaved": "OAuth 憑據需要先儲存才能檢查。如需現在檢查,請同時填寫訪問令牌。", + "control.rotation.written": "已寫回 {path}(版本 {version})。", + "control.remote.shutdown_refused": "無法透過遠端連線停止 core。伺服器上的 core 由服務管理器管理,例如執行 systemctl stop twcore。", + "control.remote.diagnostics_refused": "診斷包只能在 core 所在的機器上生成。", + "control.remote.control_section_locked": "listen.control 不能透過遠端連線修改:當前連線正是經由其中的埠進入。請在伺服器上使用 twcore remote 修改,或直接編輯那裡的配置檔案。", + "control.control_key_locked": "listen.control.key 不能在這裡修改。請在 core 所在的機器上執行 twcore control-key --rotate,或直接編輯那裡的配置檔案。", + "control.internal_error": "閘道器內部出錯:{detail}", + "control.records_unreadable": "無法讀取請求記錄:{detail}", + "control.listen.bind_invalid": "bind 只能是 loopback、all、網絡卡名(如 en0)或地址(如 192.168.1.5),當前為 {bind}。", + "// ── control:改配置时的失败 ────────────────────────────────────────": "", + "control.config_unrepairable": "配置檔案裡沒有可以自動修復的錯誤。請修改配置檔案,或從備份中恢復之前的版本。", + "control.config_stale": "版本不一致:本次修改基於 {base},當前版本為 {current}。請重新整理後重新修改。", + "control.patch.no_entry": "{path} 中沒有名為「{name}」的條目。列表條目按名稱或序號查詢。", + "control.patch.not_an_entry": "{path} 沒有指向列表中的某一項。刪除時需指明條目,例如 /clients/codex。", + "control.default_key_cannot_disable": "預設金鑰不能停用。所有未單獨接入閘道器的用戶端都使用它,停用會使這些用戶端全部無法使用。", + "control.default_key_cannot_delete": "預設金鑰不能刪除。所有未單獨接入閘道器的用戶端都使用它,刪除後這些用戶端將無法連線。", + "control.disabled_key_cannot_be_default": "閘道器金鑰「{key}」已停用,不能設為預設金鑰。", + "control.key_used_by_client": "{client} 已接管到閘道器,其配置中使用了該金鑰。請先還原該用戶端,再刪除金鑰。", + "control.models_unreadable": "無法從 {url} 讀取模型列表:{detail}", + "// 引用列表是 core 拼的英文说明(「rule `x` of route `y`」),原样显示": "", + "control.key_in_use": "閘道器金鑰「{key}」仍被 {refs} 引用,請先移除這些引用再刪除。", + "control.upstream_in_use": "上游「{upstream}」仍被 {refs} 引用,請先移除這些引用再刪除。", + "control.group_in_use": "策略組「{group}」仍被 {refs} 引用,請先移除這些引用再刪除。", + "control.proxy_in_use": "代理「{proxy}」仍被上游{upstreams!names}使用,請先解除關聯再刪除。", + "control.sheet_in_use": "價目表「{sheet}」仍被上游{upstreams!names}使用,請先解除關聯再刪除。", + "control.default_route_cannot_delete": "路由「{route}」是預設路由,不能刪除。請先將其他路由設為預設路由。", + "control.reassign_to_deleted_route": "閘道器金鑰不能改用正在刪除的路由「{route}」。", + "control.builtin_group_fixed": "每個上游的內建策略組隨上游列表自動生成,不能編輯或刪除。", + "control.route.duplicate_rule": "路由中有兩條名為「{rule}」的規則。", + "control.rule.condition_no_value": "規則「{rule}」:條件 {field} 沒有值。", + "control.rule.condition_one_value": "規則「{rule}」:條件 {field} 只能有一個值。", + "control.rule.condition_twice": "規則「{rule}」:條件 {field} 出現了兩次。", + "control.rule.condition_not_bool": "規則「{rule}」:條件 {field} 只能是 true 或 false,當前為「{value}」。", + "control.rule.no_such_key": "規則「{rule}」:不存在閘道器金鑰「{key}」。", + "control.rule.unknown_dialect": "規則「{rule}」:不支援用戶端格式「{dialect}」。", + "control.rule.no_such_probe_class": "規則「{rule}」:沒有「{class}」這一類輔助請求。", + "control.rule.no_such_upstream": "規則「{rule}」:不存在上游「{upstream}」。", + "control.rule.deny_needs_reason": "規則「{rule}」:拒絕時需要填寫原因。", + "control.rule.forward_and_deny": "規則「{rule}」不能同時轉發和拒絕。", + "control.group.name_is_upstream": "「{name}」已是上游的名稱。規則按名稱指向上游或策略組,兩者不能同名。", + "control.group.no_such_upstream": "不存在上游「{upstream}」。", + "control.group.upstream_twice": "上游「{upstream}」重複。", + "control.group.empty": "策略組至少需要一個上游。", + "control.group.preferred_not_member": "優先使用的上游「{upstream}」不在該策略組中。", + "control.group.weight_not_member": "為「{upstream}」設定了權重,但它不是該策略組的成員。", + "control.group.weight_not_load_balance": "上游「{upstream}」的權重為 {weight},只有輪詢策略組使用權重。", + "control.group.weight_out_of_range": "上游「{upstream}」的權重為 {weight},權重須為 1 到 100 之間的整數。", + "control.group.balance_not_load_balance": "balance_by「{balance_by}」只適用於輪詢策略組。", + "// ── control.plugin:装插件、改插件、批准文件、试运行。{plugin} 在 ID 上是 id,在确认上是插件的名字 ──": "", + "control.plugin.not_found": "外掛「{plugin}」不存在。", + "control.plugin.bad_id": "「{plugin}」不是有效的外掛 ID:只能使用小寫字母、數字和連字元,1 到 {max} 個字元。", + "control.plugin.id_taken": "已存在 ID 為「{plugin}」的外掛。", + "control.plugin.blank_pattern": "適用範圍中有空白項。請刪除該項,或填寫名稱或帶 * 的通配。", + "control.plugin.unreadable": "無法讀取外掛檔案 {file}:{detail}", + "control.plugin.write_failed": "無法寫入 {path}:{detail}", + "control.plugin.needs_confirmation": "外掛「{plugin}」可以修改回答中的工具呼叫,因此安裝、啟用此外掛,修改其程式碼或確認其檔案的更改,都需要在應用中確認。", + "control.plugin.file_missing": "外掛「{plugin}」的檔案已不存在,沒有可確認的更改。請更換程式碼,或刪除此外掛。", + "control.plugin.file_moved_on": "外掛「{plugin}」的檔案在稽核之後再次被改動,請重新稽核。", + "control.plugin.order": "新的順序須包含每個外掛,且每個只出現一次。", + "control.plugin.trial_changed": "外掛「{plugin}」的檔案已更改且尚未確認,無法試執行。", + "// ── control.pricing:刷新默认价目表 ──────────────────────────────": "", + "control.pricing.unreachable": "無法連線價格資料來源:{detail}", + "control.pricing.status": "價格資料來源返回 HTTP {status}。", + "control.pricing.broke_off": "下載中斷:{detail}", + "control.pricing.too_large": "下載的檔案超過 {mb} MB,不是價格資料。", + "control.pricing.not_a_dataset": "下載的內容不是價格資料:{detail}", + "control.pricing.save_failed": "無法儲存價目表:{detail}", + "// ── config:配置文件的读写与校验 ─────────────────────────────────": "", + "//": "", + "// 语法和字段错误的原话是 serde 的英文,这边只翻外面那一层(哪一关、第几行)": "", + "config.rejected": "配置有{stage:stage}錯誤:{detail}", + "config.rejected_at": "配置第 {line} 行有{stage:stage}錯誤:{detail}", + "config.unknown_field": "{field} 不是可用的欄位,可用的有:{expected}", + "config.unknown_variant": "{field} 不能取 {value},可選值:{expected}", + "config.schema_too_new": "配置的格式版本為 {found},當前 twcore 最高支援 {supported}。請升級應用,或將配置改回舊格式。", + "config.remote_port_zero": "listen.control.remote.port 為 0,應在 1–65535 之間。twcore remote enable 會自動選擇一個空閒埠。", + "config.remote_port_is_gateway": "listen.control.remote.port 為 {port},與閘道器埠相同。兩者需要使用不同的埠。", + "config.bad_remote_allow_from": "listen.control.remote.allow_from 中的「{entry}」有誤:不是有效的 IP 地址或 CIDR,應寫作 192.168.0.0/16 這樣的格式。", + "config.control_key_missing": "配置中沒有 listen.control.key,桌面應用憑它連線 core。twcore serve 啟動時會自動寫入;twcore control-key --rotate 會寫入一把新的。", + "config.control_key_invalid": "listen.control.key 應為 64 位十六進位制字元。twcore control-key --rotate 會寫入一把新的。", + "config.no_clients": "配置的 clients 中沒有閘道器金鑰,所有請求都會被拒絕。首次啟動時會自動生成一把。", + "config.duplicate_upstream": "上游名稱「{upstream}」重複。路由規則按名稱引用上游,名稱必須唯一。", + "config.duplicate_key_name": "閘道器金鑰名稱「{key}」重複。", + "config.duplicate_key_value": "閘道器金鑰「{key}」和「{other}」的值相同。閘道器按金鑰區分用戶端,金鑰的值必須唯一。", + "config.default_key_missing": "default_key 指向的閘道器金鑰「{key}」不存在。", + "config.default_key_disabled": "預設閘道器金鑰「{key}」已停用。所有未單獨接入閘道器的用戶端都使用它,停用會使這些用戶端全部無法使用。", + "config.duplicate_client_key": "閘道器金鑰「{key}」和「{other}」都標記為用戶端 {client} 專用,一個用戶端只能有一把。", + "config.bad_base_url": "上游「{upstream}」的介面地址既不是 http 也不是 https:{url}", + "config.empty_key": "閘道器金鑰「{key}」的值為空。", + "config.base_url_backslash": "上游「{upstream}」的介面地址含有反斜槓:{url}。地址中請只使用正斜槓。", + "config.base_url_userinfo": "上游「{upstream}」的介面地址在主機前帶有使用者名稱或密碼。憑據請改寫在 key 或 headers 中。", + "config.zero_concurrency": "閘道器金鑰「{key}」的 max_concurrent 為 0,使用它的請求會一直等待。不限制併發時請刪除 max_concurrent。", + "config.min_speed_range": "上游「{upstream}」的 min_speed.{field} 為 {value},須在 {min} 到 {max} 之間。", + "config.provider_concurrency_range": "上游「{upstream}」的 max_concurrent 為 {value},須在 1 到 {max} 之間。不限制併發時請刪除 max_concurrent。", + "config.redact_exceptions_too_many": "security.redact.exceptions 中有 {count} 個值,最多 {max} 個。", + "config.redact_exception_hash_bad": "security.redact.exceptions 中的例外「{sha256}」不是 SHA-256:須為 64 個小寫十六進位制字元。", + "config.redact_exception_duplicate": "例外「{sha256}」在 security.redact.exceptions 中出現了兩次。", + "config.key_limit_empty": "閘道器金鑰「{key}」的一條用量上限沒有寫明計量。limits 中的每一條須寫 requests、tokens、cost 之一。", + "config.key_limit_two_measures": "閘道器金鑰「{key}」的一條用量上限同時寫了 {measures:limit_measures}。每一條只能寫 requests、tokens、cost 之一,請分成多條。", + "config.key_limit_not_positive": "閘道器金鑰「{key}」的一條用量上限({measure:limit_measure},每{per:limit_per})為 {value},須大於 0。", + "config.key_limit_duplicate": "閘道器金鑰「{key}」有兩條相同的用量上限({measure:limit_measure},每{per:limit_per}),請只保留一條。", + "config.key_limit_cache_reads": "閘道器金鑰「{key}」的一條用量上限({measure:limit_measure})設定了 cache_reads,只有 token 數上限可以設定該項。", + "config.key_limit_retention": "閘道器金鑰「{key}」設定了每{per:limit_per}的用量上限,而 retention.row_days 為 {days}。重啟後當{per:limit_per}用量要從請求記錄中重新累計,因此 row_days 須至少為 {min}。", + "config.key_limit_cost_too_small": "閘道器金鑰「{key}」每{per:limit_per}的費用上限為 {value},須至少為 0.01。", + "config.key_limit_every": "閘道器金鑰「{key}」一條每{per:limit_per}用量上限的 every 為 {every},per 為 {per} 時 every 須在 1 到 {max} 之間。", + "config.key_limit_every_calendar": "閘道器金鑰「{key}」一條每{per:limit_per}的用量上限設定了 every,只有 per 為 minute 或 hour 的上限可以設定該項。天、周、月均從本地時間零點起算。", + "config.upstream_limit_empty": "上游「{upstream}」的一條用量上限沒有寫明計量。limits 中的每一條須寫 requests、tokens、cost 之一。", + "config.upstream_limit_two_measures": "上游「{upstream}」的一條用量上限同時寫了 {measures:limit_measures}。每一條只能寫 requests、tokens、cost 之一,請分成多條。", + "config.upstream_limit_not_positive": "上游「{upstream}」的一條用量上限({measure:limit_measure},每{per:limit_per})為 {value},須大於 0。", + "config.upstream_limit_duplicate": "上游「{upstream}」有兩條相同的用量上限({measure:limit_measure},每{per:limit_per}),請只保留一條。", + "config.upstream_limit_cache_reads": "上游「{upstream}」的一條用量上限({measure:limit_measure})設定了 cache_reads,只有 token 數上限可以設定該項。", + "config.upstream_limit_retention": "上游「{upstream}」設定了每{per:limit_per}的用量上限,而 retention.row_days 為 {days}。重啟後當{per:limit_per}用量要從請求記錄中重新累計,因此 row_days 須至少為 {min}。", + "config.upstream_limit_cost_too_small": "上游「{upstream}」每{per:limit_per}的費用上限為 {value},須至少為 0.01。", + "config.upstream_limit_every": "上游「{upstream}」一條每{per:limit_per}用量上限的 every 為 {every},per 為 {per} 時 every 須在 1 到 {max} 之間。", + "config.upstream_limit_every_calendar": "上游「{upstream}」一條每{per:limit_per}的用量上限設定了 every,只有 per 為 minute 或 hour 的上限可以設定該項。天、周、月均從本地時間零點起算。", + "config.name_collision": "「{name}」同時是上游和策略組的名稱,規則的 to 無法區分指的是哪一個。請重新命名其中一個。", + "config.bad_allow_from": "listen.gateway.allow_from 中的 {entry} 不是有效的 IP 地址或 CIDR,應寫成 192.168.0.0/16 的形式。", + "config.unknown_price_sheet": "上游「{upstream}」使用的價目表「{sheet}」不存在。", + "config.empty_models_only": "上游「{upstream}」的模型範圍(models_only)為空,不提供任何模型。暫停使用該上游請改為停用(disabled: true)。", + "config.blank_models_only": "上游「{upstream}」的模型範圍(models_only)中有空白項。", + "config.alias_empty_name": "aliases 中有一個別名的名稱為空。", + "config.alias_wildcard": "別名名稱「{alias}」含有 * 或 ?。別名只能是一個確切的名稱;要匹配多個模型,請在閘道器金鑰的 allow 或規則的 when.model 中寫通配。", + "config.alias_reserved": "別名名稱「{alias}」以 __ 開頭,該字首保留給內建項,請使用其他名稱。", + "config.alias_duplicate": "別名名稱「{alias}」重複。", + "config.alias_no_models": "別名「{alias}」沒有列出任何模型。請列出各上游對該模型使用的名稱,或刪除該別名。", + "config.alias_blank_model": "別名「{alias}」列出的模型中有空白項。", + "config.alias_chained": "別名「{alias}」列出的 {model} 本身也是別名。別名列出的應是上游使用的模型名稱,不能是其他別名。", + "config.alias_only_itself": "別名「{alias}」只列出了它自己,不起任何作用。請列出各上游使用的名稱,或刪除該別名。", + "config.manual_model_blank": "上游「{upstream}」手動新增的模型(models)中有空白項。", + "config.manual_model_padded": "上游「{upstream}」手動新增的模型「{model}」首尾有空白,請去掉。", + "config.manual_model_wildcard": "上游「{upstream}」手動新增的模型「{model}」含有 * 或 ?。手動新增的模型須為確切的模型 ID;只使用上游的部分模型,請設定啟用範圍(models_only)。", + "config.manual_model_duplicate": "模型「{model}」在上游「{upstream}」手動新增的模型中重複。", + "config.manual_model_too_long": "上游「{upstream}」手動新增的模型中有一項超過 {max} 個字元。", + "config.model_spec_effort_duplicate": "上游「{upstream}」模型「{model}」的推理檔位「{level}」重複。", + "config.model_spec_effort_default": "上游「{upstream}」模型「{model}」的預設推理檔位必須屬於 supported_levels。", + "config.model_spec_effort_disabled": "上游「{upstream}」模型「{model}」已禁用推理,不能同時指定非空推理檔位。", + "config.model_spec_blank_model": "上游「{upstream}」的模型規格(model_specs)中有一項的模型 ID 為空。", + "config.model_spec_wildcard": "上游「{upstream}」的模型規格「{model}」含有 * 或 ?。模型規格只能對應一個確切的模型 ID。", + "config.model_spec_nothing_set": "上游「{upstream}」的模型規格「{model}」中沒有設定任何規格。請至少設定一項,或刪除該規格。", + "config.model_spec_zero": "上游「{upstream}」的模型規格「{model}」中 {field} 為 0,須為大於 0 的 token 數。要使用價目表中的值,請刪除該項。", + "config.reserved_name": "{what:kind}名稱「{name}」以 __ 開頭,該字首保留給內建項,請使用其他名稱。", + "config.rule_name_empty": "有一條自定義{what:rule_line}規則沒有名稱。", + "config.rule_name_taken": "自定義{what:rule_line}規則名稱「{name}」重複。", + "config.rule_pattern_empty": "自定義{what:rule_line}規則「{name}」的{what:pattern_of}為空。", + "config.rule_pattern_bad": "自定義{what:rule_line}規則「{name}」的{what:pattern_of}有誤:{detail}", + "config.rule_codepoints_bad": "自定義內容過濾規則「{name}」的碼位寫法有誤:{detail}", + "config.rule_label_bad": "金鑰與隱私的自定義規則「{name}」的佔位符名稱為「{label}」,須以大寫字母開頭,由 1 到 24 個大寫字母、數字或下劃線組成。", + "config.rule_scope_empty": "自定義內容過濾規則「{name}」的檢查物件(scope)為空,須至少包含 request 或 response。", + "config.rule_scope_block": "自定義內容過濾規則「{name}」檢查回答,動作卻為 block。發現命中時回答已在傳送途中,檢查回答的規則只能為 strip、replace 或 record。", + "config.rule_scope_codepoints": "自定義內容過濾規則「{name}」檢查回答,匹配方式卻為 codepoints。碼位只在請求中檢查,檢查回答的規則只能為 contains 或 regex。", + "config.rule_match_bad": "金鑰與隱私的自定義規則「{name}」的匹配方式為「{matching}」,金鑰與隱私規則只能為 contains 或 regex。", + "config.unknown_rule": "security.{guard} 中的「{rule}」不是內建規則。", + "config.failover_range": "failover.{field} 為 {value},須在 {min} 到 {max} 之間。", + "config.plugin.bad_id": "外掛 ID「{plugin}」寫法有誤:只能使用小寫字母、數字和連字元,1 到 {max} 個字元。", + "config.plugin.duplicate": "外掛 ID「{plugin}」重複。", + "config.plugin.file": "外掛「{plugin}」的檔案為 {file},應為 plugins/{plugin}.js。", + "config.plugin.sha256": "外掛「{plugin}」的 sha256 應為 64 位小寫十六進位制字元。", + "config.store.read_failed": "無法讀取 {path}:{detail}", + "config.store.missing": "{path} 不存在。", + "config.store.conflict": "配置檔案在此期間已被修改(當前版本 {current},本次修改基於 {expected}),未覆蓋。請檢視當前內容後重試。", + "config.edit.name_taken": "已存在名為「{name}」的{what:kind}。", + "config.edit.not_found": "未找到名為「{name}」的{what:kind}。", + "config.edit.nameless": "{what:kind}沒有名稱。", + "config.edit.multiline": "值中不能包含換行。", + "config.edit.parse": "無法解析配置檔案:{detail}", + "config.edit.unwritable": "該值無法寫入配置:{detail}", + "config.edit.self_check": "修改結果與預期不符({detail}),未寫入任何內容。", + "// ── pack / import / backup:配置包、导入、备份与恢复 ─────────────────": "", + "pack.need_passphrase": "此配置包已用口令加密,須輸入口令才能開啟。", + "pack.wrong_passphrase": "口令不正確。", + "pack.not_encrypted": "此配置包未加密,而此處要求加密,未開啟。", + "pack.too_much_work": "此配置包的口令加密所需的計算量超出當前版本允許的範圍(工作因子 {required},最多 {max}),未開啟。", + "pack.need_key": "此配置包是為同步位置加密的,不能用口令開啟。", + "pack.wrong_key": "此配置包以另一把金鑰加密。", + "pack.too_new": "此配置包由較新版本匯出(Core {version},格式 {format}),請先更新 ThinkWatch Lite。", + "pack.corrupt": "此檔案不是可讀取的配置包:{detail}", + "pack.bad_entry": "此配置包中含有配置包不允許的「{name}」,未開啟。", + "pack.missing_entry": "此配置包缺少 {name}。", + "pack.too_large": "此配置包超過 {limit} MiB。", + "pack.schema_too_new": "此配置的結構版本為 {schema},當前版本最高支援 {supported},請先更新 ThinkWatch Lite。", + "pack.item_shape": "{item} 無法寫入配置:{detail}", + "pack.verify_failed": "拼合後的配置讀回與預期不符({detail}),未寫入任何內容。", + "pack.no_such_item": "沒有名為「{name}」的{kind:item_kind}。", + "pack.not_base64": "檔案內容不是有效的 Base64:{detail}", + "pack.passphrase_short": "口令至少需要 {min} 個字元。", + "import.exists": "此處已有名為「{name}」的{kind:item_kind},請選擇覆蓋、改名匯入或跳過。", + "import.name_taken": "已有名為「{name}」的{kind:item_kind}。", + "import.not_in_pack": "配置包中沒有名為「{name}」的{kind:item_kind}。", + "import.key_value_taken": "閘道器金鑰「{key}」的值與此處的閘道器金鑰「{other}」相同。", + "import.missing_reference": "{kind:item_kind}「{name}」引用的{target_kind:item_kind}「{target}」既不在此處,也不在配置包中。", + "import.skipped_reference": "{kind:item_kind}「{name}」引用的{target_kind:item_kind}「{target}」已跳過。", + "import.no_aws_profile": "上游「{name}」使用 AWS profile「{profile}」,本機沒有該 profile。", + "import.plugin_missing": "配置包中沒有外掛「{plugin}」的指令碼。", + "import.plugin_mismatch": "配置包中外掛「{plugin}」的指令碼與已批准的不一致。", + "backup.not_found": "沒有備份版本 {id}。", + "backup.io": "無法讀寫 {path}:{detail}", + "backup.write_failed": "無法寫入 {path}:{detail}", + "backup.prefs_too_large": "通用偏好超過 {limit} KiB。", + "backup.pinned.source_too_long": "固定金鑰的來源標識超過 {max} 位元組。", + "backup.pinned.too_many": "一次上報的固定金鑰超過 {max} 把。", + "backup.pinned.name_too_long": "固定金鑰的名稱超過 {max} 位元組。", + "// ── config.credential:上游凭据的写法 ────────────────────────────": "", + "// 整份配置校验时前面多一句「哪个上游的凭据」,由 `CONTEXT` 接上,这里只说原因": "", + "config.credential.empty_key": "API 金鑰為空。", + "config.credential.key_and_oauth": "key 和 oauth 只能填寫其中一項。", + "config.credential.empty_oauth": "oauth 的 refresh 和 endpoint 都不能為空。", + "config.credential.claude_subscription": "不支援 Claude 訂閱帳號的登入憑據,請使用 Anthropic API 金鑰。", + "config.credential.google_subscription": "不支援 Gemini CLI 的 Google 登入憑據,請使用 Gemini API 金鑰。", + "config.credential.chatgpt_without_login": "ChatGPT 帳號上游只接受登入獲得的憑據。", + "config.credential.chatgpt_client_identity": "ChatGPT 帳號上游始終以 ThinkWatch 的身份傳送請求,不能轉發用戶端的身份。", + "config.credential.identity_header": "請求頭「{header}」如實說明請求的來源,由閘道器傳送,不能在配置中設定。", + "config.credential.too_many_headers": "請求頭最多 {max} 個。", + "config.credential.bad_header_name": "請求頭名稱「{header}」無效:只能包含字母、數字和 - _ . ~,且不超過 {max} 個字元。", + "config.credential.reserved_header": "請求頭「{header}」由閘道器管理,不能在配置中設定。", + "config.credential.duplicate_header": "請求頭「{header}」重複(請求頭名稱不區分大小寫)。", + "config.credential.bad_header_value": "請求頭「{header}」的值不能包含換行,且不超過 {max} 個字元。", + "config.credential.unrecognized_placeholder": "請求頭「{header}」中的 {placeholder} 無法識別,只支援 {{{{access_token}}}}。", + "config.credential.token_without_oauth": "請求頭「{header}」使用了 {{{{access_token}}}},但該上游未配置 oauth。", + "config.credential.key_and_auth_header": "已填寫 key,API 金鑰會透過請求頭「{header}」傳送,不能再在請求頭中設定「{header}」。", + "config.credential.oauth_and_auth_header": "配置 oauth 後,令牌預設透過請求頭「{header}」傳送。如需自行設定該請求頭,請用 {{{{access_token}}}} 標明令牌的位置。", + "config.credential.no_token": "無法獲取 OAuth 訪問令牌。", + "config.credential.bedrock_oauth": "Bedrock 上游使用 Bedrock API 金鑰(key)或 AWS 訪問金鑰(aws),不支援 oauth。", + "config.credential.key_and_aws": "key 和 aws 只能填寫其中一項:Bedrock API 金鑰,或 AWS 訪問金鑰。", + "config.credential.bedrock_no_credential": "Bedrock 上游需要 Bedrock API 金鑰(key)或 AWS 訪問金鑰(aws)。", + "config.credential.aws_not_bedrock": "aws(AWS 訪問金鑰)只適用於 Bedrock 上游。", + "config.credential.aws_empty": "訪問金鑰 ID、私有訪問金鑰,以及填寫了的會話令牌都不能為空。", + "config.credential.aws_profile_and_keys": "aws.profile 和訪問金鑰只能填寫其中一項:從 AWS profile 讀取金鑰,或者在這裡寫明金鑰。", + "config.credential.aws_empty_profile": "aws.profile 沒有寫 profile 名稱,請填寫名稱,例如 default。", + "config.credential.aws_signed_header": "發往此上游的請求用 AWS 訪問金鑰簽名,簽名會設定請求頭「{header}」,不能再在請求頭中設定它。", + "config.credential.aws_no_region": "介面地址不是標準的 Bedrock 地址(https://bedrock-runtime.<區域>.amazonaws.com),需要在 aws.region 中寫明簽名用的區域。", + "config.credential.aws_bad_region": "「{region}」不是 AWS 區域程式碼(例如 us-east-1)。", + "config.credential.aws_region_mismatch": "aws.region 是 {given},介面地址所在的區域是 {host}。區域取自介面地址,aws.region 可以不填。", + "// ── config.aws_profile:从 AWS 凭证文件读访问密钥 ─────────────────": "", + "config.aws_profile.no_home": "無法確定使用者主目錄,找不到 AWS 憑證檔案。請設定 AWS_SHARED_CREDENTIALS_FILE 和 AWS_CONFIG_FILE。", + "config.aws_profile.unreadable": "無法讀取 {path}:{detail}", + "config.aws_profile.not_found": "{credentials} 和 {config} 中都沒有 AWS profile「{profile}」。", + "config.aws_profile.unsupported": "AWS profile「{profile}」透過 {setting} 獲取憑證,ThinkWatch 不會執行它,只讀取 profile 中寫明的訪問金鑰。", + "config.aws_profile.no_keys": "AWS profile「{profile}」中沒有訪問金鑰:需要 aws_access_key_id 和 aws_secret_access_key 兩項。", + "// ── config.secret:凭据里的 ${环境变量} ──────────────────────────": "", + "config.secret.env_missing": "未設定環境變數 {var}。", + "config.secret.unterminated": "第 {pos} 個字元處的 ${{...}} 沒有閉合。", + "config.secret.empty_name": "變數名為空:${{}}", + "// ── config.rotate:把换发的凭据写回配置 ─────────────────────────": "", + "config.rotate.no_provider": "配置中已沒有上游「{provider}」。", + "config.rotate.read_back_differs": "寫入後讀回的令牌與新令牌不一致。", + "// ── yaml:按字段改配置文件 ───────────────────────────────────────": "", + "yaml.parse": "無法解析 YAML:{detail}", + "yaml.not_found": "配置中找不到 {path}。", + "yaml.not_scalar": "{path} 不是標量,只有標量可以就地修改。", + "yaml.self_check": "修改結果未透過自檢,未寫入任何內容:{detail}", + "yaml.duplicate": "{path} 在配置中出現了多次,修改可能不會生效。請先手動刪除重複項。", + "yaml.block_scalar": "{path} 是多行塊(| 或 >),無法自動修改,請直接編輯配置檔案。", + "yaml.anchor_or_alias": "{path} 位於 YAML 錨點或別名(&x / *x)中,修改會影響所有引用處,請直接編輯配置檔案。", + "// ── engine:路由规则本身的问题 ───────────────────────────────────": "", + "engine.no_match": "沒有規則命中,且沒有兜底規則。請在末尾新增一條不帶條件的規則。", + "engine.phase_two_with_to": "規則「{rule}」同時設定了 provider_would_be 和 to。provider_would_be 要在選定上游之後才能判斷,這類規則只能使用 set 或 deny。", + "engine.no_action": "規則「{rule}」沒有設定 to、deny 或 set,命中後不起作用。", + "engine.unknown_target": "規則「{rule}」指向的「{target}」既不是上游也不是策略組。", + "engine.empty_group": "策略組「{group}」中沒有上游。", + "engine.duplicate_group": "策略組名稱「{group}」重複。規則按名稱引用策略組,名稱必須唯一。", + "engine.group_upstream_twice": "策略組「{group}」中上游「{upstream}」出現了不止一次。每個上游在策略組中只能出現一次。", + "engine.group_unknown_upstream": "策略組「{group}」列出的「{upstream}」不是上游。策略組的成員須為上游的名稱。", + "engine.time_syntax": "時段條件「{value}」寫法不對:應寫成「[星期 ]HH:MM-HH:MM」,星期為 mon、tue、wed、thu、fri、sat、sun 或 mon-fri 這樣的範圍,時間在 00:00 到 24:00 之間,例如「mon-fri 09:00-18:00」。", + "engine.rule_time_syntax": "規則「{rule}」的時段條件「{value}」寫法不對:應寫成「[星期 ]HH:MM-HH:MM」,星期為 mon、tue、wed、thu、fri、sat、sun 或 mon-fri 這樣的範圍,時間在 00:00 到 24:00 之間,例如「mon-fri 09:00-18:00」。", + "engine.group_weight_not_load_balance": "策略組「{group}」為上游「{upstream}」設定了權重 {weight},而只有輪詢(load-balance)策略組使用權重。請刪除權重,或將該策略組改為輪詢。", + "engine.group_weight_out_of_range": "策略組「{group}」為上游「{upstream}」設定的權重為 {weight}。權重須為 1 到 100 之間的整數。", + "engine.group_balance_not_load_balance": "策略組「{group}」設定了 balance_by: {balance_by},而只有輪詢(load-balance)策略組使用該項。請刪除該項,或將該策略組改為輪詢。", + "engine.duplicate_route": "路由名稱「{route}」重複。閘道器金鑰按名稱繫結路由,名稱必須唯一。", + "engine.unknown_default_route": "default_route 指向的路由「{route}」不存在,未繫結路由的閘道器金鑰將無法命中任何規則。", + "engine.unknown_route": "閘道器金鑰「{key}」繫結的路由「{route}」不存在。", + "engine.pinned_empty": "規則「{rule}」的指定模型列表為空。請至少列出一個上游和模型,或改為轉發到上游或策略組。", + "engine.pinned_unknown_provider": "規則「{rule}」指定模型時寫的「{upstream}」不是上游。指定模型須寫上游的名稱,不能寫策略組。", + "engine.pinned_duplicate_provider": "規則「{rule}」的指定模型中,上游「{upstream}」出現了兩次。每個上游在列表中只能出現一次。", + "engine.pinned_blank_model": "規則「{rule}」為上游「{upstream}」指定的模型名稱為空。", + "engine.pinned_with_provider_would_be": "規則「{rule}」同時設定了指定模型和 provider_would_be。provider_would_be 要在選定上游之後才能判斷,而指定模型本身已經選定了上游。", + "engine.pinned_with_set_model": "規則「{rule}」同時設定了指定模型和 set.model。指定的模型名會原樣發出,set.model 不起作用,請刪除其中一項。", + "// 比较式写错。在路由编辑对话框里多带一个 `rule`(是哪条规则)": "", + "engine.compare.empty": "{?rule:規則「{rule}」:}條件 {field} 寫法有誤:比較式為空。", + "engine.compare.no_operator": "{?rule:規則「{rule}」:}條件 {field} 寫法有誤:「{value}」缺少比較符,應以 > < >= <= = 之一開頭,例如 \">200k\"。", + "engine.compare.bad_number": "{?rule:規則「{rule}」:}條件 {field} 寫法有誤:無法解析「{value}」中的數字。", + "engine.compare.bad_unit": "{?rule:規則「{rule}」:}條件 {field} 寫法有誤:無法識別「{value}」中的單位。支援 k(千)和 m(百萬),金額寫成 $2.5 的形式。", + "// ── pricing.sheet:价目表的写法 ──────────────────────────────────": "", + "pricing.sheet.empty_name": "價目表沒有名稱。", + "pricing.sheet.padded_name": "價目表名稱「{sheet}」首尾不能包含空白。", + "pricing.sheet.duplicate_name": "價目表名稱「{sheet}」重複。", + "pricing.sheet.bad_multiplier": "價目表「{sheet}」的倍率 {value} 無效,倍率須大於 0。", + "pricing.sheet.empty_model": "價目表「{sheet}」中有模型沒有名稱。", + "pricing.sheet.bad_price": "價目表「{sheet}」中模型 {model} 的{field:price_field}為 {value},價格不能為負數。", + "pricing.sheet.half_long_context": "價目表「{sheet}」中的模型 {model} 需要同時填寫長上下文輸入價格和輸出價格,或者都不填。", + "// ── scan:静态扫描发现了什么 ────────────────────────────────────": "", + "// 句子由「哪一类文件」和「命中了什么」两个词拼出来,两张词表在上面。": "", + "// 词表里没有那个词就整句退回英文 —— 用户自定义的规则走的正是这条路。": "", + "scan.hidden": "{kind:source_in}含有{what:hidden_name}", + "scan.hidden.detail": "{what:hidden_why}{kind:source_why}", + "scan.hidden.not_all_checked": "{kind:source_in}的隱藏字元未全部檢查", + "scan.hidden.not_all_checked.detail": "隱藏字元太多,無法逐一列出:已列出前 {count} 處,從第 {line} 行起未再檢查。", + "scan.mcp.remote": "MCP server「{name}」位於遠端", + "scan.mcp.remote.detail": "該 server 的地址為 {url},使用時相關上下文會傳送到該伺服器。", + "scan.rule": "{kind:source_in}命中規則「{rule:scan_rule}」", + "scan.rule.detail": "{rule:rule_why}。{kind:source_why}", + "scan.skill.all_tools": "skill「{name}」宣告瞭 allowed-tools: [\"*\"]", + "scan.skill.all_tools.detail": "該 skill 可以使用任何工具。這可能是正常需要,建議確認是否確實需要此許可權。", + "// ── adopt.cost:接管这个客户端要付出什么 ────────────────────────": "", + "adopt.cost.claude_code.remote_control": "介面地址不是官方域名時,Remote Control 和語音輸入不可用。", + "adopt.cost.claude_code.mcp_tool_search": "MCP tool search 將預設關閉。", + "adopt.cost.claude_code.welcome_screen": "Claude Code 可能會顯示一次歡迎頁,關閉即可。", + "adopt.cost.codex.chatgpt_desktop": "ChatGPT 桌面版讀取同一份配置檔案,其本地 Codex 會話也會一併接管,重新啟動該應用後生效。", + "adopt.cost.codex.account_features": "接管期間,ChatGPT 桌面版中依賴 ChatGPT 帳號的 Codex 功能不可用,例如工作瀏覽器。", + "adopt.cost.codex.reopen_terminal": "修改後需要重新開啟終端。", + "adopt.cost.codex.sessions_split": "接管前後的會話分開顯示。", + "adopt.cost.codex.resume_through_gateway": "要透過閘道器繼續之前的會話,執行 codex resume <會話 ID> -c model_provider=thinkwatch。", + "adopt.cost.codex.sessions_after_restore": "還原後,接管期間的會話仍可直接開啟,此時直連 OpenAI。", + "adopt.cost.opencode.restart": "修改後需要重新啟動 opencode。", + "adopt.cost.zed.key_store": "Zed 的金鑰不儲存在配置檔案中,需要在 Zed 的設定介面中手動填寫一次。", + "adopt.cost.aider.lookup_order": "Aider 依次讀取主目錄、Git 專案根目錄和當前目錄中的配置,後讀取的會覆蓋先讀取的,接管只修改主目錄中的配置。", + "adopt.cost.aider.restart": "修改後需要重新啟動 Aider。", + "adopt.cost.dsh.every_entry": "網頁版、桌面版和 headless 模式都會經過閘道器,無需重新啟動。", + "adopt.cost.dsh.account_direct": "桌面版中透過 DeepSeek 帳號登入使用的模型直接連線 api.deepseek.com,不經過閘道器。", + "adopt.cost.dsh.web_search": "聯網搜尋仍直接連線 DeepSeek,不經過閘道器。", + "adopt.cost.dsh.settings_page": "接管期間,無法在 DeepSeek Harness 的設定頁中修改 llm-deepseek 這一項配置。", + "adopt.cost.dsh.models": "DeepSeek Harness 請求的模型為 deepseek-flash、deepseek-v4-pro 和 deepseek-v4-flash,需要在路由中將這些模型名交給 DeepSeek 上游,或改寫為其他上游的模型。", + "adopt.cost.pi.default_model": "預設模型保持不變;ThinkWatch 的模型在 /model 中選擇,按 Ctrl+S 可設為預設模型。", + "adopt.cost.omp.default_model": "預設模型保持不變;ThinkWatch 的模型在 /model 中選擇,指定為 default 角色後即為預設模型。", + "adopt.cost.claude_desktop.restart": "修改後需要完全退出 Claude Desktop 再重新開啟。", + "adopt.cost.claude_desktop.sign_in": "開啟時如出現登入頁,在登入頁選擇透過閘道器繼續,只需一次。", + "adopt.cost.claude_desktop.separate_history": "該模式下的對話與原有對話分開儲存。", + "adopt.cost.claude_desktop.web_search": "聯網搜尋不經過閘道器,需要另外配置。", + "adopt.cost.grok_build.builtin_models": "Grok 的內建模型仍留在模型列表中,選用時直接連線 xAI;閘道器的模型以 thinkwatch/<模型名> 列出。", + "adopt.cost.grok_build.helper_models": "聯網搜尋、圖片描述、會話標題與輸入建議仍使用 Grok 的內建模型,直接連線 xAI。", + "adopt.cost.grok_build.campaigns": "接管期間關閉 Grok 的遠端活動推送(campaigns),這類推送可能更改預設模型。", + "adopt.cost.qwen_code.restart": "修改後需要重新啟動 Qwen Code。", + "adopt.cost.qwen_code.version": "需要 Qwen Code 0.19.3 或更高版本,更早的版本不會讀取閘道器的模型。", + "adopt.cost.qwen_code.other_models": "為快速回復、視覺、上下文壓縮等任務單獨設定的模型仍使用各自的提供方。", + "adopt.cost.qwen_code.proxy": "Qwen Code 使用代理時,需將閘道器地址加入 NO_PROXY,否則發往閘道器的請求也會經過代理。", + "adopt.cost.hermes_agent.restart": "已開啟的 Hermes Agent 會話在重新啟動前仍使用原來的提供方;訊息閘道器從下一條訊息起使用新配置。", + "// ── adopt.diag:接管为什么没生效 ────────────────────────────────": "", + "adopt.diag.not_running": "{client} 當前未執行", + "adopt.diag.not_running.detail": "下次啟動時將讀取新配置。", + "adopt.diag.started_before": "{client} 的程序啟動於接管之前", + "adopt.diag.started_before.detail": "有 {count} 個程序在接管之前啟動,仍在使用舊配置。{takes_effect:takes_effect}", + "adopt.diag.restart": "退出 {client} 後重新開啟", + "adopt.diag.wsl_process": "無法從 Windows 判斷 {client} 是否已重新啟動", + "adopt.diag.wsl_process.detail": "該用戶端執行在 WSL 中,其程序在此處不可見。接管之前啟動的程序仍在使用舊配置。{takes_effect:takes_effect}", + "adopt.diag.process_unknown": "無法判斷 {client} 是否已重新啟動", + "adopt.diag.process_unknown.detail": "其程序無法與其他程式區分。接管之前啟動的程序仍在使用舊配置。{takes_effect:takes_effect}", + "adopt.diag.started_after": "{client} 在接管之後啟動", + "adopt.diag.started_after.detail": "已讀取新配置。", + "adopt.diag.reloads": "{client} 會自行重新讀取配置", + "adopt.diag.reloads.detail": "正在執行的程序無需重新啟動即可使用新配置。", + "adopt.diag.not_adopted": "尚未接管該用戶端", + "adopt.diag.not_adopted.detail": "{path} 中沒有接管記錄。", + "adopt.diag.no_shadow": "沒有優先順序更高的配置檔案", + "adopt.diag.no_shadow.none": "該用戶端沒有優先順序更高的配置檔案。", + "adopt.diag.no_shadow.absent": "{files} 不存在。", + "adopt.diag.no_shadow.unset": "{files} 存在,但未設定此處寫入的欄位。", + "adopt.diag.shadowed": "{path} 的優先順序高於接管寫入的配置", + "adopt.diag.shadowed.no_fields": "該檔案存在,但不包含相關欄位。", + "adopt.diag.shadowed.fields": "該檔案中包含 {fields},會覆蓋接管寫入的設定。", + "adopt.diag.shadowed.whole_file": "該檔案存在時,{client} 只讀取該檔案,接管寫入的配置不會被讀取。", + "adopt.diag.hermes_agent.active_profile": "Hermes Agent 已設為使用 profile {profile}", + "adopt.diag.hermes_agent.active_profile.detail": "{path} 指定了 profile {profile},因此不帶 -p 啟動的 Hermes Agent 讀取的是該 profile 的配置,而不是接管寫入的這一份。", + "adopt.diag.hermes_agent.use_default": "hermes profile use default", + "adopt.diag.look_at_fields": "檢查 {path} 中的相關欄位", + "adopt.diag.project_config": "當前專案中有同名配置檔案", + "adopt.diag.project_config.detail": "{path} 會覆蓋使用者級配置。", + "adopt.diag.look_at": "檢查 {path}", + "adopt.diag.managed": "本機存在管理策略檔案", + "adopt.diag.managed.detail": "{path} 的優先順序高於其他所有配置,包括使用者配置。", + "adopt.diag.managed_dropin": "本機存在管理策略補充檔案", + "adopt.diag.managed_dropin.detail": "{path} 在 managed-settings.json 之後合併,與它一樣優先於其他所有配置,包括使用者配置。", + "adopt.diag.no_managed": "本機沒有管理策略檔案", + "adopt.diag.no_managed.detail": "不存在優先順序高於其他所有配置的管理策略檔案。", + "adopt.diag.claude_desktop.managed": "這臺電腦的 Claude Desktop 由組織統一管理", + "adopt.diag.claude_desktop.managed.detail": "{by} 中的託管配置優先,本機配置不會生效。", + "adopt.diag.claude_desktop.not_applied": "Claude Desktop 中正在使用的是另一份配置", + "adopt.diag.claude_desktop.not_applied.detail": "{path} 中的 appliedId 已不再指向 ThinkWatch 的配置。", + "adopt.diag.claude_desktop.mode": "Claude Desktop 可能仍以原有模式啟動", + "adopt.diag.claude_desktop.mode.detail": "{paths} 中的 deploymentMode 不是 3p。在登入頁選擇透過閘道器繼續即可。", + "adopt.diag.no_exports": "shell 配置中沒有同名環境變數", + "adopt.diag.no_exports.detail": "已檢查 .zshrc、.zprofile、.bashrc 等檔案。", + "adopt.diag.shell_export": "{path} 第 {line} 行匯出了 {name}", + "adopt.diag.shell_export.harmless": "不影響 {client}(其配置檔案優先順序更高),但會影響讀取環境變數的其他用戶端。", + "adopt.diag.shell_export.overrides": "{client} 讀取環境變數,該行會覆蓋接管寫入的配置。", + "// 一条命令,两种语言里是同一串字符": "", + "adopt.diag.delete_line": "sed -i '' '{line}d' {path}", + "adopt.diag.delete_line_gnu": "sed -i '{line}d' {path}", + "// Windows 上同名变量在注册表里:没有文件,也没有行号": "", + "adopt.diag.registry_env": "登錄檔 {key} 中設定了 {name}", + "adopt.diag.registry_env.overrides": "{client} 讀取環境變數,該變數會覆蓋接管寫入的配置。", + "adopt.diag.no_registry_env": "沒有同名的環境變數", + "adopt.diag.no_registry_env.detail": "已檢查使用者和系統兩級環境變數。", + "adopt.diag.unset_env": "reg delete \"{root}\\{key}\" /v {name} /f(執行後重新開啟終端)", + "adopt.diag.unset_env_machine": "reg delete \"{root}\\{key}\" /v {name} /f(需要以管理員身份開啟終端)", + "adopt.diag.fields_gone": "接管寫入的欄位已不在配置中", + "adopt.diag.fields_gone.detail": "{path} 中未找到接管寫入的介面地址,可能已被其他工具修改。", + "adopt.diag.adopt_again": "重新接管該用戶端", + "adopt.diag.endpoint_ok": "配置中的介面地址與接管時一致", + "adopt.diag.endpoint_ok.detail": "當前指向 {endpoint}。", + "adopt.diag.cloud": "{client} 設定為直連 {cloud:cloud}", + "adopt.diag.cloud.settings": "{path} 中的 {name} 處於開啟狀態,{client} 因此不讀取 ANTHROPIC_BASE_URL,請求不會到達閘道器。", + "adopt.diag.cloud.shell": "{path} 第 {line} 行匯出了 {name},接管寫入的配置沒有關閉它,{client} 因此不讀取 ANTHROPIC_BASE_URL,請求不會到達閘道器。", + "adopt.diag.cloud.env": "環境變數中設定了 {name},接管寫入的配置沒有關閉它,{client} 因此不讀取 ANTHROPIC_BASE_URL,請求不會到達閘道器。", + "adopt.diag.cloud.above": "{path} 開啟了 {name},其優先順序高於接管寫入的配置,在該目錄中啟動的 {client} 的請求不會到達閘道器。", + "adopt.diag.cloud.managed": "{path} 是組織統一管理的配置,其中開啟了 {name},{client} 的請求不會到達閘道器。", + "adopt.diag.no_cloud": "{client} 沒有設定為直連雲服務商", + "adopt.diag.no_cloud.detail": "CLAUDE_CODE_USE_* 系列開關均未開啟。", + "adopt.diag.static_only": "以上均為靜態檢查", + "adopt.diag.static_only.detail": "靜態檢查無法確認配置已實際生效。收到該用戶端的真實請求後,才能確認接管已生效。", + "// ── adopt.manual:手动配置的步骤 ────────────────────────────────": "", + "// 地址和密钥不在句子里:界面各给一个复制按钮,句子只说填到哪儿": "", + "adopt.manual.file": "開啟 {file},寫入下面幾項。", + "adopt.path.fixed": "{client} 的配置檔案位置不能更改。", + "adopt.path.adopted": "{client} 已接管,需先還原才能更改路徑。", + "adopt.other_instance": "{client} 由另一個 ThinkWatch Lite 接管,需在接管它的 ThinkWatch Lite 中還原。", + "adopt.path.not_absolute": "{path} 不是完整路徑。", + "adopt.path.folder": "{path} 是一個資料夾,需填寫配置檔案的路徑。", + "adopt.path.no_folder": "資料夾 {folder} 不存在。", + "adopt.path.format": "{client} 的配置檔案是 {ext} 檔案。", + "adopt.path.not_folder": "{path} 不是資料夾。", + "adopt.path.unsaved": "位置未能儲存:{detail}", + "adopt.manual.zed.key": "然後在 Zed 的設定中,為 ThinkWatch 填入金鑰。", + "adopt.manual.also_file": "金鑰寫入 {file};下面以 refs 或 version 開頭的幾項屬於該檔案。", + "adopt.manual.cursor.open": "在 Cursor 中開啟 Settings → Models。", + "adopt.manual.cursor.base": "開啟 Override OpenAI Base URL,填入閘道器地址。", + "adopt.manual.cursor.key": "在 OpenAI API Key 中填入金鑰,然後點選 Verify。", + "adopt.manual.cursor.caveat": "Tab 補全與 inline edit 仍由 Cursor 自身的服務處理,不經過閘道器,因此只能部分接管。", + "adopt.manual.continue.open": "開啟 ~/.continue/config.yaml。", + "adopt.manual.continue.open_windows": "開啟 %USERPROFILE%\\.continue\\config.yaml。", + "adopt.manual.continue.entry": "在 models 列表中新增一項:provider 設為 openai,apiBase 設為閘道器地址,apiKey 設為金鑰。", + "adopt.manual.continue.caveat": "接入需要在 models 列表中新增條目,不提供自動接管,請按上述步驟手動配置。", + "adopt.manual.antigravity_cli.export": "在 shell 配置檔案中匯出 GOOGLE_GEMINI_BASE_URL(閘道器地址)和 GEMINI_API_KEY(金鑰)。", + "// Windows 上没有 shell 配置文件可 export,用户级环境变量用 setx 写": "", + "adopt.manual.antigravity_cli.setx": "在終端中執行 setx GOOGLE_GEMINI_BASE_URL,後接閘道器地址;再執行 setx GEMINI_API_KEY,後接金鑰。", + "adopt.manual.antigravity_cli.provider": "在 ~/.gemini/antigravity-cli/settings.json 中加入 \"modelProvider\": \"gemini\"。", + "adopt.manual.antigravity_cli.provider_windows": "在 %USERPROFILE%\\.gemini\\antigravity-cli\\settings.json 中加入 \"modelProvider\": \"gemini\"。", + "adopt.manual.antigravity_cli.reopen": "然後重新開啟終端。", + "adopt.manual.antigravity_cli.caveat": "設定後,agy 不再使用 Google 帳號的額度。agy 發出的模型名均為 Gemini 模型,如需使用其他服務商的模型,須在路由中按模型名改寫。", + "// ── wsl:WSL 里的客户端 ─────────────────────────────────────────": "", + "wsl.unreadable": "無法讀取 WSL · {distro}:{detail}", + "wsl.no_user": "WSL · {distro} 的 /etc/passwd 中沒有 ID 為 {uid} 的使用者。", + "wsl.unknown": "沒有名為 {distro} 的 WSL 發行版。", + "wsl.via_windows": "WSL · {distro} 中的 {client} 經由 Windows 上的閘道器傳送請求。", + "wsl.none": "這臺電腦上沒有 WSL 發行版。", + "wsl.shutdown_failed": "未能停止 WSL:{detail}", + "wslconfig.encoding": "{path} 既不是 UTF-8 也不是 UTF-16 文字,未作修改。可手動在其中的 [wsl2] 段設定 networkingMode=mirrored。", + "adopt.manual.claude_desktop.open": "在 Claude Desktop 中依次開啟 Help → Troubleshooting → Enable Developer Mode,然後開啟 Developer → Configure Third-Party Inference。", + "adopt.manual.claude_desktop.fields": "選擇閘道器作為提供方,填入閘道器地址和金鑰,鑑權方式設為 x-api-key。", + "adopt.manual.claude_desktop.apply": "點選 Apply Changes,然後完全退出 Claude Desktop 再重新開啟。", + "// ── adopt.mcp:这份 MCP 配置为什么写不了 ────────────────────────": "", + "adopt.mcp.unverified_format": "該用戶端的 MCP 配置格式尚未驗證,寫入可能導致用戶端無法讀取配置", + "adopt.mcp.zed_structure": "Zed 的 context server 使用不同的配置結構,不支援 command/args 形式", + "adopt.mcp.dsh_rows": "DeepSeek Harness 的每個 MCP server 是補丁檔案中的一行外掛配置,此處只列出,不寫入", + "adopt.mcp.toml_null": "{field} 的值為 null,而 {client} 的 MCP 配置是 TOML,沒有 null 的寫法,未做任何修改", + "// ── adopt:接管和还原的说明 ─────────────────────────────────────": "", + "adopt.takes_effect": "{takes_effect:takes_effect}", + "adopt.plan.fields_only": "欄位名已查證,尚未在本機實際執行驗證。收到第一個請求之前,請勿視為已生效。", + "adopt.plan.codex.detail_mode": "接管期間,ChatGPT 桌面版中的 Codex 按預設方式顯示對話詳情,還原時恢復原來的設定。", + "adopt.plan.no_models": "閘道器目前沒有該金鑰可用的模型,{client} 中不會出現 ThinkWatch 的模型。有可用模型後,請在用戶端頁更新模型列表。", + "adopt.plan.no_models_nothing_written": "閘道器目前沒有該金鑰可用的模型,不會對 {client} 做任何修改。有可用模型後,請重新接管。", + "adopt.plan.hermes_agent.other_profiles": "只修改預設 profile;{profiles} 保留各自的配置。", + "adopt.plan.hermes_agent.active_profile": "當前使用的 profile 是 {profile},因此不帶 -p 啟動的 Hermes Agent 讀取該 profile 的配置,而不是此處修改的預設配置。", + "adopt.plan.shadowed": "檢測到 {paths},其優先順序高於接管寫入的配置,其中的同名設定會覆蓋接管的設定。", + "adopt.plan.shadowed.whole_file": "檢測到 {paths},{client} 只讀取該檔案,接管寫入的配置不會生效。", + "adopt.plan.pi.proxy_env": "已設定 {name},而 NO_PROXY 中沒有 {host},Pi 訪問閘道器的請求會經過該代理。將 {host} 加入 NO_PROXY 後改為直接連線。", + "adopt.plan.pi.proxy_setting": "{path} 中設定了 httpProxy,而 NO_PROXY 中沒有 {host},Pi 訪問閘道器的請求會經過該代理。將 {host} 加入 NO_PROXY 後改為直接連線。", + "adopt.plan.cloud_off.settings": "{path} 開啟了 {name},{client} 因此直連 {cloud:cloud}。接管期間關閉這個開關,還原時重新開啟。", + "adopt.plan.cloud_off.shell": "{path} 第 {line} 行匯出了 {name},{client} 因此直連 {cloud:cloud}。接管期間關閉這個開關,還原時重新開啟。", + "adopt.plan.cloud_off.env": "環境變數中設定了 {name},{client} 因此直連 {cloud:cloud}。接管期間關閉這個開關,還原時重新開啟。", + "adopt.plan.cloud_above": "{path} 開啟了 {name},其優先順序高於接管寫入的配置:在該目錄中啟動的 {client} 仍會直連 {cloud:cloud}。", + "adopt.plan.cloud_models": "{names} 中沒有設定 Bedrock 模型:用到這幾類模型時,{client} 會以 Anthropic 的模型名向閘道器請求,需要在路由中新增規則,把這些名字改寫為 Bedrock 上的模型。", + "adopt.plan.bedrock_unusable": "{client} 透過{how:aws_how}獲取 AWS 憑據,閘道器無法使用這種方式:閘道器不執行命令,也不代為登入。新建的上游需要 Bedrock API 金鑰、訪問金鑰,或寫有訪問金鑰的 AWS profile。", + "adopt.plan.bedrock_profile_unusable": "AWS profile {profile} 透過 {setting} 獲取憑據,閘道器不執行這類設定。新建的上游需要 Bedrock API 金鑰、訪問金鑰,或寫有訪問金鑰的 AWS profile。", + "adopt.plan.bedrock_no_credential": "未找到閘道器可用的 {client} AWS 憑據,新建上游時需要填寫憑據。", + "adopt.plan.bedrock_settings_only": "{vars} 只寫在 {path} 中,閘道器無法讀取:閘道器的執行環境中有這個變數後,新建的上游才能使用;也可以在新建上游時直接填寫。", + "adopt.plan.bedrock_unseen": "閘道器的執行環境中沒有 {vars}:環境中有這個變數後,新建的上游才能使用;也可以在新建上游時直接填寫。", + "adopt.plan.bedrock_refresh": "{path} 設定了 awsAuthRefresh,這是 Claude Code 在 AWS 憑據過期時執行的命令。閘道器不執行該命令;AWS 憑證檔案發生變化時,閘道器會重新讀取。", + "adopt.plan.claude_desktop.was_cloud": "Claude Desktop 當前透過配置「{name}」使用 {cloud:cloud}。接管期間改用 ThinkWatch 的配置,還原時切回「{name}」。", + "adopt.plan.claude_desktop.bedrock_key": "Claude Desktop 的 Bedrock API 金鑰儲存在 {path} 中,閘道器無法讀取。新建的上游從環境變數 AWS_BEARER_TOKEN_BEDROCK 讀取金鑰,需要閘道器的執行環境中有這個變數;也可以在新建上游時直接填寫金鑰。", + "adopt.plan.claude_desktop.aws_dir": "Claude Desktop 從 {dir} 讀取 AWS profile {profile},而閘道器讀取 ~/.aws 中的憑證檔案(除非 AWS_SHARED_CREDENTIALS_FILE 和 AWS_CONFIG_FILE 指定了其他檔案)。", + "adopt.plan.claude_desktop.rule_name_taken": "路由「{route}」中已有名為「{rule}」的規則,且不是接管 Claude Desktop 時新增的。在路由頁重新命名或刪除該規則後,重新接管。", + "adopt.claude_desktop.rule_left": "Claude Desktop 已還原,但路由「{route}」中的規則「{rule}」未能刪除({detail})。請在路由頁刪除該規則。", + "adopt.claude_desktop.rule_unchecked": "Claude Desktop 已還原,但無法請閘道器刪除接管時新增的路由規則「{rule}」({detail})。如該規則仍在,請在路由頁刪除。", + "adopt.claude_desktop.rule_not_reverted": "為 Claude Desktop 新增到路由「{route}」的規則「{rule}」仍然存在:Claude Desktop 未能接管({detail}),該規則也未能撤回({reason})。請在路由頁刪除該規則。", + "adopt.restore.config_gone": "配置檔案已不存在,僅刪除接管記錄。", + "adopt.restore.secret_lost": "{field} 的原值是金鑰,僅儲存在全文備份中,而 {backup} 已不存在。該欄位已刪除,需要手動重新填寫。", + "adopt.restore.file_removed": "該檔案在接管時新建,還原後內容為空,已一併刪除。", + "adopt.restore.cloud_on": "{name} 將重新開啟,{client} 會再次直連 {cloud:cloud}。", + "adopt.restore.cloud_env": "該檔案中的 {name} 將被移除,{client} 是否直連 {cloud:cloud} 重新由環境變數決定。", + "adopt.warn.symlink": "{path} 是符號連結,實際寫入的檔案為 {real}。", + "adopt.warn.symlink_dir": "{dir} 是符號連結,{path} 實際寫入的位置為 {real}。", + "adopt.warn.world_readable": "{path} 的許可權為 {mode},本機其他使用者可以讀取寫入的金鑰。可執行 chmod 600 {path} 收緊許可權。", + "adopt.warn.wsl_private": "{path} 是從 Windows 一側新建的,WSL 中的其他使用者可能讀得到寫入的金鑰。可在 WSL 中執行 chmod 600 {path} 收緊許可權。", + "// ── adopt:接管、还原、搬 MCP 时的失败 ──────────────────────────": "", + "adopt.file.read_failed": "無法讀取 {path}:{detail}", + "adopt.file.write_failed": "無法寫入 {path}:{detail}", + "adopt.file.changed": "{path} 在確認之後被修改,未寫入任何內容。請重新檢視改動。", + "adopt.file.verify_failed": "修改後的內容未透過校驗,未寫入任何內容({detail})。", + "adopt.file.readback_mismatch": "寫入後讀回的內容與預期不符,已從備份還原:{path}", + "adopt.file.link_loop": "符號連結層數過多:{path}", + "adopt.file.not_restored": "寫入中途停止,且無法將 {path} 恢復原樣:{detail}。原來的內容儲存在 {backup}", + "adopt.file.not_removed": "寫入中途停止,且無法刪除此次新建的 {path}:{detail}", + "adopt.plan.read_failed": "無法讀取 {client} 的配置 {path}:{detail}", + "adopt.plan.parse_failed": "無法解析 {client} 的配置,未做任何修改:{detail}", + "adopt.plan.foreign_record": "{path} 旁的接管記錄屬於 {other},而不是 {client},未做任何修改。", + "adopt.plan.no_record": "沒有 {client} 的接管記錄,無法還原。如需手動還原,請檢視 {path}。", + "adopt.plan.managed": "這臺電腦的 {client} 由組織統一管理({by}),無法接管,未做任何修改。", + "adopt.plan.cloud_managed": "{path} 是組織統一管理的配置,其中開啟了 {name},{client} 會直連 {cloud:cloud},無法接管,未做任何修改。", + "adopt.plan.stale": "{client} 的配置在檢視改動期間已被修改,未寫入任何內容。請重新檢視改動。", + "adopt.plan.gateway_changed": "閘道器為 {client} 提供的模型在檢視改動期間發生了變化,未寫入任何內容。請重新檢視改動。", + "adopt.mcp.unknown_client": "未知的用戶端「{client}」。", + "adopt.mcp.parse_failed": "無法解析 {client} 的 MCP 配置,未做任何修改:{detail}", + "adopt.mcp.not_there": "{client} 中沒有名為「{name}」的 MCP server。", + "adopt.mcp.not_copyable": "{client} 的 MCP 配置格式尚未驗證,不會寫入。", + "// ── sync:多设备同步 ────────────────────────────────────────────": "", + "sync.passphrase_wrong": "同步口令不正確。", + "sync.off": "同步未開啟。", + "sync.already_on": "同步已開啟。使用其他同步位置前,請先停止同步。", + "sync.location_taken": "另一臺裝置剛剛在此位置開啟了同步。請重新測試連線後加入。", + "sync.place_changed": "這是另一個同步位置。請先停止同步,再以新的位置開啟同步。", + "sync.passphrase_short": "同步口令至少需要 {min} 個字元。", + "sync.passphrase_changed": "同步口令已在其他裝置上更改,請輸入新口令。", + "sync.locked_new": "同步位置已啟用加密,輸入同步口令後繼續同步。", + "sync.not_encrypted": "同步位置未加密。", + "sync.too_new": "其他裝置使用較新版本(Core {version}),更新 ThinkWatch Lite 後繼續同步。", + "sync.too_new_unknown": "其他裝置使用較新版本,更新 ThinkWatch Lite 後繼續同步。", + "sync.not_arrived": "最新版本尚未完整到達同步位置。", + "sync.location_empty": "同步位置為空:其中的同步資料已被刪除,或它已不是原來的位置。可重新上傳本機配置,或停止同步。", + "sync.looks_empty": "同步位置似乎為空,將再檢查幾次後再作處理。", + "sync.stale": "同步期間配置已更改,將重新同步。", + "sync.version_gone": "同步位置上已沒有版本 {id}。", + "sync.merge_invalid": "合併後的配置未透過校驗,未應用任何內容。", + "sync.join_undecided": "{item} 在本機與同步資料中不同,請選擇覆蓋、改名匯入或跳過。", + "sync.both_name_taken": "名稱 {name} 已被使用。", + "sync.both_not_allowed": "此衝突無法兩者都保留:其中一方已刪除該物件,或該物件沒有名稱。", + "sync.take_not_allowed": "此衝突無法採用另一方的內容:合併結果將無法透過校驗。", + "sync.proxy_unusable": "代理「{proxy}」無法用於同步位置:{detail}", + "sync.http_client": "無法建立到同步位置的連線:{detail}", + "sync.local": "本機配置無法用於同步:{detail}", + "sync.write_section": "無法寫入同步設定:{detail}", + "sync.prefs_too_large": "同步資料中的通用偏好超過 {limit} KiB,本裝置保留自己的通用偏好,其餘內容已同步。", + "sync.shutting_down": "core 正在退出。", + "sync.keyring_corrupt": "無法讀取同步位置上的同步金鑰。它可能仍在傳送中,或已損壞。", + "sync.keyring_missing": "同步位置上缺少同步金鑰,未同步任何內容。可用本裝置儲存的副本恢復,或停止同步。", + "sync.keyring_rolled_back": "同步位置上的同步金鑰早於本裝置上次讀到的版本,未同步任何內容。可用本裝置儲存的副本恢復,或停止同步。", + "sync.keyring_too_new": "同步位置上的同步金鑰由較新版本寫入。更新 ThinkWatch Lite 後繼續同步。", + "sync.local.io": "無法使用 {path}:{detail}", + "sync.folder.missing": "同步資料夾 {path} 不存在。如在外接硬碟或網路共享上,請先連線。", + "sync.folder.denied": "無法寫入 {path}:{detail}", + "sync.folder.io": "無法使用 {path}:{detail}", + "sync.folder.task": "無法使用同步資料夾:{detail}", + "sync.store.exists": "同步位置上已有 {path}。", + "sync.store.bad_path": "{path} 不是同步位置內的路徑。", + "sync.store.denied": "同步位置拒絕訪問({status})。請檢查使用者名稱、密碼或金鑰。", + "sync.store.server_error": "同步位置對 {what} 返回 {status}。", + "sync.store.unexpected": "同步位置對 {what} 返回 {status}。", + "sync.store.unreachable": "無法連線同步位置:{detail}", + "sync.store.too_large": "同步位置上的 {what} 超過 {limit} MiB,未讀取。", + "sync.s3.sign": "無法為發往 S3 的請求籤名:{detail}", + "sync.s3.bad_listing": "S3 返回的檔案列表無法讀取。", + "sync.webdav.bad_url": "{url} 不是 WebDAV 地址:{detail}", + "sync.webdav.bad_listing": "WebDAV 伺服器返回的目錄列表無法讀取。", + "sync.webdav.root_missing": "WebDAV 資料夾 {url} 不存在。", + "sync.config.device_id": "sync.device_id 須以至少 8 個小寫十六進位制字元開頭,開啟同步時生成。", + "sync.config.device_name": "sync.device_name 須為 1 到 {max} 個字元,且只佔一行。", + "sync.config.passphrase_missing": "sync.encrypt 已開啟,須填寫 sync.passphrase。", + "sync.config.blank": "sync.target.{field} 不能為空。", + "sync.config.folder_relative": "同步資料夾 {path} 須為絕對路徑。", + "sync.config.address": "sync.target.{field} 為 {url}。同步位置須使用 https:// 地址;http:// 僅限本機和內網。", + "sync.config.bucket": "{bucket} 不是有效的儲存桶名稱,請使用小寫字母、數字、點和連字元。", + "sync.config.prefix": "{prefix} 不是儲存桶內的資料夾:不能以 / 開頭,也不能含 . 或 .. 段。", + "sync.config.unknown_proxy": "同步位置經代理「{proxy}」連線,但 proxies 中未定義該代理;內建的選項為 direct 和 system。", + "sync.config.plain_http_proxy": "內網的 http:// 同步位置不能經代理「{proxy}」連線:密碼會以明文經過代理。請使用直連,或改用 https:// 地址。", + "sync.config.blank_exclude": "sync.exclude 中有空的上游名稱。", + "sync.config.multiline": "sync.{field} 須只佔一行。", + "wsl.network_unavailable": "無法識別 WSL · {distro} 可用的 Windows 閘道器地址。請啟動發行版並檢查預設路由;連通性檢測需要 WSL 內安裝 curl 或 python3。", + "wsl.probe_failed": "啟用監聽後,WSL · {distro} 仍無法訪問此閘道器。請檢查 Windows 防火牆和 WSL 網路;用戶端配置尚未更改。", + "wsl.listener_change": "本次接管還會啟用 Windows 閘道器監聽 {address}。保留已有監聽和金鑰校驗;僅在現有規則未放行時新增所需的 WSL 來源。", + "wsl.listener_restore": "同時移除 Lite 新增且已無用戶端需要的監聽和來源規則;獨立修改過的設定會保留。", + "wsl.rollback_failed": "WSL 接管失敗,且因設定已變化或控制面不可用,無法回退監聽:{detail}。請檢查閘道器監聽設定;接管記錄已保留。", + "wsl.stopped": "WSL · {distro} 已停止。啟動發行版後才能檢查閘道器連通性。", + "wsl.listener_cleanup_failed": "用戶端配置已還原,但未能移除閒置的 WSL 監聽或來源規則:{detail}。請檢查閘道器監聽設定;清理記錄已保留。", + "gw.web_tools.failed": "聯網工具:{detail}", + "gw.web_tools.query_mismatch": "搜尋引擎返回的結果與查詢內容不匹配。", + "config.web_tools.invalid": "聯網工具配置無效:{detail}" + } +} diff --git a/src/i18n/core.zh.json b/src/i18n/core.zh.json index 2946dc8d..19837582 100644 --- a/src/i18n/core.zh.json +++ b/src/i18n/core.zh.json @@ -61,29 +61,6 @@ "credential_helper": "凭据脚本", "idp": "经代理的身份提供方登录" }, - "rule_why": { - "ignore-previous": "典型的提示注入开头", - "disregard": "典型的提示注入开头,使用 disregard 一类的动词", - "you-are-now": "试图重新设定模型的身份", - "ignore-previous-zh": "中文提示注入,要求忽略先前的指令", - "new-instructions-zh": "中文提示注入,声明新的指令", - "you-are-now-zh": "试图重新设定模型的身份", - "chat-marker": "伪造对话标记,试图让模型将正文当作系统消息", - "fake-system": "伪装成系统或助手的发言", - "curl-pipe-sh": "下载后直接执行,执行的内容由远端决定且无法预先查看", - "rm-rf-root": "删除整个主目录或根目录", - "chmod-777": "将文件权限设为所有人可写", - "base64-decode-exec": "将要执行的内容隐藏在 base64 编码中", - "exfil-env": "将环境变量(通常包含密钥)发送到外部", - "exfil-credentials": "要求模型将凭据文件的内容发送出去", - "exfil-credentials-reversed": "要求模型将凭据文件的内容发送出去", - "write-startup-item": "写入开机或打开终端时自动执行的位置", - "crontab-install": "安装定时任务,或删除全部现有定时任务", - "ssh-key-read": "读取私钥或云服务凭据", - "secret-to-unknown-host": "将凭据发往既非本机、也不是该凭据服务商的主机", - "thinkwatch-data": "读写 ThinkWatch 的数据目录,其中以明文保存全部上游密钥和这几项防护的设置", - "upload-file-to-host": "将本地文件的内容上传到外部主机" - }, "source_in": { "hooks": "hook 中", "mcp": "MCP server 中", @@ -119,57 +96,6 @@ "inspect_tools": "危险命令", "content": "内容过滤" }, - "scan_rule": { - "ignore-previous": "要求忽略先前的指令", - "disregard": "要求无视系统提示", - "you-are-now": "重新设定模型身份", - "ignore-previous-zh": "要求忽略先前的指令(中文)", - "new-instructions-zh": "声明新的指令(中文)", - "you-are-now-zh": "重新设定模型身份(中文)", - "chat-marker": "伪造对话标记", - "fake-system": "伪装的系统发言", - "curl-pipe-sh": "下载即执行", - "base64-decode-exec": "解码后执行", - "exfil-env": "外发环境变量", - "exfil-credentials": "外发凭据文件", - "exfil-credentials-reversed": "外发凭据文件(动词在前)", - "ssh-key-read": "读取私钥或云凭据", - "write-startup-item": "写入启动项", - "crontab-install": "安装定时任务", - "rm-rf-root": "删除主目录或根目录", - "chmod-777": "开放全部写权限", - "secret-to-unknown-host": "凭据发往陌生主机", - "thinkwatch-data": "读写 ThinkWatch 自己的数据", - "upload-file-to-host": "上传本地文件到外部主机" - }, - "content_rule": { - "unicode-tags": "Unicode 标签字符", - "bidi-controls": "双向控制符", - "zero-width": "零宽字符", - "private-use": "私用区字符", - "ignore-previous-instructions": "要求忽略先前的指令", - "ignore-all-previous": "要求忽略之前的全部内容", - "disregard-your-instructions": "要求无视指令", - "jailbreak": "越狱", - "dan": "DAN", - "developer-mode": "开发者模式", - "you-are-now": "重新设定身份", - "new-persona": "新的人设", - "act-as": "要求扮演角色", - "pretend-to-be": "要求假装身份", - "system-prompt": "索取系统提示词", - "reveal-your-instructions": "要求透露指令", - "what-are-your-rules": "询问规则", - "base64-wall": "长串 Base64", - "zh-ignore-previous": "要求忽略先前的指令(中文)", - "zh-forget-your": "要求忘记指令(中文)", - "zh-do-not-follow": "要求不要遵循(中文)", - "zh-you-are-now": "重新设定身份(中文)", - "zh-role-play": "要求扮演角色(中文)", - "zh-reveal-your": "要求透露指令(中文)", - "zh-system-prompt": "系统提示词(中文)", - "zh-jailbreak": "越狱(中文)" - }, "zai_step": { "authorize_url": "获取授权地址", "wait_authorization": "等待授权", @@ -227,37 +153,62 @@ { "arg": "upstream", "en": "the credential of upstream `{upstream}`", - "zh": "上游「{upstream}」的凭据" + "zh": "上游「{upstream}」的凭据", + "ja": "アップストリーム「{upstream}」の認証情報", + "zh-Hant": "上游「{upstream}」的憑據", + "ko": "업스트림 「{upstream}」의 인증 정보", + "es": "Credenciales del proveedor «{upstream}»" }, { "arg": "upstream", "en": "The credential for upstream `{upstream}` could not be obtained", - "zh": "无法获取上游「{upstream}」的凭据" + "zh": "无法获取上游「{upstream}」的凭据", + "ja": "アップストリーム「{upstream}」の認証情報を取得できませんでした", + "zh-Hant": "無法獲取上游「{upstream}」的憑據", + "ko": "업스트림 「{upstream}」의 인증 정보를 가져올 수 없습니다", + "es": "No se pudieron obtener las credenciales de «{upstream}»" }, { "arg": "proxy", "en": "The password for proxy `{proxy}` could not be read", - "zh": "无法读取代理「{proxy}」的密码" + "zh": "无法读取代理「{proxy}」的密码", + "ja": "プロキシ「{proxy}」のパスワードを読み取れませんでした", + "zh-Hant": "無法讀取代理「{proxy}」的密碼", + "ko": "프록시 「{proxy}」의 비밀번호를 읽을 수 없습니다", + "es": "No se pudo leer la contraseña del proxy «{proxy}»" }, { "arg": "provider", "en": "oauth.refresh of upstream `{provider}` could not be located", - "zh": "找不到上游「{provider}」的 oauth.refresh" + "zh": "找不到上游「{provider}」的 oauth.refresh", + "ja": "アップストリーム「{provider}」の oauth.refresh が見つかりませんでした", + "zh-Hant": "找不到上游「{provider}」的 oauth.refresh", + "ko": "업스트림 「{provider}」의 oauth.refresh를 찾을 수 없습니다", + "es": "No se encontró oauth.refresh en el proveedor «{provider}»" }, { "arg": "provider", "en": "after writing the new credential for upstream `{provider}` the configuration could not be read, so nothing was written", - "zh": "写入上游「{provider}」的新凭据后无法读取配置,未写入任何内容" + "zh": "写入上游「{provider}」的新凭据后无法读取配置,未写入任何内容", + "ja": "アップストリーム「{provider}」の認証情報を更新できませんでした。設定を読み込めなかったため、変更は保存されていません", + "zh-Hant": "寫入上游「{provider}」的新憑據後無法讀取配置,未寫入任何內容", + "ko": "업스트림 「{provider}」의 새 인증 정보를 저장하지 못했습니다", + "es": "No se guardaron las nuevas credenciales del proveedor «{provider}»" }, { "arg": "step", "en": "{step:zai_step_en}", - "zh": "{step:zai_step}时失败" + "zh": "{step:zai_step}时失败", + "zh-Hant": "{step:zai_step}時失敗" }, { "arg": "backend", "en": "The ChatGPT backend could not be reached", - "zh": "无法连接 ChatGPT 后端" + "zh": "无法连接 ChatGPT 后端", + "ja": "ChatGPT のバックエンドに接続できませんでした", + "zh-Hant": "無法連線 ChatGPT 後端", + "ko": "ChatGPT 백엔드에 연결할 수 없습니다", + "es": "No se pudo conectar con el servicio de ChatGPT" } ], "messages": { diff --git a/src/i18n/guard.i18n.ts b/src/i18n/guard.i18n.ts new file mode 100644 index 00000000..38738f25 --- /dev/null +++ b/src/i18n/guard.i18n.ts @@ -0,0 +1,55 @@ +import type { Matcher } from "@/types"; +import CATALOG from "./guard.zh.json"; +import HANT_CATALOG from "./guard.zh-Hant.json"; +import { getLang, type Lang } from "./index"; + +type RuleCopy = { name: string; why?: string; about?: string }; +type GuardCatalog = Record; kinds: Record }>; + +export function guardTables(lang: "zh" | "zh-Hant") { + const catalog = lang === "zh" ? CATALOG : HANT_CATALOG; + return { + scan_rule: Object.fromEntries(Object.entries(catalog.inspect_tools.rules).map(([id, copy]) => [id, copy.name])), + rule_why: Object.fromEntries(Object.entries(catalog.inspect_tools.rules).map(([id, copy]) => [id, copy.why])), + content_rule: Object.fromEntries(Object.entries(catalog.content.rules).map(([id, copy]) => [id, copy.name])), + }; +} + +function guardCopy(guard: string, lang: Lang) { + const catalog: GuardCatalog | undefined = lang === "zh" ? CATALOG : lang === "zh-Hant" ? HANT_CATALOG : undefined; + return catalog && Object.hasOwn(catalog, guard) ? catalog[guard] : undefined; +} + +export function guardKind(guard: string, slug: string): string | undefined { + const kinds = guardCopy(guard, getLang())?.kinds; + return kinds && Object.hasOwn(kinds, slug) ? kinds[slug] : undefined; +} + +/** 前缀、长度和字符类型取实际判据,更新规则时说明跟着变。 */ +function guardAboutZh(m: Matcher, traditional: boolean): string | undefined { + if (m.kind !== "prefix" && m.kind !== "prefixes") return undefined; + const prefixes = m.kind === "prefix" ? [{ ...m, tail: "any" }] : m.prefixes; + const groups = new Map(); + for (const p of prefixes) { + const key = `${p.min_tail}:${p.tail}`; + const unit = traditional + ? p.tail === "hex" ? "十六進位字元" : p.tail === "alnum" ? "英數字元" : "字元" + : p.tail === "hex" ? "十六进制字符" : p.tail === "alnum" ? "字母或数字" : "字符"; + const group = groups.get(key) ?? { prefixes: [], length: p.min_tail, unit }; + group.prefixes.push(`\`${p.prefix}\``); + groups.set(key, group); + } + return [...groups.values()].map(({ prefixes, length, unit }) => + traditional ? `以 ${prefixes.join("、")} 開頭,後面至少有 ${length} 個${unit}` + : `${prefixes.join("、")} 开头,其后至少 ${length} 个${unit}`, + ).join(";") || undefined; +} + +export function guardRuleText(guard: string, id: string, field: keyof RuleCopy, english?: string, matcher?: Matcher): string { + const lang = getLang(); + const rules = guardCopy(guard, lang)?.rules; + const name = rules && Object.hasOwn(rules, id) ? rules[id]?.[field] : undefined; + const translated = (lang === "zh" || lang === "zh-Hant") && field === "about" && english && matcher + ? guardAboutZh(matcher, lang === "zh-Hant") : undefined; + return translated ?? name ?? english ?? ""; +} diff --git a/src/i18n/guard.zh-Hant.json b/src/i18n/guard.zh-Hant.json new file mode 100644 index 00000000..df87fed9 --- /dev/null +++ b/src/i18n/guard.zh-Hant.json @@ -0,0 +1,669 @@ +{ + "redact": { + "rules": { + "age-secret-key": { + "name": "age 私鑰" + }, + "alibaba-access-key-id": { + "name": "阿里雲 AccessKey ID" + }, + "anthropic-api-key": { + "name": "Anthropic API 金鑰" + }, + "artifactory-key": { + "name": "JFrog Artifactory 金鑰" + }, + "atlassian-token": { + "name": "Atlassian API 令牌" + }, + "auth-header-credential": { + "name": "請求頭中的憑據", + "about": "`Authorization`、`X-Api-Key`、`Api-Key`、`X-Goog-Api-Key` 請求頭的值,包括 curl 的 `-H`、HTTP 原文與程式碼中的寫法;只換值" + }, + "aws-access-key-id": { + "name": "AWS 訪問金鑰 ID" + }, + "aws-other-key-id": { + "name": "AWS 其他訪問金鑰 ID" + }, + "aws-temporary-key-id": { + "name": "AWS 臨時訪問金鑰 ID" + }, + "azure-ad-client-secret": { + "name": "Azure AD 用戶端密碼", + "about": "3 個字元、1 位數字與 `Q~`,其後 31 至 34 個字元" + }, + "bank-card": { + "name": "銀行卡號", + "about": "銀聯、Visa、Mastercard、American Express、JCB、Discover、Diners Club 的卡號:號段、位數對得上並透過 Luhn 校驗;公開的測試卡號除外" + }, + "bedrock-api-key": { + "name": "Amazon Bedrock API 金鑰" + }, + "bot-webhook": { + "name": "機器人 Webhook", + "about": "飛書 / Lark、釘釘、企業微信、Slack、Discord、Microsoft Teams 機器人 Webhook 地址中的令牌;只換令牌段" + }, + "br-cpf": { + "name": "巴西 CPF", + "about": "`ddd.ddd.ddd-dd` 寫法的巴西 CPF,兩位校驗碼對得上" + }, + "brevo-key": { + "name": "Brevo API 金鑰" + }, + "cerebras-key": { + "name": "Cerebras API 金鑰" + }, + "clojars-token": { + "name": "Clojars 令牌" + }, + "cloudflare-origin-ca-key": { + "name": "Cloudflare Origin CA 金鑰" + }, + "cn-address": { + "name": "中國大陸詳細地址", + "about": "行政區劃名稱、街道路巷村之一與門牌號(號、棟、單元、室)組成的中國大陸詳細地址;只到區縣的不算" + }, + "cn-landline": { + "name": "中國大陸固定電話", + "about": "`0` 開頭的 2 至 3 位區號加 7 至 8 位號碼,區號有效,須帶括號或連字元(`010-12345678`、`(0755)1234567`)" + }, + "cn-license-plate": { + "name": "中國大陸車牌號", + "about": "省份簡稱、字母與 5 位字母或數字(新能源車為 6 位),不含 I、O" + }, + "cn-mobile-phone": { + "name": "中國大陸手機號", + "about": "中國大陸手機號:`1` 開頭的 11 位數字,第二位為 3 到 9,前後不緊挨其他數字;可帶 `+86`、`0086`、`86-` 字首,可按 3-4-4 以空格或連字元分隔" + }, + "cn-passport": { + "name": "中國護照號", + "about": "`E` 或 `E` 加一個字母開頭、其後 7 至 8 位數字,且前 20 個字元內出現「護照」或「passport」" + }, + "cn-resident-id": { + "name": "居民身份證號", + "about": "18 位居民身份證號(含港澳臺居民居住證、外國人永久居留身份證):地區碼、1900 年以來的出生日期和校驗碼都對得上" + }, + "cn-resident-id-15": { + "name": "15 位舊身份證號", + "about": "15 位舊身份證號:地區碼、6 位出生日期都對得上,其後 3 位順序碼" + }, + "command-line-password": { + "name": "命令列中的口令", + "about": "命令列中的口令:`curl -u 使用者:口令`、`--user`、`mysql -p口令`、`PGPASSWORD=… psql`;只換口令" + }, + "config-assignment": { + "name": "配置檔案中的金鑰賦值", + "about": "`.env`、YAML、TOML、INI、JSON 中變數名以 `SECRET`、`SECRET_KEY`、`PASSWORD`、`PASSWD`、`PWD`、`TOKEN`、`API_KEY`、`APIKEY`、`ACCESS_KEY`、`PRIVATE_KEY`、`CLIENT_SECRET` 結尾(不區分大小寫)、值為至少 8 個字元的字面量的賦值;只換值,表示式、變數引用和佔位寫法不算" + }, + "conn-string-password": { + "name": "連線串列埠令", + "about": "`協議://使用者:口令@主機` 中的口令;只換口令" + }, + "crypto-address": { + "name": "區塊鏈賬戶/擴充套件公鑰", + "about": "EVM 十六進位制地址,經校驗的 Bitcoin/TRON/XRP/Stellar 地址、Bitcoin 隔離見證地址和 BIP32/SLIP-0132 擴充套件公鑰;也覆蓋 Solana 等無校驗和的 32 位元組 Base58 賬戶格式" + }, + "crypto-extended-key": { + "name": "擴充套件私鑰", + "about": "BIP32 / SLIP-0132 擴充套件私鑰:`xprv`、`tprv`、`yprv`、`Yprv`、`zprv`、`Zprv`、`uprv`、`Uprv`、`vprv`、`Vprv`;Base58Check、私鑰標記及 secp256k1 標量均有效" + }, + "crypto-hex-key": { + "name": "裸錢包私鑰/32 位元組雜湊", + "about": "64 位十六進位制串,可帶 `0x` 字首;覆蓋 EVM、TRON 裸私鑰以及格式無法區分的交易雜湊和摘要" + }, + "crypto-keystore": { + "name": "錢包金鑰庫/密文", + "about": "字面量 `keystore` 或 `ciphertext` 欄位,包括 Ethereum V3 加密金鑰材料;作為文字貼上的 JSON 物件也保護,只換值" + }, + "crypto-mnemonic": { + "name": "助記詞", + "about": "連續 12、15、18、21 或 24 個 BIP39 英文或簡體中文詞表中的詞,並透過校驗和;可帶編號,整段" + }, + "crypto-rpc-key": { + "name": "區塊鏈 RPC 地址憑證", + "about": "Infura `/v3/`、Alchemy `/v2/`、QuickNode 令牌路徑及 Helius `api-key` URL 中的 API 憑據;只換憑據部分" + }, + "crypto-secret-field": { + "name": "欄位中的錢包機密", + "about": "按欄位識別私鑰、種子、助記詞、恢復短語、口令、恢復碼和 MPC/備份份額,包括 `pk`、`privateKey`、`PRIVY_WALLET_PRIVATE_KEY` 和中文標籤;只換值,不猜測金鑰長度" + }, + "crypto-solana-key": { + "name": "Solana 金鑰對", + "about": "Base58 編碼或作為文字貼上的 JSON 位元組陣列,含 64 位元組 Ed25519 種子與公鑰;由種子派生的公鑰須一致,排除同長度簽名" + }, + "crypto-stellar-key": { + "name": "Stellar 私密種子", + "about": "Stellar `S` StrKey 種子,版本、32 位元組載荷和 CRC16-XModem 校驗均有效" + }, + "crypto-sui-key": { + "name": "Sui 私鑰", + "about": "`suiprivkey1` Bech32 編碼,校驗和有效,含支援的簽名方案和 32 位元組金鑰" + }, + "crypto-wif-key": { + "name": "WIF 私鑰", + "about": "51 或 52 個字元的 WIF 私鑰:Base58Check 校驗透過,版本位元組對得上" + }, + "crypto-xrp-seed": { + "name": "XRP 賬戶種子", + "about": "XRP 字母表的 Base58Check 賬戶種子,包括 secp256k1 和 Ed25519 版本" + }, + "databricks-token": { + "name": "Databricks 令牌" + }, + "digitalocean-other-token": { + "name": "DigitalOcean 其他令牌" + }, + "digitalocean-token": { + "name": "DigitalOcean 令牌" + }, + "docker-hub-token": { + "name": "Docker Hub 令牌" + }, + "doppler-token": { + "name": "Doppler 令牌" + }, + "email": { + "name": "郵箱地址", + "about": "郵箱地址:`名稱@域名`" + }, + "exchange-credential": { + "name": "交易 API/簽名鑑權憑證", + "about": "SDK/配置欄位或交易請求頭中的 API key、secret、passphrase、簽名 Memo、OTP 和鑑權簽名;覆蓋 Binance、OKX、Bybit、Coinbase、Kraken、KuCoin、Bitget、Gate、MEXC、Gemini、Bitfinex、HTX、BitMart、Phemex、Bitstamp、Polymarket 和 predict.fun;只換值" + }, + "fireworks-key": { + "name": "Fireworks AI API 金鑰" + }, + "flyio-token": { + "name": "Fly.io 令牌" + }, + "geo-coordinates": { + "name": "精確座標", + "about": "成對出現、在取值範圍內、小數不少於 5 位的緯度與經度" + }, + "github-fine-grained-token": { + "name": "GitHub 細粒度令牌" + }, + "github-oauth-token": { + "name": "GitHub OAuth 令牌" + }, + "github-personal-token": { + "name": "GitHub 個人令牌" + }, + "github-refresh-token": { + "name": "GitHub 重新整理令牌" + }, + "github-server-token": { + "name": "GitHub 伺服器令牌" + }, + "github-user-token": { + "name": "GitHub 使用者令牌" + }, + "gitlab-other-token": { + "name": "GitLab 其他令牌" + }, + "gitlab-token": { + "name": "GitLab 令牌" + }, + "google-api-key": { + "name": "Google API 金鑰" + }, + "google-oauth-token": { + "name": "Google OAuth 令牌" + }, + "grafana-token": { + "name": "Grafana 令牌" + }, + "groq-key": { + "name": "Groq API 金鑰" + }, + "heroku-key": { + "name": "Heroku API 金鑰" + }, + "hk-macau-taiwan-id": { + "name": "港澳臺身份證號", + "about": "香港、澳門、臺灣身份證號:香港、臺灣的校驗碼對得上;澳門的須前文寫明證件名稱" + }, + "huggingface-token": { + "name": "Hugging Face 令牌" + }, + "iban": { + "name": "國際銀行帳號(IBAN)", + "about": "國家程式碼、兩位校驗碼與該國規定位數的帳號,MOD 97-10 校驗透過;連寫或四位一組" + }, + "imei": { + "name": "IMEI", + "about": "15 位數字,Luhn 校驗透過,且前 20 個字元內出現「IMEI」" + }, + "in-aadhaar": { + "name": "印度 Aadhaar 號碼", + "about": "12 位數字(可四位一組),首位為 2 至 9,Verhoeff 校驗透過" + }, + "internal-domain": { + "name": "內部域名", + "about": "以 `.local`、`.internal`、`.lan`、`.corp`、`.home.arpa`、`.intranet` 結尾的域名" + }, + "internal-ip": { + "name": "內網地址", + "about": "`10.`、`172.16–31.`、`192.168.`、`100.64–127.` 開頭的地址與 `fc00::/7` 內的 IPv6 地址,不含 127.0.0.1" + }, + "intl-phone": { + "name": "國際電話號碼", + "about": "`+` 開頭,國家碼有效、位數與該國規定一致;可帶空格與連字元" + }, + "jp-my-number": { + "name": "日本個人番號", + "about": "12 位數字,校驗位對得上,且前 20 個字元內出現「マイナンバー」「個人番號」或「My Number」" + }, + "jwt": { + "name": "JWT", + "about": "三段 base64url,首段解碼後含 `\"alg\"`" + }, + "kr-rrn": { + "name": "韓國居民登入號", + "about": "6 位出生日期、`-` 與 7 位數字,日期有效、第 8 位為 1 至 8" + }, + "labeled-account": { + "name": "帶欄位名的銀行帳號", + "about": "欄位名為 `銀行帳號`、`開戶帳號`、`銀行卡號`、`account_number`、`bank_account`、`bank_account_number` 的值,包括 `欄位名: 值`、`\"欄位名\": \"值\"` 與表格表頭的寫法;只換值" + }, + "labeled-address": { + "name": "帶欄位名的住址", + "about": "欄位名為 `住址`、`家庭住址`、`收貨地址`、`聯絡地址`、`home_address`、`shipping_address`、`residential_address`、`address` 的值,包括 `欄位名: 值`、`\"欄位名\": \"值\"` 與表格表頭的寫法;只換值" + }, + "labeled-birth-date": { + "name": "帶欄位名的出生日期", + "about": "欄位名為 `出生日期`、`生日`、`birthday`、`birth_date`、`date_of_birth`、`dob` 的值,包括 `欄位名: 值`、`\"欄位名\": \"值\"` 與表格表頭的寫法;只換值" + }, + "labeled-health": { + "name": "帶欄位名的健康資訊", + "about": "欄位名為 `病歷號`、`住院號`、`診斷`、`病史`、`medical_record_number`、`diagnosis` 的值,包括 `欄位名: 值`、`\"欄位名\": \"值\"` 與表格表頭的寫法;只換值" + }, + "labeled-name": { + "name": "帶欄位名的姓名", + "about": "欄位名為 `姓名`、`真實姓名`、`聯絡人`、`收件人`、`收貨人`、`real_name`、`full_name`、`legal_name`、`first_name`、`last_name`、`given_name`、`family_name`、`name` 的值,包括 `欄位名: 值`、`\"欄位名\": \"值\"` 與表格表頭的寫法;只換值" + }, + "langfuse-secret-key": { + "name": "Langfuse 私密金鑰" + }, + "langsmith-key": { + "name": "LangSmith API 金鑰" + }, + "linear-key": { + "name": "Linear API 金鑰" + }, + "mac-address": { + "name": "MAC 地址", + "about": "6 組兩位十六進位制字元,以 `:` 或 `-` 分隔;全零、廣播與組播地址除外" + }, + "mainland-travel-permit": { + "name": "港澳臺往來內地通行證號", + "about": "港澳居民來往內地通行證(`H` 或 `M` 加 8 位數字)與臺灣居民來往大陸通行證(8 位數字),且前 20 個字元內出現「通行證」「回鄉證」或「臺胞證」" + }, + "minimax-key": { + "name": "MiniMax API 金鑰" + }, + "notion-token": { + "name": "Notion 令牌" + }, + "npm-token": { + "name": "npm 令牌" + }, + "onepassword-token": { + "name": "1Password 服務帳號令牌" + }, + "openai-api-key": { + "name": "OpenAI API 金鑰", + "about": "`sk-` 開頭,全長至少 40 個字元,同時含字母和數字" + }, + "openai-project-key": { + "name": "OpenAI 專案金鑰" + }, + "openai-service-key": { + "name": "OpenAI 服務帳號與管理金鑰" + }, + "openrouter-key": { + "name": "OpenRouter API 金鑰" + }, + "passport-mrz": { + "name": "護照機讀區", + "about": "兩行各 44 個字元、以 `P` 開頭,四處校驗位與綜合校驗位都對得上;整段" + }, + "perplexity-key": { + "name": "Perplexity API 金鑰" + }, + "pinecone-key": { + "name": "Pinecone API 金鑰" + }, + "postman-key": { + "name": "Postman API 金鑰" + }, + "private-key": { + "name": "私鑰", + "about": "`-----BEGIN … PRIVATE KEY-----` 至對應的 END,整段" + }, + "public-ip": { + "name": "公網 IP 地址", + "about": "公網 IPv4、IPv6 地址;私有、迴環、鏈路本地、運營商級 NAT、文件示例與組播地址除外" + }, + "pulumi-token": { + "name": "Pulumi 令牌" + }, + "pypi-token": { + "name": "PyPI 令牌" + }, + "qianfan-api-key": { + "name": "百度千帆 API 金鑰", + "about": "`bce-v3/ALTAK-` 開頭,其後為 21 個字母或數字、`/` 與 40 個十六進位制字元,整段" + }, + "replicate-token": { + "name": "Replicate 令牌" + }, + "rubygems-token": { + "name": "RubyGems 令牌" + }, + "sendgrid-key": { + "name": "SendGrid 金鑰" + }, + "sentry-token": { + "name": "Sentry 令牌" + }, + "sg-nric": { + "name": "新加坡 NRIC / FIN", + "about": "S、T、F、G 之一開頭,7 位數字加校驗字母,校驗字母對得上" + }, + "shopify-token": { + "name": "Shopify 令牌" + }, + "sk-compat-key": { + "name": "OpenAI 相容格式 API 金鑰", + "about": "`sk-` 開頭,其後恰為 32 個字母和數字(兩者都有),或恰為 48 個小寫字母" + }, + "slack-app-token": { + "name": "Slack 應用令牌" + }, + "slack-bot-token": { + "name": "Slack 機器人令牌" + }, + "slack-other-token": { + "name": "Slack 其他令牌" + }, + "slack-user-token": { + "name": "Slack 使用者令牌" + }, + "stripe-live-key": { + "name": "Stripe 生產金鑰" + }, + "stripe-restricted-key": { + "name": "Stripe 受限金鑰" + }, + "stripe-webhook-secret": { + "name": "Stripe Webhook 簽名金鑰" + }, + "supabase-key": { + "name": "Supabase 金鑰" + }, + "tavily-key": { + "name": "Tavily API 金鑰" + }, + "telegram-bot-token": { + "name": "Telegram 機器人令牌", + "about": "8 至 10 位數字與 `:AA`,其後 33 個字元" + }, + "tencent-secret-id": { + "name": "騰訊雲 SecretId" + }, + "terraform-token": { + "name": "Terraform Cloud 令牌", + "about": "14 個字母或數字與 `.atlasv1.`,其後 60 至 70 個字元" + }, + "thinkwatch-saved-secret": { + "name": "ThinkWatch 中儲存的金鑰", + "about": "按值識別 ThinkWatch 中儲存的金鑰,與格式無關:上游金鑰與請求頭中的值、閘道器金鑰、代理密碼、遠端控制金鑰、同步與備份憑據。不足 12 個字元的值不識別" + }, + "twilio-api-key": { + "name": "Twilio API 金鑰" + }, + "uk-nino": { + "name": "英國國民保險號", + "about": "2 個字母、6 位數字與 A 至 D 之一組成的英國國民保險號,不會分配的字母組合除外" + }, + "url-token": { + "name": "URL 中的令牌", + "about": "URL 查詢引數 `access_token`、`api_key`、`apikey`、`client_secret`、`sig`、`X-Amz-Signature`、`X-Goog-Signature` 的值;只換引數值" + }, + "us-ssn": { + "name": "美國社會安全號", + "about": "`ddd-dd-dddd` 寫法的美國社會安全號,不會分配的區號、組號與序號除外" + }, + "uuid": { + "name": "UUID/緊湊識別符號", + "about": "帶連字元的 UUID 和 32 位十六進位制串,不區分大小寫、不限制版本,包括訂單號和追蹤 ID;同形狀的緊湊雜湊也替換" + }, + "vault-token": { + "name": "HashiCorp Vault 令牌" + }, + "vin": { + "name": "車輛識別代號(VIN)", + "about": "17 個字元、不含 I、O、Q,第 9 位校驗碼對得上" + }, + "volcengine-access-key-id": { + "name": "火山引擎 AccessKey ID" + }, + "xai-key": { + "name": "xAI API 金鑰" + }, + "zhipu-api-key": { + "name": "智譜 API 金鑰", + "about": "32 個十六進位制字元、`.` 與 16 個字母或數字相連" + } + }, + "kinds": { + "ai-services": "AI 服務", + "business": "支付、通訊與協作", + "cloud": "雲服務與基礎設施", + "conn-strings": "連線串", + "contact": "聯絡方式", + "crypto": "加密貨幣", + "custom": "自定義", + "dev-platforms": "程式碼託管與軟體釋出", + "device": "裝置與網路標識", + "financial": "金融賬戶", + "foreign-ids": "境外證件號碼", + "id-documents": "證件號碼", + "in-context": "固定位置的憑據", + "internal": "內網地址", + "jwt": "JWT", + "labeled-personal": "帶欄位名的個人資訊", + "location": "住址與位置", + "private-keys": "私鑰", + "saved": "儲存的金鑰", + "vehicle": "車輛" + } + }, + "content": { + "rules": { + "act-as": { + "name": "要求扮演角色" + }, + "base64-wall": { + "name": "長串 Base64" + }, + "bidi-controls": { + "name": "雙向控制符", + "why": "可使螢幕上的顯示順序與實際字元順序不一致。" + }, + "dan": { + "name": "DAN" + }, + "developer-mode": { + "name": "開發者模式" + }, + "disregard-your-instructions": { + "name": "要求無視指令" + }, + "ignore-all-previous": { + "name": "要求忽略之前的全部內容" + }, + "ignore-previous-instructions": { + "name": "要求忽略先前的指令" + }, + "jailbreak": { + "name": "越獄" + }, + "new-persona": { + "name": "新的人設" + }, + "pretend-to-be": { + "name": "要求假裝身份" + }, + "private-use": { + "name": "私用區字元", + "why": "沒有標準含義。部分圖示字型會用到。" + }, + "reveal-your-instructions": { + "name": "要求透露指令" + }, + "system-prompt": { + "name": "索取系統提示詞" + }, + "unicode-tags": { + "name": "Unicode 標籤字元", + "why": "在編輯器中完全不可見,但會原樣進入模型上下文,可用於隱藏整段指令。" + }, + "what-are-your-rules": { + "name": "詢問規則" + }, + "you-are-now": { + "name": "重新設定身份" + }, + "zero-width": { + "name": "零寬字元", + "why": "在編輯器中不可見,但會被模型讀到。表情符號、波斯文等正常文字也會用到。" + }, + "zh-do-not-follow": { + "name": "要求不要遵循(中文)" + }, + "zh-forget-your": { + "name": "要求忘記指令(中文)" + }, + "zh-ignore-previous": { + "name": "要求忽略先前的指令(中文)" + }, + "zh-jailbreak": { + "name": "越獄(中文)" + }, + "zh-reveal-your": { + "name": "要求透露指令(中文)" + }, + "zh-role-play": { + "name": "要求扮演角色(中文)" + }, + "zh-system-prompt": { + "name": "系統提示詞(中文)" + }, + "zh-you-are-now": { + "name": "重新設定身份(中文)" + } + }, + "kinds": { + "chinese": "中文說法", + "custom": "自定義", + "injection": "指令覆蓋", + "invisible": "隱藏字元", + "persona": "身份與提示詞" + } + }, + "inspect_tools": { + "rules": { + "base64-decode-exec": { + "name": "解碼後執行", + "why": "將要執行的內容隱藏在 base64 編碼中" + }, + "chat-marker": { + "name": "偽造對話標記", + "why": "偽造對話標記,試圖讓模型將正文當作系統訊息" + }, + "chmod-777": { + "name": "開放全部寫許可權", + "why": "將檔案許可權設為所有人可寫" + }, + "crontab-install": { + "name": "安裝定時任務", + "why": "安裝定時任務,或刪除全部現有定時任務" + }, + "curl-pipe-sh": { + "name": "下載即執行", + "why": "下載後直接執行,執行的內容由遠端決定且無法預先檢視" + }, + "disregard": { + "name": "要求無視系統提示", + "why": "典型的提示注入開頭,使用 disregard 一類的動詞" + }, + "exfil-credentials": { + "name": "外發憑據檔案", + "why": "要求模型將憑據檔案的內容傳送出去" + }, + "exfil-credentials-reversed": { + "name": "外發憑據檔案(動詞在前)", + "why": "要求模型將憑據檔案的內容傳送出去" + }, + "exfil-env": { + "name": "外發環境變數", + "why": "將環境變數(通常包含金鑰)傳送到外部" + }, + "fake-system": { + "name": "偽裝的系統發言", + "why": "偽裝成系統或助手的發言" + }, + "ignore-previous": { + "name": "要求忽略先前的指令", + "why": "典型的提示注入開頭" + }, + "ignore-previous-zh": { + "name": "要求忽略先前的指令(中文)", + "why": "中文提示注入,要求忽略先前的指令" + }, + "new-instructions-zh": { + "name": "宣告新的指令(中文)", + "why": "中文提示注入,宣告新的指令" + }, + "rm-rf-root": { + "name": "刪除主目錄或根目錄", + "why": "刪除整個主目錄或根目錄" + }, + "secret-to-unknown-host": { + "name": "憑據發往陌生主機", + "why": "將憑據發往既非本機、也不是該憑據服務商的主機" + }, + "ssh-key-read": { + "name": "讀取私鑰或雲憑據", + "why": "讀取私鑰或雲服務憑據" + }, + "thinkwatch-data": { + "name": "讀寫 ThinkWatch 自己的資料", + "why": "讀寫 ThinkWatch 的資料目錄,其中以明文儲存全部上游金鑰和這幾項防護的設定" + }, + "upload-file-to-host": { + "name": "上傳本地檔案到外部主機", + "why": "將本地檔案的內容上傳到外部主機" + }, + "write-startup-item": { + "name": "寫入啟動項", + "why": "寫入開機或開啟終端時自動執行的位置" + }, + "you-are-now": { + "name": "重新設定模型身份", + "why": "試圖重新設定模型的身份" + }, + "you-are-now-zh": { + "name": "重新設定模型身份(中文)", + "why": "試圖重新設定模型的身份" + } + }, + "kinds": { + "command": "內建", + "custom": "自定義" + } + } +} diff --git a/src/i18n/guard.zh.json b/src/i18n/guard.zh.json new file mode 100644 index 00000000..d25b3cee --- /dev/null +++ b/src/i18n/guard.zh.json @@ -0,0 +1,225 @@ +{ + "redact": { + "rules": { + "age-secret-key": {"name": "age 私钥"}, + "alibaba-access-key-id": {"name": "阿里云 AccessKey ID"}, + "anthropic-api-key": {"name": "Anthropic API 密钥"}, + "artifactory-key": {"name": "JFrog Artifactory 密钥"}, + "atlassian-token": {"name": "Atlassian API 令牌"}, + "auth-header-credential": {"name": "请求头中的凭据", "about": "`Authorization`、`X-Api-Key`、`Api-Key`、`X-Goog-Api-Key` 请求头的值,包括 curl 的 `-H`、HTTP 原文与代码中的写法;只换值"}, + "aws-access-key-id": {"name": "AWS 访问密钥 ID"}, + "aws-other-key-id": {"name": "AWS 其他访问密钥 ID"}, + "aws-temporary-key-id": {"name": "AWS 临时访问密钥 ID"}, + "azure-ad-client-secret": {"name": "Azure AD 客户端密码", "about": "3 个字符、1 位数字与 `Q~`,其后 31 至 34 个字符"}, + "bank-card": {"name": "银行卡号", "about": "银联、Visa、Mastercard、American Express、JCB、Discover、Diners Club 的卡号:号段、位数对得上并通过 Luhn 校验;公开的测试卡号除外"}, + "bedrock-api-key": {"name": "Amazon Bedrock API 密钥"}, + "bot-webhook": {"name": "机器人 Webhook", "about": "飞书 / Lark、钉钉、企业微信、Slack、Discord、Microsoft Teams 机器人 Webhook 地址中的令牌;只换令牌段"}, + "br-cpf": {"name": "巴西 CPF", "about": "`ddd.ddd.ddd-dd` 写法的巴西 CPF,两位校验码对得上"}, + "brevo-key": {"name": "Brevo API 密钥"}, + "cerebras-key": {"name": "Cerebras API 密钥"}, + "clojars-token": {"name": "Clojars 令牌"}, + "cloudflare-origin-ca-key": {"name": "Cloudflare Origin CA 密钥"}, + "cn-address": {"name": "中国大陆详细地址", "about": "行政区划名称、街道路巷村之一与门牌号(号、栋、单元、室)组成的中国大陆详细地址;只到区县的不算"}, + "cn-landline": {"name": "中国大陆固定电话", "about": "`0` 开头的 2 至 3 位区号加 7 至 8 位号码,区号有效,须带括号或连字符(`010-12345678`、`(0755)1234567`)"}, + "cn-license-plate": {"name": "中国大陆车牌号", "about": "省份简称、字母与 5 位字母或数字(新能源车为 6 位),不含 I、O"}, + "cn-mobile-phone": {"name": "中国大陆手机号", "about": "中国大陆手机号:`1` 开头的 11 位数字,第二位为 3 到 9,前后不紧挨其他数字;可带 `+86`、`0086`、`86-` 前缀,可按 3-4-4 以空格或连字符分隔"}, + "cn-passport": {"name": "中国护照号", "about": "`E` 或 `E` 加一个字母开头、其后 7 至 8 位数字,且前 20 个字符内出现「护照」或「passport」"}, + "cn-resident-id": {"name": "居民身份证号", "about": "18 位居民身份证号(含港澳台居民居住证、外国人永久居留身份证):地区码、1900 年以来的出生日期和校验码都对得上"}, + "cn-resident-id-15": {"name": "15 位旧身份证号", "about": "15 位旧身份证号:地区码、6 位出生日期都对得上,其后 3 位顺序码"}, + "command-line-password": {"name": "命令行中的口令", "about": "命令行中的口令:`curl -u 用户:口令`、`--user`、`mysql -p口令`、`PGPASSWORD=… psql`;只换口令"}, + "config-assignment": {"name": "配置文件中的密钥赋值", "about": "`.env`、YAML、TOML、INI、JSON 中变量名以 `SECRET`、`SECRET_KEY`、`PASSWORD`、`PASSWD`、`PWD`、`TOKEN`、`API_KEY`、`APIKEY`、`ACCESS_KEY`、`PRIVATE_KEY`、`CLIENT_SECRET` 结尾(不区分大小写)、值为至少 8 个字符的字面量的赋值;只换值,表达式、变量引用和占位写法不算"}, + "conn-string-password": {"name": "连接串口令", "about": "`协议://用户:口令@主机` 中的口令;只换口令"}, + "crypto-address": {"name": "区块链账户/扩展公钥", "about": "EVM 十六进制地址,经校验的 Bitcoin/TRON/XRP/Stellar 地址、Bitcoin 隔离见证地址和 BIP32/SLIP-0132 扩展公钥;也覆盖 Solana 等无校验和的 32 字节 Base58 账户格式"}, + "crypto-extended-key": {"name": "扩展私钥", "about": "BIP32 / SLIP-0132 扩展私钥:`xprv`、`tprv`、`yprv`、`Yprv`、`zprv`、`Zprv`、`uprv`、`Uprv`、`vprv`、`Vprv`;Base58Check、私钥标记及 secp256k1 标量均有效"}, + "crypto-hex-key": {"name": "裸钱包私钥/32 字节哈希", "about": "64 位十六进制串,可带 `0x` 前缀;覆盖 EVM、TRON 裸私钥以及格式无法区分的交易哈希和摘要"}, + "crypto-keystore": {"name": "钱包密钥库/密文", "about": "字面量 `keystore` 或 `ciphertext` 字段,包括 Ethereum V3 加密密钥材料;作为文本粘贴的 JSON 对象也保护,只换值"}, + "crypto-mnemonic": {"name": "助记词", "about": "连续 12、15、18、21 或 24 个 BIP39 英文或简体中文词表中的词,并通过校验和;可带编号,整段"}, + "crypto-rpc-key": {"name": "区块链 RPC 地址凭证", "about": "Infura `/v3/`、Alchemy `/v2/`、QuickNode 令牌路径及 Helius `api-key` URL 中的 API 凭据;只换凭据部分"}, + "crypto-secret-field": {"name": "字段中的钱包机密", "about": "按字段识别私钥、种子、助记词、恢复短语、口令、恢复码和 MPC/备份份额,包括 `pk`、`privateKey`、`PRIVY_WALLET_PRIVATE_KEY` 和中文标签;只换值,不猜测密钥长度"}, + "crypto-solana-key": {"name": "Solana 密钥对", "about": "Base58 编码或作为文本粘贴的 JSON 字节数组,含 64 字节 Ed25519 种子与公钥;由种子派生的公钥须一致,排除同长度签名"}, + "crypto-stellar-key": {"name": "Stellar 私密种子", "about": "Stellar `S` StrKey 种子,版本、32 字节载荷和 CRC16-XModem 校验均有效"}, + "crypto-sui-key": {"name": "Sui 私钥", "about": "`suiprivkey1` Bech32 编码,校验和有效,含支持的签名方案和 32 字节密钥"}, + "crypto-wif-key": {"name": "WIF 私钥", "about": "51 或 52 个字符的 WIF 私钥:Base58Check 校验通过,版本字节对得上"}, + "crypto-xrp-seed": {"name": "XRP 账户种子", "about": "XRP 字母表的 Base58Check 账户种子,包括 secp256k1 和 Ed25519 版本"}, + "databricks-token": {"name": "Databricks 令牌"}, + "digitalocean-other-token": {"name": "DigitalOcean 其他令牌"}, + "digitalocean-token": {"name": "DigitalOcean 令牌"}, + "docker-hub-token": {"name": "Docker Hub 令牌"}, + "doppler-token": {"name": "Doppler 令牌"}, + "email": {"name": "邮箱地址", "about": "邮箱地址:`名称@域名`"}, + "exchange-credential": {"name": "交易 API/签名鉴权凭证", "about": "SDK/配置字段或交易请求头中的 API key、secret、passphrase、签名 Memo、OTP 和鉴权签名;覆盖 Binance、OKX、Bybit、Coinbase、Kraken、KuCoin、Bitget、Gate、MEXC、Gemini、Bitfinex、HTX、BitMart、Phemex、Bitstamp、Polymarket 和 predict.fun;只换值"}, + "fireworks-key": {"name": "Fireworks AI API 密钥"}, + "flyio-token": {"name": "Fly.io 令牌"}, + "geo-coordinates": {"name": "精确坐标", "about": "成对出现、在取值范围内、小数不少于 5 位的纬度与经度"}, + "github-fine-grained-token": {"name": "GitHub 细粒度令牌"}, + "github-oauth-token": {"name": "GitHub OAuth 令牌"}, + "github-personal-token": {"name": "GitHub 个人令牌"}, + "github-refresh-token": {"name": "GitHub 刷新令牌"}, + "github-server-token": {"name": "GitHub 服务器令牌"}, + "github-user-token": {"name": "GitHub 用户令牌"}, + "gitlab-other-token": {"name": "GitLab 其他令牌"}, + "gitlab-token": {"name": "GitLab 令牌"}, + "google-api-key": {"name": "Google API 密钥"}, + "google-oauth-token": {"name": "Google OAuth 令牌"}, + "grafana-token": {"name": "Grafana 令牌"}, + "groq-key": {"name": "Groq API 密钥"}, + "heroku-key": {"name": "Heroku API 密钥"}, + "hk-macau-taiwan-id": {"name": "港澳台身份证号", "about": "香港、澳门、台湾身份证号:香港、台湾的校验码对得上;澳门的须前文写明证件名称"}, + "huggingface-token": {"name": "Hugging Face 令牌"}, + "iban": {"name": "国际银行账号(IBAN)", "about": "国家代码、两位校验码与该国规定位数的账号,MOD 97-10 校验通过;连写或四位一组"}, + "imei": {"name": "IMEI", "about": "15 位数字,Luhn 校验通过,且前 20 个字符内出现「IMEI」"}, + "in-aadhaar": {"name": "印度 Aadhaar 号码", "about": "12 位数字(可四位一组),首位为 2 至 9,Verhoeff 校验通过"}, + "internal-domain": {"name": "内部域名", "about": "以 `.local`、`.internal`、`.lan`、`.corp`、`.home.arpa`、`.intranet` 结尾的域名"}, + "internal-ip": {"name": "内网地址", "about": "`10.`、`172.16–31.`、`192.168.`、`100.64–127.` 开头的地址与 `fc00::/7` 内的 IPv6 地址,不含 127.0.0.1"}, + "intl-phone": {"name": "国际电话号码", "about": "`+` 开头,国家码有效、位数与该国规定一致;可带空格与连字符"}, + "jp-my-number": {"name": "日本个人番号", "about": "12 位数字,校验位对得上,且前 20 个字符内出现「マイナンバー」「個人番号」或「My Number」"}, + "jwt": {"name": "JWT", "about": "三段 base64url,首段解码后含 `\"alg\"`"}, + "kr-rrn": {"name": "韩国居民登录号", "about": "6 位出生日期、`-` 与 7 位数字,日期有效、第 8 位为 1 至 8"}, + "labeled-account": {"name": "带字段名的银行账号", "about": "字段名为 `银行账号`、`开户账号`、`银行卡号`、`account_number`、`bank_account`、`bank_account_number` 的值,包括 `字段名: 值`、`\"字段名\": \"值\"` 与表格表头的写法;只换值"}, + "labeled-address": {"name": "带字段名的住址", "about": "字段名为 `住址`、`家庭住址`、`收货地址`、`联系地址`、`home_address`、`shipping_address`、`residential_address`、`address` 的值,包括 `字段名: 值`、`\"字段名\": \"值\"` 与表格表头的写法;只换值"}, + "labeled-birth-date": {"name": "带字段名的出生日期", "about": "字段名为 `出生日期`、`生日`、`birthday`、`birth_date`、`date_of_birth`、`dob` 的值,包括 `字段名: 值`、`\"字段名\": \"值\"` 与表格表头的写法;只换值"}, + "labeled-health": {"name": "带字段名的健康信息", "about": "字段名为 `病历号`、`住院号`、`诊断`、`病史`、`medical_record_number`、`diagnosis` 的值,包括 `字段名: 值`、`\"字段名\": \"值\"` 与表格表头的写法;只换值"}, + "labeled-name": {"name": "带字段名的姓名", "about": "字段名为 `姓名`、`真实姓名`、`联系人`、`收件人`、`收货人`、`real_name`、`full_name`、`legal_name`、`first_name`、`last_name`、`given_name`、`family_name`、`name` 的值,包括 `字段名: 值`、`\"字段名\": \"值\"` 与表格表头的写法;只换值"}, + "langfuse-secret-key": {"name": "Langfuse 私密密钥"}, + "langsmith-key": {"name": "LangSmith API 密钥"}, + "linear-key": {"name": "Linear API 密钥"}, + "mac-address": {"name": "MAC 地址", "about": "6 组两位十六进制字符,以 `:` 或 `-` 分隔;全零、广播与组播地址除外"}, + "mainland-travel-permit": {"name": "港澳台往来内地通行证号", "about": "港澳居民来往内地通行证(`H` 或 `M` 加 8 位数字)与台湾居民来往大陆通行证(8 位数字),且前 20 个字符内出现「通行证」「回乡证」或「台胞证」"}, + "minimax-key": {"name": "MiniMax API 密钥"}, + "notion-token": {"name": "Notion 令牌"}, + "npm-token": {"name": "npm 令牌"}, + "onepassword-token": {"name": "1Password 服务账号令牌"}, + "openai-api-key": {"name": "OpenAI API 密钥", "about": "`sk-` 开头,全长至少 40 个字符,同时含字母和数字"}, + "openai-project-key": {"name": "OpenAI 项目密钥"}, + "openai-service-key": {"name": "OpenAI 服务账号与管理密钥"}, + "openrouter-key": {"name": "OpenRouter API 密钥"}, + "passport-mrz": {"name": "护照机读区", "about": "两行各 44 个字符、以 `P` 开头,四处校验位与综合校验位都对得上;整段"}, + "perplexity-key": {"name": "Perplexity API 密钥"}, + "pinecone-key": {"name": "Pinecone API 密钥"}, + "postman-key": {"name": "Postman API 密钥"}, + "private-key": {"name": "私钥", "about": "`-----BEGIN … PRIVATE KEY-----` 至对应的 END,整段"}, + "public-ip": {"name": "公网 IP 地址", "about": "公网 IPv4、IPv6 地址;私有、回环、链路本地、运营商级 NAT、文档示例与组播地址除外"}, + "pulumi-token": {"name": "Pulumi 令牌"}, + "pypi-token": {"name": "PyPI 令牌"}, + "qianfan-api-key": {"name": "百度千帆 API 密钥", "about": "`bce-v3/ALTAK-` 开头,其后为 21 个字母或数字、`/` 与 40 个十六进制字符,整段"}, + "replicate-token": {"name": "Replicate 令牌"}, + "rubygems-token": {"name": "RubyGems 令牌"}, + "sendgrid-key": {"name": "SendGrid 密钥"}, + "sentry-token": {"name": "Sentry 令牌"}, + "sg-nric": {"name": "新加坡 NRIC / FIN", "about": "S、T、F、G 之一开头,7 位数字加校验字母,校验字母对得上"}, + "shopify-token": {"name": "Shopify 令牌"}, + "sk-compat-key": {"name": "OpenAI 兼容格式 API 密钥", "about": "`sk-` 开头,其后恰为 32 个字母和数字(两者都有),或恰为 48 个小写字母"}, + "slack-app-token": {"name": "Slack 应用令牌"}, + "slack-bot-token": {"name": "Slack 机器人令牌"}, + "slack-other-token": {"name": "Slack 其他令牌"}, + "slack-user-token": {"name": "Slack 用户令牌"}, + "stripe-live-key": {"name": "Stripe 生产密钥"}, + "stripe-restricted-key": {"name": "Stripe 受限密钥"}, + "stripe-webhook-secret": {"name": "Stripe Webhook 签名密钥"}, + "supabase-key": {"name": "Supabase 密钥"}, + "tavily-key": {"name": "Tavily API 密钥"}, + "telegram-bot-token": {"name": "Telegram 机器人令牌", "about": "8 至 10 位数字与 `:AA`,其后 33 个字符"}, + "tencent-secret-id": {"name": "腾讯云 SecretId"}, + "terraform-token": {"name": "Terraform Cloud 令牌", "about": "14 个字母或数字与 `.atlasv1.`,其后 60 至 70 个字符"}, + "thinkwatch-saved-secret": {"name": "ThinkWatch 中保存的密钥", "about": "按值识别 ThinkWatch 中保存的密钥,与格式无关:上游密钥与请求头中的值、网关密钥、代理密码、远程控制密钥、同步与备份凭据。不足 12 个字符的值不识别"}, + "twilio-api-key": {"name": "Twilio API 密钥"}, + "uk-nino": {"name": "英国国民保险号", "about": "2 个字母、6 位数字与 A 至 D 之一组成的英国国民保险号,不会分配的字母组合除外"}, + "url-token": {"name": "URL 中的令牌", "about": "URL 查询参数 `access_token`、`api_key`、`apikey`、`client_secret`、`sig`、`X-Amz-Signature`、`X-Goog-Signature` 的值;只换参数值"}, + "us-ssn": {"name": "美国社会安全号", "about": "`ddd-dd-dddd` 写法的美国社会安全号,不会分配的区号、组号与序号除外"}, + "uuid": {"name": "UUID/紧凑标识符", "about": "带连字符的 UUID 和 32 位十六进制串,不区分大小写、不限制版本,包括订单号和追踪 ID;同形状的紧凑哈希也替换"}, + "vault-token": {"name": "HashiCorp Vault 令牌"}, + "vin": {"name": "车辆识别代号(VIN)", "about": "17 个字符、不含 I、O、Q,第 9 位校验码对得上"}, + "volcengine-access-key-id": {"name": "火山引擎 AccessKey ID"}, + "xai-key": {"name": "xAI API 密钥"}, + "zhipu-api-key": {"name": "智谱 API 密钥", "about": "32 个十六进制字符、`.` 与 16 个字母或数字相连"} + }, + "kinds": { + "ai-services": "AI 服务", + "business": "支付、通信与协作", + "cloud": "云服务与基础设施", + "conn-strings": "连接串", + "contact": "联系方式", + "crypto": "加密货币", + "custom": "自定义", + "dev-platforms": "代码托管与软件发布", + "device": "设备与网络标识", + "financial": "金融账户", + "foreign-ids": "境外证件号码", + "id-documents": "证件号码", + "in-context": "固定位置的凭据", + "internal": "内网地址", + "jwt": "JWT", + "labeled-personal": "带字段名的个人信息", + "location": "住址与位置", + "private-keys": "私钥", + "saved": "保存的密钥", + "vehicle": "车辆" + } + }, + "content": { + "rules": { + "act-as": {"name": "要求扮演角色"}, + "base64-wall": {"name": "长串 Base64"}, + "bidi-controls": {"name": "双向控制符", "why": "可使屏幕上的显示顺序与实际字符顺序不一致。"}, + "dan": {"name": "DAN"}, + "developer-mode": {"name": "开发者模式"}, + "disregard-your-instructions": {"name": "要求无视指令"}, + "ignore-all-previous": {"name": "要求忽略之前的全部内容"}, + "ignore-previous-instructions": {"name": "要求忽略先前的指令"}, + "jailbreak": {"name": "越狱"}, + "new-persona": {"name": "新的人设"}, + "pretend-to-be": {"name": "要求假装身份"}, + "private-use": {"name": "私用区字符", "why": "没有标准含义。部分图标字体会用到。"}, + "reveal-your-instructions": {"name": "要求透露指令"}, + "system-prompt": {"name": "索取系统提示词"}, + "unicode-tags": {"name": "Unicode 标签字符", "why": "在编辑器中完全不可见,但会原样进入模型上下文,可用于隐藏整段指令。"}, + "what-are-your-rules": {"name": "询问规则"}, + "you-are-now": {"name": "重新设定身份"}, + "zero-width": {"name": "零宽字符", "why": "在编辑器中不可见,但会被模型读到。表情符号、波斯文等正常文字也会用到。"}, + "zh-do-not-follow": {"name": "要求不要遵循(中文)"}, + "zh-forget-your": {"name": "要求忘记指令(中文)"}, + "zh-ignore-previous": {"name": "要求忽略先前的指令(中文)"}, + "zh-jailbreak": {"name": "越狱(中文)"}, + "zh-reveal-your": {"name": "要求透露指令(中文)"}, + "zh-role-play": {"name": "要求扮演角色(中文)"}, + "zh-system-prompt": {"name": "系统提示词(中文)"}, + "zh-you-are-now": {"name": "重新设定身份(中文)"} + }, + "kinds": { + "chinese": "中文说法", + "custom": "自定义", + "injection": "指令覆盖", + "invisible": "隐藏字符", + "persona": "身份与提示词" + } + }, + "inspect_tools": { + "rules": { + "base64-decode-exec": {"name": "解码后执行", "why": "将要执行的内容隐藏在 base64 编码中"}, + "chat-marker": {"name": "伪造对话标记", "why": "伪造对话标记,试图让模型将正文当作系统消息"}, + "chmod-777": {"name": "开放全部写权限", "why": "将文件权限设为所有人可写"}, + "crontab-install": {"name": "安装定时任务", "why": "安装定时任务,或删除全部现有定时任务"}, + "curl-pipe-sh": {"name": "下载即执行", "why": "下载后直接执行,执行的内容由远端决定且无法预先查看"}, + "disregard": {"name": "要求无视系统提示", "why": "典型的提示注入开头,使用 disregard 一类的动词"}, + "exfil-credentials": {"name": "外发凭据文件", "why": "要求模型将凭据文件的内容发送出去"}, + "exfil-credentials-reversed": {"name": "外发凭据文件(动词在前)", "why": "要求模型将凭据文件的内容发送出去"}, + "exfil-env": {"name": "外发环境变量", "why": "将环境变量(通常包含密钥)发送到外部"}, + "fake-system": {"name": "伪装的系统发言", "why": "伪装成系统或助手的发言"}, + "ignore-previous": {"name": "要求忽略先前的指令", "why": "典型的提示注入开头"}, + "ignore-previous-zh": {"name": "要求忽略先前的指令(中文)", "why": "中文提示注入,要求忽略先前的指令"}, + "new-instructions-zh": {"name": "声明新的指令(中文)", "why": "中文提示注入,声明新的指令"}, + "rm-rf-root": {"name": "删除主目录或根目录", "why": "删除整个主目录或根目录"}, + "secret-to-unknown-host": {"name": "凭据发往陌生主机", "why": "将凭据发往既非本机、也不是该凭据服务商的主机"}, + "ssh-key-read": {"name": "读取私钥或云凭据", "why": "读取私钥或云服务凭据"}, + "thinkwatch-data": {"name": "读写 ThinkWatch 自己的数据", "why": "读写 ThinkWatch 的数据目录,其中以明文保存全部上游密钥和这几项防护的设置"}, + "upload-file-to-host": {"name": "上传本地文件到外部主机", "why": "将本地文件的内容上传到外部主机"}, + "write-startup-item": {"name": "写入启动项", "why": "写入开机或打开终端时自动执行的位置"}, + "you-are-now": {"name": "重新设定模型身份", "why": "试图重新设定模型的身份"}, + "you-are-now-zh": {"name": "重新设定模型身份(中文)", "why": "试图重新设定模型的身份"} + }, + "kinds": { + "command": "内置", + "custom": "自定义" + } + } +} diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 08742b4a..f53cfb0f 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -15,10 +15,18 @@ import { useSyncExternalStore } from "react"; * ); * * 组件里 `const t = useText(fooText)`,然后 `t.title`、`t.failed(3)`。 - * **英文那一份的形状由中文那一份决定**:少一条、多一条、参数对不上,都是 - * 编译错误 —— 漏翻不会等到有人看见那一屏才发现。 + * 文案的形状由第一份决定。日文可以逐步补齐,缺少的条目使用英文。 */ -export type Lang = "zh" | "en"; +export const LANG_NAMES = { + zh: "简体中文", + "zh-Hant": "繁體中文", + en: "English", + ja: "日本語", + ko: "한국어", + es: "Español", +} as const; +export type Lang = keyof typeof LANG_NAMES; +export const LANGUAGES: readonly Lang[] = Object.keys(LANG_NAMES) as Lang[]; declare global { interface Window { @@ -27,18 +35,26 @@ declare global { } } -/** 语言自己的名字。**不翻译**:找「English」的人未必认得「英文」两个字 */ -export const LANG_NAMES: Record = { - zh: "简体中文", - en: "English", -}; +export function isLang(value: unknown): value is Lang { + return typeof value === "string" && Object.hasOwn(LANG_NAMES, value); +} + +export function preferredLanguage(tags: readonly string[]): Lang { + for (const tag of tags) { + const [language, scriptOrRegion] = tag.trim().toLowerCase().split(/[-_.@]/, 2); + if (language === "zh" && ["hant", "tw", "hk", "mo"].includes(scriptOrRegion ?? "")) { + return "zh-Hant"; + } + if (isLang(language)) return language; + } + return "en"; +} function initial(): Lang { const injected = typeof window === "undefined" ? undefined : window.__TW_LANG__; - if (injected === "zh" || injected === "en") return injected; + if (isLang(injected)) return injected; // 不在应用里(浏览器直接打开、隔离预览)时,按浏览器的语言 - const nav = typeof navigator === "undefined" ? "" : navigator.language; - return /^zh\b/i.test(nav) ? "zh" : "en"; + return typeof navigator === "undefined" ? "en" : preferredLanguage([...navigator.languages, navigator.language]); } let current: Lang = initial(); @@ -49,18 +65,18 @@ export function getLang(): Lang { } /** ``:读屏和浏览器的断行、字体选择都看它 */ -function tagOf(lang: Lang): string { - return lang === "zh" ? "zh-CN" : "en"; +export function localeTag(lang: Lang): string { + return lang === "zh" ? "zh-CN" : lang; } export function setLang(next: Lang) { if (next === current) return; current = next; - if (typeof document !== "undefined") document.documentElement.lang = tagOf(next); + if (typeof document !== "undefined") document.documentElement.lang = localeTag(next); for (const f of listeners) f(); } -if (typeof document !== "undefined") document.documentElement.lang = tagOf(current); +if (typeof document !== "undefined") document.documentElement.lang = localeTag(current); function subscribe(f: () => void) { listeners.add(f); @@ -74,14 +90,21 @@ export function useLang(): Lang { return useSyncExternalStore(subscribe, getLang, getLang); } -/** 一组文案的中英两份 */ -export type Messages = { readonly zh: T; readonly en: T }; +export type Messages = Readonly>; +type Localizations = Partial, Partial>>; /** - * 定义一组文案。第二个参数必须和第一个同形:键一样、函数的参数一样。 + * 定义一组文案。未翻译的顶层条目使用英文,繁体中文使用简体中文。 */ -export function messages(zh: T, en: NoInfer): Messages { - return { zh, en }; +export function messages(zh: T, en: NoInfer, locales: Localizations> = {}): Messages { + return { + zh, + en, + "zh-Hant": locales["zh-Hant"] ? { ...zh, ...locales["zh-Hant"] } : zh, + ja: locales.ja ? { ...en, ...locales.ja } : en, + ko: locales.ko ? { ...en, ...locales.ko } : en, + es: locales.es ? { ...en, ...locales.es } : en, + }; } /** 组件里取文案 */ diff --git a/src/i18n/plugin-defaults.json b/src/i18n/plugin-defaults.json index 60458b38..ce1595da 100644 --- a/src/i18n/plugin-defaults.json +++ b/src/i18n/plugin-defaults.json @@ -7,10 +7,42 @@ "zh": { "name": "指定回答语言", "description": "在系统提示词末尾附加一句固定的要求:使用此处设置的语言回答。", - "settings": { "language": "回答语言" } + "settings": { + "language": "回答语言" + } }, "en": { - "settings": { "language": "Answer language" } + "settings": { + "language": "Answer language" + } + }, + "ja": { + "name": "回答言語の指定", + "description": "システムプロンプトの末尾に、指定した言語で回答するよう指示を追加します。", + "settings": { + "language": "回答言語" + } + }, + "zh-Hant": { + "name": "指定回答語言", + "description": "在系統提示詞末尾附加一句固定的要求:使用此處設定的語言回答。", + "settings": { + "language": "回答語言" + } + }, + "ko": { + "name": "응답 언어 지정", + "description": "시스템 프롬프트 끝에 지정한 언어로 응답하라는 지시를 추가합니다.", + "settings": { + "language": "응답 언어" + } + }, + "es": { + "name": "Idioma de respuesta", + "description": "Añade al mensaje del sistema una instrucción para responder en el idioma elegido.", + "settings": { + "language": "Idioma de respuesta" + } } }, { @@ -19,10 +51,42 @@ "zh": { "name": "WSL 路径转换", "description": "将工具调用参数中的盘符路径改写为客户端能打开的写法(WSL 的 /mnt/c/… 或 Windows 的 C:\\…),回答和对话历史中的工具调用均适用。", - "settings": { "windows_client": "客户端运行在 Windows 上(关闭时按 WSL 处理)" } + "settings": { + "windows_client": "客户端运行在 Windows 上(关闭时按 WSL 处理)" + } }, "en": { - "settings": { "windows_client": "The client runs on Windows (otherwise WSL)" } + "settings": { + "windows_client": "The client runs on Windows (otherwise WSL)" + } + }, + "ja": { + "name": "WSL パスの変換", + "description": "ツール呼び出しの引数に含まれるパスを、クライアントで開ける WSL または Windows 形式に変換します。回答と会話履歴の両方に適用されます。", + "settings": { + "windows_client": "クライアントは Windows で実行(オフの場合は WSL)" + } + }, + "zh-Hant": { + "name": "WSL 路徑轉換", + "description": "將工具呼叫引數中的磁碟機代號路徑改寫為用戶端能開啟的寫法(WSL 的 /mnt/c/… 或 Windows 的 C:\\…),回答和對話歷史中的工具呼叫均適用。", + "settings": { + "windows_client": "用戶端執行在 Windows 上(關閉時按 WSL 處理)" + } + }, + "ko": { + "name": "WSL 경로 변환", + "description": "응답과 대화 기록의 도구 호출에 들어 있는 경로를 클라이언트에서 열 수 있는 WSL 또는 Windows 형식으로 바꿉니다.", + "settings": { + "windows_client": "클라이언트가 Windows에서 실행됨(끄면 WSL 사용)" + } + }, + "es": { + "name": "Conversión de rutas WSL", + "description": "Convierte las rutas de las llamadas a herramientas en respuestas y en el historial al formato WSL o Windows que puede abrir el cliente.", + "settings": { + "windows_client": "El cliente se ejecuta en Windows (desactívalo si usa WSL)" + } } } ] diff --git a/src/import/CannotImportDialog.i18n.ts b/src/import/CannotImportDialog.i18n.ts index eaf67fb4..ae06d30b 100644 --- a/src/import/CannotImportDialog.i18n.ts +++ b/src/import/CannotImportDialog.i18n.ts @@ -21,4 +21,30 @@ export const cannotImportText = messages( latest: "Up to date", checkFailed: "Update check failed", }, + { + "zh-Hant": { + title: "無法匯入這條連結", + unsupported: (param: string) => `這條連結含有當前版本不支援的引數「${param}」。`, + unsupportedUnnamed: "這條連結含有當前版本不支援的引數。", + update: "更新 ThinkWatch Lite 後再開啟這條連結。", + check: "檢查更新", + install: "安裝更新", + checkFailed: "檢查更新失敗", + }, + ko: { + check: "업데이트 확인", + latest: "최신 버전", + checkFailed: "업데이트 확인 실패", + }, + es: { + title: "No se puede importar este enlace", + unsupported: (param: string) => `Este enlace contiene un parámetro que esta versión no admite: “${param}”.`, + unsupportedUnnamed: "Este enlace contiene un parámetro que esta versión no admite.", + update: "Actualiza ThinkWatch Lite, luego abre este enlace de nuevo.", + check: "Buscar actualizaciones", + install: "Instalar actualización", + latest: "Al día", + checkFailed: "Error al buscar actualizaciones", + }, + }, ); diff --git a/src/keys/CreatedDialog.i18n.tsx b/src/keys/CreatedDialog.i18n.tsx index 90b5af49..5412cebb 100644 --- a/src/keys/CreatedDialog.i18n.tsx +++ b/src/keys/CreatedDialog.i18n.tsx @@ -16,4 +16,22 @@ export const createdDialogText = messages( key: "Key", done: "Done", }, + { + "zh-Hant": { + title: "金鑰已建立", + canConnect: (name: ReactNode) => <>{name} 現在可以連線閘道器。, + gatewayAddress: "閘道器地址", + key: "金鑰", + }, + ko: { + key: "키", + }, + es: { + title: "Tecla creada", + canConnect: (name: ReactNode) => <>{name} ahora se puede conectar a la puerta de enlace., + gatewayAddress: "Dirección de la pasarela", + key: "Clave", + done: "Hecho", + }, + }, ); diff --git a/src/keys/DeleteDialog.i18n.ts b/src/keys/DeleteDialog.i18n.ts index 838800b9..3b227db4 100644 --- a/src/keys/DeleteDialog.i18n.ts +++ b/src/keys/DeleteDialog.i18n.ts @@ -15,4 +15,18 @@ export const deleteDialogText = messages( keepIt: "This key was generated when the client was connected. Keeping it lets the next connection reuse it, with nothing to reconfigure.", }, + { + "zh-Hant": { + title: (name: string) => `刪除金鑰「${name}」`, + description: "刪除後,使用這把金鑰的用戶端將立即無法連線。可從備份中恢復。", + regenerated: (client: string) => `${client} 再次接管時會重新生成一把`, + keepIt: "這把金鑰是接管時生成的。保留它,下次接管可以直接複用,不必重新配置。", + }, + es: { + title: (name: string) => `Suprímase la clave “${name}”`, + description: "Los clientes que utilizan esta llave pierden acceso inmediatamente. La llave se puede restaurar desde las copias de seguridad.", + regenerated: (client: string) => `${client} obtiene una nueva clave cuando se conecta de nuevo`, + keepIt: "Esta clave fue generada cuando el cliente estaba conectado. Mantenerla permite que la siguiente conexión la reutilice, sin nada que reconfigurar.", + }, + }, ); diff --git a/src/keys/KeyDialog.i18n.ts b/src/keys/KeyDialog.i18n.ts index c853b4d7..22908214 100644 --- a/src/keys/KeyDialog.i18n.ts +++ b/src/keys/KeyDialog.i18n.ts @@ -55,4 +55,58 @@ export const keyDialogText = messages( disabledRejects: "When disabled, every request with this key is rejected", create: "Create", }, + { + "zh-Hant": { + nameRequired: "請填寫名稱", + nameTaken: "這個名稱已被佔用", + patternsRequired: "請至少新增一條規則或選中一個模型", + limitRequired: "請填寫用量上限的數值", + limitsInvalid: "請修正用量上限", + editTitle: "編輯金鑰", + newTitle: "新建金鑰", + newDescription: "新金鑰立即可用。用戶端把它填進請求頭即可連線閘道器。", + lastUsed: (at: string) => `最後使用 ${at}`, + neverUsed: "從未使用", + usage: (n: number) => `24 小時 ${n.toLocaleString()} 次`, + rotate: "更換…", + name: "名稱", + nameHint: "流量與會話裡按它區分用戶端", + routeHint: "指定路由後,這把金鑰獨立於預設路由設定。", + limit: "併發上限", + enabled: "啟用", + defaultAlwaysOn: "預設金鑰不能停用:未接管的用戶端均使用它", + disabledRejects: "停用後,使用這把金鑰的請求一律拒絕", + create: "建立", + }, + ko: { + name: "이름", + enabled: "활성화됨", + }, + es: { + nameRequired: "Se requiere un nombre", + nameTaken: "Este nombre ya está en uso", + patternsRequired: "Se requiere al menos un patrón o un modelo", + limitRequired: "Introduzca una cantidad para cada límite de uso", + limitsInvalid: "Fijar los límites de uso", + editTitle: "Editar la tecla", + newTitle: "Nueva tecla", + newDescription: "La nueva llave funciona inmediatamente. Los clientes la envían en un encabezado de solicitud para conectarse a la puerta de enlace.", + lastUsed: (at: string) => `Última utilización ${at}`, + neverUsed: "Nunca utilizado", + usage: (n: number) => n === 1 ? "1 solicitud en 24 horas" : `${n.toLocaleString()} solicitudes en 24 horas`, + rotate: "Girar…", + name: "Nombre", + namePlaceholder: "Por ejemplo, códice", + nameHint: "Identifica al cliente en Tráfico y Sesiones", + route: "Ruta", + routeHint: "Asignar una ruta para que esta clave sea independiente de la configuración de ruta predeterminada.", + pinRoute: (name: string) => `Usar siempre ${name}`, + limit: "Límite de concurrencia", + noLimit: "Sin límite", + enabled: "Activado", + defaultAlwaysOn: "La clave predeterminada no puede ser desactivada: cada cliente que no está conectado la usa", + disabledRejects: "Cuando está desactivada, se rechaza toda solicitud con esta clave", + create: "Crear", + }, + }, ); diff --git a/src/keys/KeysPage.i18n.tsx b/src/keys/KeysPage.i18n.tsx index 952f0ec8..b98ac426 100644 --- a/src/keys/KeysPage.i18n.tsx +++ b/src/keys/KeysPage.i18n.tsx @@ -48,4 +48,64 @@ export const keysPageText = messages( noKeys: "No keys yet", noKeysHint: "Clients must use a key to connect to the gateway, even from this computer.", }, + { + "zh-Hant": { + keysUnit: (_n: number) => "把金鑰", + active: "活躍", + requests24h: (n: ReactNode) => <>24 小時 {n} 次請求, + noRequests24h: "24 小時內無請求", + cost: "費用", + connectClient: "接管用戶端…", + newKey: "新建金鑰", + copied: (name: string) => `已複製金鑰「${name}」`, + madeDefault: (name: string) => `「${name}」已設為預設金鑰`, + enabledToast: (name: string) => `已啟用「${name}」`, + loadFailed: "無法讀取金鑰", + emptyTitle: "每個用戶端一把金鑰", + emptyDescription: "接管用戶端時為它單獨生成金鑰,流量、路由和併發上限按用戶端區分。", + noKeys: "尚無金鑰", + noKeysHint: "用戶端須使用金鑰連線閘道器,本機連線也不例外。", + }, + ja: { + keysUnit: (_n: number) => "個のキー", + active: "有効", + disabled: "無効", + requests24h: (n: ReactNode) => <>過去 24 時間のリクエスト {n} 件, + noRequests24h: "過去 24 時間にリクエストなし", + cost: "費用", + connectClient: "クライアントに接続…", + newKey: "キーを作成", + copied: (name: string) => `キー「${name}」をコピーしました`, + madeDefault: (name: string) => `「${name}」を既定のキーに設定しました`, + disabledToast: (name: string) => `「${name}」を無効にしました`, + enabledToast: (name: string) => `「${name}」を有効にしました`, + loadFailed: "キーを読み込めませんでした", + emptyTitle: "クライアントごとにキーを発行", + emptyDescription: "クライアントを接続すると専用のキーが作成され、トラフィック、ルート、同時実行上限を個別に管理できます。", + noKeys: "キーがありません", + noKeysHint: "この端末から接続する場合も、ゲートウェイへの接続にはキーが必要です。", + }, + ko: { + cost: "비용", + }, + es: { + keysUnit: (n: number) => (n === 1 ? "tecla" : "teclas"), + active: "activo", + disabled: "desactivado", + requests24h: (n: ReactNode) => <>{n} solicitudes en 24 horas, + noRequests24h: "Ninguna solicitud en 24 horas", + cost: "Coste", + connectClient: "Conectar un cliente…", + newKey: "Nueva tecla", + copied: (name: string) => `Clave “${name}” copiada`, + madeDefault: (name: string) => `“${name}” es ahora la clave predeterminada`, + disabledToast: (name: string) => `«${name}» desactivado`, + enabledToast: (name: string) => `Activado “${name}”`, + loadFailed: "No se pudieron cargar las teclas", + emptyTitle: "Una clave por cliente", + emptyDescription: "Conectar un cliente genera una clave separada para él, por lo que los límites de tráfico, rutas y condiciones se atribuyen al cliente correcto.", + noKeys: "Aún no hay llaves.", + noKeysHint: "Los clientes deben usar una llave para conectarse a la puerta de enlace, incluso desde este ordenador.", + }, + }, ); diff --git a/src/keys/KeysTable.i18n.ts b/src/keys/KeysTable.i18n.ts index eac99ade..a2d80f20 100644 --- a/src/keys/KeysTable.i18n.ts +++ b/src/keys/KeysTable.i18n.ts @@ -47,4 +47,51 @@ export const keysTableText = messages( removeDefault: "Delete… (the default key cannot be deleted)", removeConnected: "Delete… (available once the client is restored)", }, + { + "zh-Hant": { + key: "金鑰", + last24h: "24 小時", + cost: "費用", + default: "預設", + limitReached: "已達上限", + copyKey: "複製金鑰", + edit: "編輯…", + rotate: "更換金鑰…", + makeDefault: "設為預設金鑰", + enable: "啟用", + locate: "在配置檔案中定位", + remove: "刪除…", + removeDefault: "刪除…(預設金鑰不能刪除)", + removeConnected: "刪除…(取消接管後可刪除)", + }, + ko: { + key: "키", + cost: "비용", + actions: "작업", + default: "기본값", + disabled: "비활성화됨", + }, + es: { + key: "Clave", + route: "Ruta", + models: "Modelos permitidos", + last24h: "Las últimas 24 horas", + cost: "Coste", + actions: "Acciones", + default: "Predeterminado", + disabled: "Desactivado", + limitReached: "Límite alcanzado", + actionsFor: (name: string) => `Acciones en relación con ${name}`, + copyKey: "Copiar clave", + edit: "Editar…", + rotate: "Gira la tecla…", + makeDefault: "Establecer como clave predeterminada", + enable: "Activar", + disable: "Desactivar", + locate: "Mostrar en el archivo de configuraciónuración", + remove: "Eliminar…", + removeDefault: "Borrar... (la clave predeterminada no puede ser borrada)", + removeConnected: "Eliminar... (disponible una vez restaurado el cliente)", + }, + }, ); diff --git a/src/keys/LimitsEditor.i18n.ts b/src/keys/LimitsEditor.i18n.ts index 775871de..9c21d41c 100644 --- a/src/keys/LimitsEditor.i18n.ts +++ b/src/keys/LimitsEditor.i18n.ts @@ -56,4 +56,54 @@ export const limitsEditorText = messages( more: (n: number) => `${n} more`, fewer: "Show less", }, + { + "zh-Hant": { + hint: "分鐘、小時上限用滿時請求先排隊等待;天、周、月上限用滿後請求被拒絕,直到重置", + none: "未設上限,用量不限", + add: "新增上限", + everyLabel: (n: number) => `第 ${n} 條上限的週期長度`, + perLabel: (n: number) => `第 ${n} 條上限的週期`, + maxLabel: (n: number) => `第 ${n} 條上限的數值`, + measureLabel: (n: number) => `第 ${n} 條上限的計量`, + cacheReads: "計入快取讀取", + remove: "刪除", + removeLabel: (n: number) => `刪除第 ${n} 條上限`, + badEvery: (hours: boolean, most: number) => `${hours ? "小時" : "分鐘"}數須為 1 到 ${most} 之間的整數`, + required: "請填寫上限", + notPositive: (cost: boolean): string => (cost ? "須為大於 0 的金額" : "須為大於 0 的整數"), + costTooSmall: "金額須至少為 $0.01", + duplicate: "與前面的一條上限重複", + retention: (per: string, need: number, days: number) => `每${per}的上限要求請求記錄至少保留 ${need} 天,當前為 ${days} 天`, + unpriced: (n: number) => `${n} 個可用模型沒有價格,其費用按 0 計入上限:`, + more: (n: number) => `另有 ${n} 個`, + }, + ko: { + remove: "제거", + }, + es: { + title: "Límites de uso", + hint: "Las solicitudes de espera en un minuto completo o un límite de hora; un límite usado día, semana o mes las rechaza hasta que se reinicia", + none: "No hay límites: el uso es ilimitado", + add: "Añadir límite", + atMost: "como máximo", + everyLabel: (n: number) => `Período de duración del límite ${n}`, + perLabel: (n: number) => `Período límite ${n}`, + maxLabel: (n: number) => `Importe del límite ${n}`, + measureLabel: (n: number) => `Medida del límite ${n}`, + cacheReads: "Lectura de caché de cuenta", + remove: "Quitar", + removeLabel: (n: number) => `Eliminar el límite ${n}`, + badEvery: (hours: boolean, most: number) => `${hours ? "Horas" : "Actas"} debe ser un número entero del 1 al ${most}`, + required: "Introduzca un límite", + notPositive: (cost: boolean): string => (cost ? "Debe ser una cantidad superior a 0" : "Debe ser un número entero por encima de 0"), + costTooSmall: "Debe ser por lo menos $0.01", + duplicate: "Igual que un límite superior", + retention: (per: string, need: number, days: number) => `Un límite por ${per} necesidades registros de solicitud mantenidos para al menos ${need === 1 ? "1 día" : `${need} días`}; se mantienen para ${days === 1 ? "1 día" : `${days} días`}`, + unpriced: (n: number) => n === 1 + ? "1 modelo que esta clave puede utilizar no tiene precio y cuenta como $0 hacia el límite:" + : `${n} modelos que esta clave puede utilizar no tienen precio y cuentan como $0 hacia el límite:`, + more: (n: number) => `${n} más`, + fewer: "Mostrar menos", + }, + }, ); diff --git a/src/keys/ModelScope.i18n.ts b/src/keys/ModelScope.i18n.ts index afd63af8..ad8795be 100644 --- a/src/keys/ModelScope.i18n.ts +++ b/src/keys/ModelScope.i18n.ts @@ -77,4 +77,71 @@ export const modelScopeText = messages( lockedHint: (p: string) => `Matched by ${p}; edit that pattern to drop it`, inheritedHint: (m: string) => `Allowed with ${m}; it can be dropped on its own once ${m} is out of scope`, }, + { + "zh-Hant": { + some: "指定範圍", + none: "無", + allNote: (n: number) => `允許請求全部 ${n} 個模型。用戶端列表可按別名設定隱藏原名。`, + allNoteEmpty: "允許請求閘道器提供的全部模型。", + noneNote: "用戶端的模型列表為空。多數用戶端據此選擇模型,實際等同於停用這把金鑰。", + patterns: "通配規則", + patternsHint: "一條規則覆蓋一組模型,上游新增同族模型時自動包含", + patternAdd: "回車新增", + patternHits: (n: number) => `命中 ${n} 個`, + patternHitsUnknown: "尚無清單", + patternRemove: (p: string) => `刪除規則 ${p}`, + noCatalog: "尚未獲取到任何上游的模型清單,因此只能手填規則。在上游頁獲取清單後,此處可直接勾選。", + search: "搜尋模型", + counts: (visible: number, total: number) => `已允許 ${visible} / 共 ${total}`, + hiddenFromClients: "用戶端列表已隱藏", + source: "來源", + picked: "單獨選中", + inherited: (m: string) => `隨 ${m} 放行`, + aliasOf: (models: string[]) => `別名,指向 ${models.join("、")}`, + aliasRule: "範圍裡有某個上游模型,指向它的別名也一起放行;只選別名,不會放行原名。", + rest: (n: number) => `其餘 ${n} 個`, + noMatch: "沒有匹配的模型", + lockedHint: (p: string) => `由 ${p} 命中,取消請修改該規則`, + inheritedHint: (m: string) => `隨 ${m} 放行,${m} 不在範圍裡時才可單獨取消`, + }, + ko: { + none: "없음", + model: "모델", + provider: "업스트림", + }, + es: { + scope: "Modelos permitidos", + all: "Todos", + some: "Específico", + none: "Ninguno", + allNote: (n: number) => n === 1 + ? "Todos los modelos están permitidos: 1 en total. La configuración de Alias puede ocultar los nombres originales de las listas de clientes." + : `Todos los modelos ${n} están permitidos. La configuración de Alias puede ocultar nombres originales de las listas de clientes.`, + allNoteEmpty: "Todos los modelos ofrecidos por la pasarela están permitidos.", + noneNote: "La lista de modelos del cliente está vacía. La mayoría de los clientes eligen un modelo, por lo que esto equivale a desactivar la clave.", + patterns: "Patrones", + patternsHint: "Un patrón cubre un grupo de modelos, incluyendo los que un principio agrega más adelante", + patternPlaceholder: "Por ejemplo, gpt-5*", + patternAdd: "Introduzca para añadir", + patternHits: (n: number) => (n === 1 ? "coincide con 1" : `Coincide con ${n}`), + patternHitsUnknown: "aún no hay catálogo", + patternRemove: (p: string) => `Eliminar el patrón ${p}`, + noCatalog: "No se ha informado de ningún modelo de catálogo todavía, por lo que los patrones tienen que ser tecleados a mano. Una vez que uno se obtiene en la página Upstreams, los modelos se pueden marcar aquí.", + search: "Modelos de búsqueda", + counts: (visible: number, total: number) => `${visible} de ${total} permitido`, + model: "Modelo", + hiddenFromClients: "Oculto de las listas de clientes", + provider: "Proveedor", + source: "Desde", + byPattern: (p: string) => `igualada por ${p}`, + picked: "elegido", + inherited: (m: string) => `permitido con ${m}`, + aliasOf: (models: string[]) => `Alias para ${models.join(", ")}`, + aliasRule: "Conceder un modelo original también permite alias que lo listan. Elegir sólo un alias no permite sus nombres originales.", + rest: (n: number) => (n === 1 ? "1 más" : `${n} más`), + noMatch: "No hay coincidencias de modelos", + lockedHint: (p: string) => `Coincidido con ${p}; editar ese patrón para soltarlo`, + inheritedHint: (m: string) => `Permitido con ${m}; puede ser abandonado por sí solo una vez ${m} está fuera de su ámbito de aplicación`, + }, + }, ); diff --git a/src/keys/RotateDialog.i18n.tsx b/src/keys/RotateDialog.i18n.tsx index 923fcda0..f74581ae 100644 --- a/src/keys/RotateDialog.i18n.tsx +++ b/src/keys/RotateDialog.i18n.tsx @@ -81,4 +81,63 @@ export const rotateDialogText = messages( rotateAndSync: "Rotate and sync", rotate: "Rotate", }, + { + "zh-Hant": { + doneTitle: "金鑰已更換", + synced: (key: ReactNode, clients: string[]) => (<> + {key} + {` 的新金鑰已寫入 ${clients.join("、")} 的配置檔案。`} + ), + shown: (key: ReactNode) => (<> + {key} + {" 的新金鑰如下。"} + ), + newKey: "新金鑰", + restart: (client: string) => `請重新啟動 ${client}`, + stillOld: "正在執行的視窗仍在使用原金鑰,重啟後恢復。", + writeFailed: (client: string) => `未能寫入 ${client} 的配置`, + enterManually: (error: string, client: string) => `${error}。金鑰已更換,請在 ${client} 中手動填寫新金鑰。`, + updateElsewhere: "使用原金鑰的地方需要改成新金鑰,否則將無法連線。", + title: (name: string) => `更換金鑰「${name}」`, + description: (owner: string | null) => owner + ? `原金鑰立即失效。新金鑰會同時寫入 ${owner} 的配置檔案。` + : "原金鑰立即失效。使用原金鑰的地方需要改成新金鑰。", + needsRestart: (client: string) => `${client} 需要重新啟動`, + readsAtStart: (client: string) => `${client} 在啟動時讀取配置,更換後正在執行的視窗會無法連線,需要重新啟動它。`, + isDefault: "這是預設金鑰", + defaultClients: "手動配置了這把金鑰的用戶端都會無法連線,需要逐個改成新金鑰。", + rotateAndSync: "更換並同步", + rotate: "更換", + }, + es: { + doneTitle: "Tecla rotada", + synced: (key: ReactNode, clients: string[]) => (<> + {"La nueva clave para "} + {key} + {` ha sido escrito en la configuración ${andList(clients)} ${clients.length === 1 ? "archivo" : "archivos"}.`} + ), + shown: (key: ReactNode) => (<> + {"La nueva clave para "} + {key} + {" se muestra a continuación."} + ), + newKey: "Nueva tecla", + restart: (client: string) => `Reiniciar ${client}`, + stillOld: "Windows que ya se están ejecutando todavía utilizan la vieja clave. Reiniciar restaura la conexión.", + writeFailed: (client: string) => `No se pudo escribir a la configuración ${client}`, + enterManually: (error: string, client: string) => `${error}. La clave ha sido rotada, por lo que la nueva clave tiene que ser introducida manualmente ${client}.`, + updateElsewhere: "Cualquier cosa que use la vieja llave debe ser cambiada a la nueva llave, o no se conectará.", + done: "Hecho", + title: (name: string) => `Girar la tecla “${name}”`, + description: (owner: string | null) => owner + ? `La clave actual deja de funcionar inmediatamente. La nueva clave también se escribe en el archivo de configuraciónuración ${owner}.` + : "La llave actual deja de funcionar inmediatamente. Cualquier cosa que la use debe ser cambiada a la nueva llave.", + needsRestart: (client: string) => `${client} necesita reiniciar`, + readsAtStart: (client: string) => `${client} lee su configuración al iniciar. Una vez rotada la tecla, las ventanas que ya se están ejecutando no pueden conectarse hasta que ${client} se reinicie.`, + isDefault: "Esta es la clave predeterminada", + defaultClients: "Los clientes configurados manualmente con esta clave no se conectarán, y cada uno debe ser cambiado a la nueva clave.", + rotateAndSync: "Rotar y sincronizar", + rotate: "Rotar", + }, + }, ); diff --git a/src/keys/labels.i18n.ts b/src/keys/labels.i18n.ts index 3bb5da69..a8ba6387 100644 --- a/src/keys/labels.i18n.ts +++ b/src/keys/labels.i18n.ts @@ -30,4 +30,34 @@ export const labelsText = messages( defaultRoute: "Default", defaultNamed: (route: string) => `Default (${route})`, }, + { + "zh-Hant": { + takeoverOn: (client: string) => `接管 ${client} 時生成。接管期間不能刪除。`, + takeoverOff: (client: string) => `為 ${client} 生成。${client} 當前未接管,這把金鑰保留,接管時直接使用。`, + manualFor: (client: string) => `手動配置 · ${client}`, + manualTip: (client: string) => `為 ${client} 生成,按手動配置的步驟填入 ${client}。`, + noModels: "無", + models: (n: number) => `${n} 個模型`, + rules: (n: number) => `${n} 條規則`, + defaultRoute: "預設", + defaultNamed: (route: string) => `預設(${route})`, + }, + ko: { + noModels: "없음", + defaultRoute: "기본값", + }, + es: { + takeover: (client: string) => `Conectado · ${client}`, + takeoverOn: (client: string) => `Generado cuando ${client} estaba conectado. No se puede eliminar mientras dure la conexión.`, + takeoverOff: (client: string) => `Generado para ${client}. ${client} no está conectado en este momento; la clave se mantiene y se utiliza cuando está.`, + manualFor: (client: string) => `Montado a mano · ${client}`, + manualTip: (client: string) => `Generado para ${client}, que debe introducirse en ${client} siguiendo los pasos de configuración.`, + allModels: "Todos", + noModels: "Ninguno", + models: (n: number) => (n === 1 ? "1 modelo" : `${n} modelos`), + rules: (n: number) => (n === 1 ? "1 patrón" : `${n} patrones`), + defaultRoute: "Predeterminado", + defaultNamed: (route: string) => `Predeterminado ${route}`, + }, + }, ); diff --git a/src/keys/limits.i18n.ts b/src/keys/limits.i18n.ts index f979e5cd..f49ff122 100644 --- a/src/keys/limits.i18n.ts +++ b/src/keys/limits.i18n.ts @@ -64,4 +64,57 @@ export const limitsText = messages( ? `${amount} tokens per ${per}${cacheReads ? " (cache reads included)" : ""}` : `${amount} per ${per}`, }, + { + "zh-Hant": { + per: ({ minute: "分鐘", hour: "小時", day: "天", week: "周", month: "月" }), + unit: (per: LimitPer, _n: number): string => ({ minute: "分鐘", hour: "小時", day: "天", week: "周", month: "月" })[per], + span: (per: LimitPer, n: number): string => (n > 1 ? ` ${n} ${({ minute: "分鐘", hour: "小時", day: "天", week: "周", month: "月" })[per]}` : ({ minute: "分鐘", hour: "小時", day: "天", week: "周", month: "月" })[per]), + measure: { requests: "次請求", tokens: "token", cost: "費用 (USD)" } satisfies Record, + period: { + minute: "最近一分鐘", + hour: "最近一小時", + day: "今天", + week: "本週", + month: "本月", + } satisfies Record, + reached: "已達上限", + phrase: (per: string, amount: string, measure: LimitMeasure, cacheReads: boolean) => measure === "requests" + ? `每${per} ${amount} 次請求` + : measure === "tokens" + ? `每${per} ${amount} token${cacheReads ? "(含快取讀取)" : ""}` + : `每${per} ${amount} 費用`, + }, + ko: { + period: { + minute: "Last minute", + hour: "Last hour", + day: "오늘", + week: "This week", + month: "This month", + }, + }, + es: { + per: ({ minute: "minuto", hour: "hora", day: "día", week: "semana", month: "mes" }), + unit: (per: LimitPer, n: number): string => (n > 1 ? `${({ minute: "minuto", hour: "hora", day: "día", week: "semana", month: "mes" })[per]}s` : ({ minute: "minuto", hour: "hora", day: "día", week: "semana", month: "mes" })[per]), + span: (per: LimitPer, n: number): string => (n > 1 ? `${n} ${({ minute: "minuto", hour: "hora", day: "día", week: "semana", month: "mes" })[per]}s` : ({ minute: "minuto", hour: "hora", day: "día", week: "semana", month: "mes" })[per]), + lastN: (span: string) => `Último ${span}`, + measure: { requests: "solicitudes", tokens: "tokens", cost: "USD" }, + period: { + minute: "Último minuto", + hour: "Última hora", + day: "Hoy", + week: "Esta semana", + month: "Este mes", + }, + resets: (at: string) => `reinicia ${at}`, + at: (hm: string) => `en ${hm}`, + on: (date: string, hm: string) => `${date} al ${hm}`, + reached: "Límite alcanzado", + phrase: (per: string, amount: string, measure: LimitMeasure, cacheReads: boolean) => measure === "requests" + ? `${amount} solicitudes por ${per}` + : measure === "tokens" + ? `${amount} fichas por ${per}${cacheReads ? " (Caché lee incluido)" : ""}` + : `${amount} per ${per}`, + }, + }, ); diff --git a/src/keys/parts.i18n.ts b/src/keys/parts.i18n.ts index f29cc12f..2be0fc29 100644 --- a/src/keys/parts.i18n.ts +++ b/src/keys/parts.i18n.ts @@ -16,4 +16,21 @@ export const partsText = messages( neverUsed: "Never used", inProgress: "In progress", }, + { + "zh-Hant": { + neverUsed: "從未使用", + inProgress: "請求中", + }, + ko: { + inProgress: "진행 중", + }, + es: { + requests: (n: number) => { + const v = Math.round(n); + return v === 1 ? "1 solicitud" : `${v.toLocaleString()} solicitudes`; + }, + neverUsed: "Nunca utilizado", + inProgress: "En curso", + }, + }, ); diff --git a/src/labels.i18n.ts b/src/labels.i18n.ts index 837f95d1..df4668c4 100644 --- a/src/labels.i18n.ts +++ b/src/labels.i18n.ts @@ -255,4 +255,238 @@ export const labelsText = messages( "Takes effect after the client restarts; clients that read their configuration from environment variables also need the terminal reopened.", }, }, + { + "zh-Hant": { + groupKinds: { + fallback: "按順序", + select: "手動選擇", + "load-balance": "輪詢", + "url-test": "延遲最低", + cheapest: "費用最低", + }, + balanceBy: { + weights: "按比例", + latency: "按速度", + health: "按穩定性", + "latency-health": "按速度和穩定性", + }, + probes: { + health_check: { + label: "連通性檢查", + what: "用戶端啟動時傳送的空請求,用於確認閘道器可達。", + }, + warmup: { label: "預熱", what: "正文為 Warmup 的請求,用於預熱連線與快取。" }, + titling: { label: "生成標題", what: "為會話生成標題。設為本地應答時,所有會話使用同一標題。" }, + topic_detect: { + label: "話題識別", + what: "判斷本輪對話的話題,用戶端據此決定是否切換上下文。", + }, + suggestion: { label: "輸入建議", what: "輸入框中顯示的補全建議。" }, + }, + flags: { + cache: { yes: "帶快取", no: "不帶快取" }, + tools: { yes: "帶工具", no: "不帶工具" }, + image: { yes: "帶圖片", no: "不帶圖片" }, + thinking: { yes: "開啟擴充套件思考", no: "未開啟擴充套件思考" }, + stream: { yes: "流式", no: "非流式" }, + }, + conditionNames: { + model: "模型", + client: "金鑰", + dialect: "用戶端格式", + input_tokens: "輸入 token", + max_tokens: "max_tokens", + tool_count: "工具數", + intent: "輔助請求", + provider_would_be: "選定上游", + time: "時段", + }, + anyProbe: "任一輔助請求", + userRequest: "使用者請求", + notSet: "未設定", + flagMismatch: (want: string, got: string) => `要求${want},實際為${got}`, + countMismatch: (name: string, want: string, got: string) => `要求${name} ${want},實際為 ${got}`, + valueMismatch: (name: string, want: string, got: string) => `要求${name}為 ${want},實際為 ${got}`, + setModel: (model: string) => `模型改為 ${model},prompt cache 整體失效`, + onlyAtSessionStart: "以上改寫僅在新會話開始時應用", + setField: (field: string, value: string) => `${field} 改為 ${value}`, + reasoningOff: "關閉推理", + effort: { + rule: (asked: string, sent: string) => `推理強度 ${asked} → ${sent}:規則改寫`, + ruleRemoved: "已去掉推理強度:規則改寫", + ruleOff: "已關閉推理:規則改寫", + rejected: (asked: string, sent: string) => `推理強度 ${asked} 被上游拒收,已改用 ${sent} 重發`, + rejectedRemoved: (asked: string) => `推理強度 ${asked} 被上游拒收,已去掉後重發`, + rejectedOff: "關閉推理(none)被上游拒收,已去掉該欄位後重發", + rejectedOffTo: (sent: string) => `關閉推理(none)被上游拒收,已改用 ${sent} 重發`, + remembered: (asked: string, sent: string) => `推理強度 ${asked} → ${sent}:該模型不支援 ${asked}`, + rememberedRemoved: (asked: string) => `已去掉推理強度:該模型不支援 ${asked}`, + rememberedOff: "已去掉推理強度:該模型不支援關閉推理(none)", + rememberedOffTo: (sent: string) => `推理強度 none → ${sent}:該模型不支援關閉推理`, + }, + rejected: (status: number) => `${status} · 請求被上游拒絕`, + rateLimited: "429 · 速率限制", + upstreamError: (status: number | string) => `${status} · 上游錯誤`, + noResponse: "未收到回應", + idleTimeout: "無回應超時", + idleTimeoutSecs: (secs: string) => `無回應超時 · ${secs} 秒`, + aborted: "手動中止", + deniedHop: (rule: string) => `未傳送 · 被規則「${rule}」拒絕`, + notSent: { + denied: "規則拒絕", + unavailable: "無可用上游", + model: "模型不可用", + unrouted: "未能路由", + limited: "用量上限", + busy: "併發已滿", + throttled: "上游速率限制中", + full: "上游用量已滿", + timeout: "等待超時", + }, + quote: { + free: "不計費。", + estimate: (amount: string) => `預估費用約 ${amount}。`, + unpriced: (model: string) => `無法計價:${model} 不在價目表中。`, + }, + stages: { + syntax: "語法", + schema: "欄位", + semantics: "語義", + }, + takesEffect: { + immediately: "下一個請求即使用新配置。", + onRestart: "重新啟動用戶端後生效;透過環境變數讀取配置的用戶端需重新開啟終端。", + }, + }, + ko: { + allUpstreams: "모든 업스트림", + conditionNames: { + model: "모델", + client: "키", + dialect: "Client format", + input_tokens: "Input tokens", + max_tokens: "max_tokens", + tool_count: "Tool count", + intent: "Auxiliary request", + provider_would_be: "Selected upstream", + time: "시간", + }, + served: "성공", + }, + es: { + groupKinds: { + fallback: "En orden", + select: "Manual", + "load-balance": "Robin redondo", + "url-test": "Latencia más baja", + cheapest: "Costo más bajo", + }, + balanceBy: { + weights: "Por razón", + latency: "Por velocidad", + health: "Por fiabilidad", + "latency-health": "Por velocidad y fiabilidad", + }, + allUpstreams: "Todos los proveedores", + probes: { + health_check: { + label: "Chequeo médico", + what: "Una petición vacía enviada cuando el cliente comienza, para confirmar que la puerta de enlace es accesible.", + }, + warmup: { + label: "Calentamiento", + what: "Una solicitud con Warmup como su cuerpo, enviada para calentar la conexión y el caché.", + }, + titling: { + label: "Generación de títulos", + what: "Genera un título para la sesión. Cuando se establece en “Respuesta local”, cada sesión obtiene el mismo título.", + }, + topic_detect: { + label: "Detección de temas", + what: "Detecta el tema del turno actual; el cliente lo utiliza para decidir si cambiar de contexto.", + }, + suggestion: { label: "Sugerencias", what: "Sugerencias de finalización mostradas en el cuadro de entrada." }, + }, + flags: { + cache: { yes: "Con caché", no: "Sin caché" }, + tools: { yes: "Con herramientas", no: "Sin herramientas" }, + image: { yes: "Con imágenes", no: "Sin imágenes" }, + thinking: { yes: "Pensamiento extendido sobre", no: "Pensamiento extendido off" }, + stream: { yes: "Streaming", no: "No incorporación de datos" }, + }, + conditionNames: { + model: "Modelo", + client: "Clave", + dialect: "Formato del cliente", + input_tokens: "tokens de entrada", + max_tokens: "max_tokens", + tool_count: "Conteo de herramientas", + intent: "Solicitud complementaria", + provider_would_be: "Selección de la fase anterior", + time: "Hora", + }, + anyProbe: "Cualquier solicitud auxiliar", + or: " o ", + userRequest: "solicitud del usuario", + notSet: "no establecido", + flagMismatch: (want: string, got: string) => `Requiere “${want}”; actual: “${got}”`, + countMismatch: (name: string, want: string, got: string) => `${name} debe ser ${want}; real: ${got}`, + valueMismatch: (name: string, want: string, got: string) => `${name} debe ser ${want}; real: ${got}`, + setModel: (model: string) => `Modelo establecido en ${model}; toda la caché del prompt está invalidada`, + onlyAtSessionStart: "Las reescrituras anteriores solo se aplican cuando se inicia una nueva sesión", + setField: (field: string, value: string) => `${field} Se fija en ${value}`, + reasoningLevel: (level: string) => `Razonamiento ${level}`, + reasoningOff: "Razonamiento", + effort: { + rule: (asked: string, sent: string) => `Esfuerzo de razonamiento ${asked} → ${sent}: reescrito por una regla`, + ruleRemoved: "Retirada del esfuerzo de razonamiento: reescrita por una regla", + ruleOff: "Razonamiento desactivado: reescrito por una regla", + rejected: (asked: string, sent: string) => `El esfuerzo de razonamiento ${asked} fue rechazado por la parte anterior; se resiente con ${sent}`, + rejectedRemoved: (asked: string) => `El esfuerzo de razonamiento ${asked} fue rechazado por el río; resiente sin él`, + rejectedOff: "Desactivar el razonamiento (ninguno) fue rechazado por la corriente; resentir sin el campo", + rejectedOffTo: (sent: string) => `Desactivar el razonamiento (ninguno) fue rechazado por la corriente; resentirse con ${sent}`, + remembered: (asked: string, sent: string) => `Esfuerzo de razonamiento ${asked} → ${sent}: el modelo no admite ${asked}`, + rememberedRemoved: (asked: string) => `Retirada del esfuerzo de razonamiento: el modelo no admite ${asked}`, + rememberedOff: "Retirada del esfuerzo de razonamiento: el modelo no apoya el desactivamiento del razonamiento (ninguno)", + rememberedOffTo: (sent: string) => `Esfuerzo de razonamiento ninguno → ${sent}: el modelo no apoya el desactivamiento del razonamiento`, + }, + served: "Correcto", + servedStatus: (status: number) => `Éxito · ${status}`, + rejected: (status: number) => `${status} · Rechazada por la corriente`, + rateLimited: "429 Tasa limitada", + upstreamError: (status: number | string) => `${status} · Error ascendente`, + noResponse: "No se recibió respuesta", + estimated: "Estimación local", + estimatedAfter: (status: number) => `${status} · Estimación local`, + idleTimeout: "Sin respuesta", + idleTimeoutSecs: (secs: string) => `Sin respuesta · ${secs} s`, + aborted: "Abortado", + deniedHop: (rule: string) => `No enviado · negado por la regla “${rule}”`, + notSent: { + denied: "Denegado", + unavailable: "Sin del proveedor", + model: "Modelo no disponible", + unrouted: "Sin enrutar", + limited: "Límite de utilización", + busy: "A capacidad", + throttled: "Tasa limitada", + full: "Límite del flujo ascendente", + timeout: "Tiempo de espera fuera", + }, + quote: { + free: "Libre.", + estimate: (amount: string) => `Costo estimado: alrededor de ${amount}.`, + unpriced: (model: string) => `Sin precio: ${model} no figura en la hoja de precios.`, + }, + stages: { + syntax: "Sintaxis", + schema: "Campo", + semantics: "Semántico", + }, + takesEffect: { + immediately: "La siguiente petición utiliza la nueva configuración.", + onRestart: "Toma efecto después de que el cliente se reinicie; los clientes que leen su configuración desde variables de entorno también necesitan reabrir el terminal.", + }, + }, + }, ); diff --git a/src/launch/LaunchScreen.i18n.ts b/src/launch/LaunchScreen.i18n.ts index 477c58e1..56bb8641 100644 --- a/src/launch/LaunchScreen.i18n.ts +++ b/src/launch/LaunchScreen.i18n.ts @@ -14,4 +14,30 @@ export const launchText = messages( slow: (secs: number) => `Starting is taking longer than usual: ${secs} s so far`, readFailed: "The gateway status could not be read", }, + { + "zh-Hant": { + starting: "正在啟動閘道器", + loading: "正在載入資料", + slow: (secs: number) => `啟動耗時較長,已用 ${secs} 秒`, + readFailed: "無法讀取閘道器狀態", + }, + ja: { + starting: "ゲートウェイを起動しています", + loading: "データを読み込んでいます", + slow: (secs: number) => `起動に時間がかかっています(${secs} 秒経過)`, + readFailed: "ゲートウェイの状態を取得できませんでした", + }, + ko: { + starting: "게이트웨이 시작 중", + loading: "데이터 불러오는 중", + slow: (secs: number) => `시작에 시간이 오래 걸리고 있습니다(${secs}초 경과).`, + readFailed: "게이트웨이 상태를 읽을 수 없습니다.", + }, + es: { + starting: "Iniciando la puerta de enlace", + loading: "Cargando datos", + slow: (secs: number) => `El inicio está tardando más de lo habitual (${secs} s).`, + readFailed: "No se pudo leer el estado de la puerta de enlace.", + }, + }, ); diff --git a/src/launch/trouble.exited.test.ts b/src/launch/trouble.exited.test.ts index 05074a8f..1b28616c 100644 --- a/src/launch/trouble.exited.test.ts +++ b/src/launch/trouble.exited.test.ts @@ -3,9 +3,9 @@ import { trouble } from "./trouble"; describe("trouble: core exited in safe mode too", () => { it("says it cannot start and gives core's own words, with a retry", () => { - const t = trouble("exited:已有 twcore 实例正在运行(pid 7)。", 0); + const t = trouble("exited:A twcore instance is already running (PID 7).", 0); expect(t.what).toBe("core 无法启动"); - expect(t.next).toBe("已有 twcore 实例正在运行(pid 7)。"); + expect(t.next).toBe("A twcore instance is already running (PID 7)."); expect(t.retry).toBe(true); expect(t.bad).toBe(true); }); diff --git a/src/launch/trouble.i18n.ts b/src/launch/trouble.i18n.ts index d46df83f..f3f30557 100644 --- a/src/launch/trouble.i18n.ts +++ b/src/launch/trouble.i18n.ts @@ -34,4 +34,70 @@ export const troubleText = messages( attempt: (n: number) => `Attempt ${n}`, restart: "Restart", }, + { + "zh-Hant": { + missing: "未找到 core 程式", + failed: "core 程式無法執行", + exited: "core 無法啟動", + restarting: (attempt: string) => `core 已退出,正在進行第 ${attempt} 次重啟`, + retryIn: (secs: number) => `${secs} 秒後重試`, + safeMode: "安全模式:閘道器未執行", + safeModeNext: "配置、備份與還原接管仍可使用。安全模式通常由配置錯誤導致,請檢查配置檔案。", + stopped: "core 未執行", + stoppedNext: "點選「重新啟動」以啟動 core", + starting: "正在啟動 core", + wait: "請稍候", + connecting: "正在重新連線 core", + attempt: (n: number) => `第 ${n} 次嘗試`, + restart: "重新啟動", + }, + ja: { + missing: "core プログラムが見つかりません", + failed: "core プログラムを実行できませんでした", + exited: "core を起動できませんでした", + restarting: (attempt: string) => `core が終了しました。再起動中(${attempt} 回目)`, + retryIn: (secs: number) => `${secs} 秒後に再試行します`, + safeMode: "セーフモード:ゲートウェイは停止中です", + safeModeNext: "設定の編集、バックアップ、クライアント設定の復元は利用できます。設定ファイルにエラーがないか確認してください。", + stopped: "core は停止中です", + stoppedNext: "「再起動」をクリックして core を起動してください", + starting: "core を起動しています", + wait: "しばらくお待ちください", + connecting: "core に再接続しています", + attempt: (n: number) => `${n} 回目の試行`, + restart: "再起動", + }, + ko: { + missing: "core 실행 파일을 찾을 수 없습니다.", + failed: "core를 실행할 수 없습니다.", + exited: "core를 시작할 수 없습니다.", + restarting: (attempt: string) => `core가 종료되었습니다. 다시 시작 중(${attempt}번째 시도).`, + retryIn: (secs: number) => `${secs}초 후 다시 시도합니다.`, + safeMode: "안전 모드: 게이트웨이가 중지되었습니다.", + stopped: "core가 중지되어 있습니다.", + stoppedNext: "core를 시작하려면 다시 시작을 클릭하세요.", + starting: "core 시작 중", + wait: "잠시 기다려 주세요.", + connecting: "core에 다시 연결 중", + attempt: (n: number) => `${n}번째 시도`, + restart: "다시 시작", + safeModeNext: "설정 편집, 백업, 클라이언트 복원을 계속 사용할 수 있습니다. 안전 모드는 보통 설정 오류로 시작됩니다. 설정 파일을 확인하세요.", + }, + es: { + missing: "No se encontró el ejecutable de core.", + failed: "No se pudo ejecutar core.", + exited: "No se pudo iniciar core.", + restarting: (attempt: string) => `core se cerró. Reiniciando (intento ${attempt}).`, + retryIn: (secs: number) => `Se volverá a intentar en ${secs} s.`, + safeMode: "Modo seguro: la puerta de enlace está detenida.", + safeModeNext: "La edición de configuración, copias de seguridad y restauración de clientes permanecen disponibles. El modo seguro suele ser causado por un error de configuración; compruebe el archivo de configuraciónuración.", + stopped: "core está detenido.", + stoppedNext: "Pulsa Reiniciar para iniciar core.", + starting: "Iniciando core", + wait: "Esto puede tardar un momento.", + connecting: "Reconectando con core", + attempt: (n: number) => `Intento ${n}`, + restart: "Reiniciar", + }, + }, ); diff --git a/src/mcp/McpPage.i18n.tsx b/src/mcp/McpPage.i18n.tsx index d3275d63..9b73ef63 100644 --- a/src/mcp/McpPage.i18n.tsx +++ b/src/mcp/McpPage.i18n.tsx @@ -203,4 +203,247 @@ export const mcpText = messages( reportOnly: "Report only; no file is changed. Open the path above to review it before taking action.", viewDetail: "View details", }, + { + "zh-Hant": { + tabServers: "伺服器", + tabExtensions: "技能與鉤子", + tabFindings: "發現", + rescan: "重新掃描", + loadFailed: "掃描失敗", + levelCount: { high: "項高風險", medium: "項中風險", low: "項低風險" } as Record, + clean: "未發現問題", + unreadableCount: "個檔案無法讀取", + scannedAt: (files: number, time: string) => `已掃描 ${files} 個檔案 · ${time}`, + newDot: "有新發現", + server: "伺服器", + noMcp: "未配置 MCP 伺服器", + noClients: "未檢測到支援 MCP 的用戶端", + noClientsHint: "用戶端裝在別處或改過配置目錄時,可以指定它的配置位置。", + absent: (names: string[]) => `未檢測到:${names.join("、")}`, + noMcpHint: "在用戶端中新增 MCP 伺服器後,各用戶端的配置將並列在此。", + enabled: "已啟用", + legendNote: "點選格子複製或移除,寫入前顯示改動。", + cannotWrite: "此用戶端不支援寫入", + removeFrom: (client: string) => `從 ${client} 移除`, + copyFrom: (from: string, to: string) => `從 ${from} 複製到 ${to}`, + copyTo: (to: string) => `複製到 ${to}`, + noSource: "沒有可複製的來源", + disabledTip: "配置中為 enabled: false,列出但不會被載入", + differsTip: "同名伺服器在各用戶端中的配置不同,點選並排檢視", + readsEnv: (keys: string[]) => `讀取 ${keys.join("、")}`, + remote: "遠端", + thirdPartyTip: "上下文將傳送至該地址", + viewConfig: "檢視配置", + configuredIn: (n: number) => `已在 ${n} 個用戶端中配置。`, + compareDesc: "各用戶端中的配置不一致,不一致的欄位已標出。", + env: "環境變數", + noEnv: "(無)", + unify: "如需統一:在矩陣中選擇要保留的配置,複製到其他用戶端。寫入前將顯示改動。", + copyTitle: (name: string, to: string) => `將 ${name} 複製到 ${to}`, + removeTitle: (name: string, from: string) => `從 ${from} 移除 ${name}`, + modifies: "將修改", + noop: "配置已是目標狀態,無需修改。", + stale: "目標檔案在檢視改動期間已被修改,未寫入任何內容。以下改動已按當前內容重新計算,核對後請再次確認。", + backup: "寫入前將完整備份原檔案,除此項外不做任何改動。", + envCopied: "env 中可能含有金鑰,將一併複製。", + applyFailed: "未能寫入", + hooks: "鉤子", + hooksNote: "鉤子在工具呼叫前後直接執行命令,無需模型參與即可獲得執行許可權。", + hooksRunByGrok: (note: string) => `${note}Grok Build 預設還會執行 Claude Code 與 Cursor 的鉤子。`, + skillsNote: "僅列出,不支援跨用戶端複製:技能的跨用戶端格式尚無通行標準。", + client: "用戶端", + sharedSkills: "共用目錄", + name: "名稱", + allowedTools: "允許的工具", + level: "級別", + noHooks: "未配置鉤子", + noSkills: "未安裝技能", + copyCommand: "複製命令", + copyPath: "複製路徑", + changePath: "更改路徑…", + changePathOf: (name: string) => `更改 ${name} 的路徑…`, + viewFinding: "檢視發現", + newFindings: (n: number, em: Em) => <>{em(`${n} 項新發現`)},此前掃描時不存在。, + markRead: "標為已讀", + scope: "掃描範圍:用戶端配置、技能、鉤子、斜槓命令、subagent 與專案指令。", + unreadable: (n: number) => `${n} 個檔案無法讀取,本次未掃描`, + finding: "發現", + noIssues: "未發現問題", + checked: "已檢查隱藏字元、提示注入、危險命令與過寬許可權四類問題。", + reportOnly: "僅報告,不修改任何檔案。請開啟上述路徑檢視後再做處理。", + viewDetail: "檢視詳情", + }, + ja: { + tabServers: "サーバー", + tabExtensions: "スキルとフック", + tabFindings: "検出結果", + rescan: "再スキャン", + loadFailed: "スキャンに失敗しました", + levelCount: { high: "件(高リスク)", medium: "件(中リスク)", low: "件(低リスク)" }, + clean: "問題は見つかりませんでした", + unreadableCount: "個のファイルを読み取り不可", + scannedAt: (files: number, time: string) => `${files} 個のファイルをスキャン · ${time}`, + newDot: "新しい検出結果があります", + server: "サーバー", + noMcp: "MCP サーバーが設定されていません", + noClients: "MCP 対応のクライアントが見つかりませんでした", + noClientsHint: "クライアントのインストール先や設定ディレクトリを変更した場合は、設定ファイルの場所を指定できます。", + absent: (names: string[]) => `見つかりませんでした:${names.join("、")}`, + locate: "場所を指定…", + noMcpHint: "クライアントに MCP サーバーを追加すると、設定がここに並んで表示されます。", + enabled: "有効", + disabled: "無効", + none: "未設定", + legendNote: "セルをクリックしてコピーまたは削除します。保存前に変更内容を確認できます。", + cannotWrite: "このクライアントの設定は書き込めません", + removeFrom: (client: string) => `${client} から削除`, + copyFrom: (from: string, to: string) => `${from} から ${to} にコピー`, + copyTo: (to: string) => `${to} にコピー`, + noSource: "コピー元がありません", + disabledTip: "設定が enabled: false のため、一覧に表示されますが読み込まれません", + differs: "設定が異なります", + differsTip: "同じ名前のサーバーでもクライアントごとに設定が異なります。クリックして比較できます。", + readsEnv: (keys: string[]) => `参照:${keys.join("、")}`, + remote: "リモート", + thirdParty: "サードパーティー", + thirdPartyTip: "このアドレスにコンテキストを送信します", + cellLabel: (server: string, client: string, state: string) => `${server} · ${client}:${state}`, + viewConfig: "設定を表示", + actionsFor: (name: string) => `${name} の操作`, + configuredIn: (n: number) => `${n} 件のクライアントに設定されています。`, + compareDesc: "クライアントによって値が異なる項目を強調表示しています。", + env: "環境変数", + noEnv: "(なし)", + unify: "設定を統一するには、一覧で残す設定を選び、ほかのクライアントにコピーしてください。保存前に変更内容を確認できます。", + copyTitle: (name: string, to: string) => `${name} を ${to} にコピー`, + removeTitle: (name: string, from: string) => `${from} から ${name} を削除`, + modifies: "変更するファイル", + noop: "設定はすでに目的の状態です。", + stale: "確認中に対象ファイルが変わったため、書き込みを中止しました。最新の内容で再計算した変更を確認してください。", + backup: "保存前に元のファイル全体をバックアップします。変更は表示されている項目に限られます。", + envCopied: "env もコピーします。機密情報が含まれる場合があります。", + applyFailed: "書き込めませんでした", + hooks: "フック", + hooksNote: "フックはツール呼び出しの前後に、モデルを介さずコマンドを実行します。", + hooksRunByGrok: (note: string) => `${note}Grok Build は既定で Claude Code と Cursor のフックも実行します。`, + skills: "スキル", + skillsNote: "スキルは一覧で確認できます。クライアント間の共通形式がないため、コピーには対応していません。", + client: "クライアント", + sharedSkills: "共有フォルダー", + event: "イベント", + command: "コマンド", + name: "名前", + allowedTools: "許可するツール", + level: "レベル", + noHooks: "フックが設定されていません", + noSkills: "スキルがインストールされていません", + listSep: "、", + copyCommand: "コマンドをコピー", + copyPath: "パスをコピー", + changePath: "パスを変更…", + changePathOf: (name: string) => `${name} のパスを変更…`, + viewFinding: "検出結果を表示", + newFindings: (n: number, em: Em) => <>前回のスキャン以降に {em(`${n} 件の新しい問題`)}が見つかりました。, + markRead: "既読にする", + scope: "対象:クライアント設定、スキル、フック、スラッシュコマンド、サブエージェント、プロジェクト指示。", + unreadable: (n: number) => `${n} 個のファイルを読み取れなかったため、スキャンできませんでした`, + finding: "検出結果", + levels: { high: "高", medium: "中", low: "低" }, + isNew: "新規", + noIssues: "問題は見つかりませんでした", + checked: "不可視文字、プロンプトインジェクション、危険なコマンド、過剰な権限を確認しました。", + reportOnly: "変更は適用されていません。対応する前に、上記のパスのファイルを確認してください。", + viewDetail: "詳細を表示", + }, + ko: { + server: "서버", + enabled: "활성화됨", + disabled: "비활성화됨", + client: "클라이언트", + name: "이름", + copyCommand: "명령 복사", + markRead: "읽음으로 표시", + }, + es: { + tabServers: "Servidores", + tabExtensions: "Capacidades y ganchos", + tabFindings: "Conclusiones", + loadFailed: "Falló el escaneo", + levelCount: { high: "alta", medium: "medio", low: "baja" }, + clean: "No se encontraron problemas", + unreadableCount: "ilegible", + scannedAt: (files: number, time: string) => `${plural(files, "archivo", "archivos")} escaneado · ${time}`, + newDot: "Nuevas conclusiones", + server: "Servidor", + noMcp: "No hay servidores MCP", + noClients: "No se han encontrado clientes con soporte MCP", + noClientsHint: "Un cliente instalado en otro lugar, o con su directorio de configuración movido, se puede dar su ubicación.", + absent: (names: string[]) => `No detectada: ${names.join(", ")}`, + locate: "Elegir ubicación…", + noMcpHint: "Una vez que se agregan servidores MCP en un cliente, la configuración de cada cliente se lista aquí lado a lado.", + enabled: "Activado", + disabled: "Desactivado", + none: "No configurado", + legendNote: "Haga clic en una celda para copiar o eliminar; el cambio se muestra antes de que se escriba nada.", + cannotWrite: "Escribir a este cliente no es compatible", + removeFrom: (client: string) => `Eliminar de ${client}`, + copyFrom: (from: string, to: string) => `Copia de ${from} a ${to}`, + copyTo: (to: string) => `Copiar a ${to}`, + noSource: "No hay fuente para copiar desde", + disabledTip: "Establecer a activado: false en la configuración; enlistado pero no cargado", + differs: "Diferencias", + differsTip: "Este servidor está configurado de manera diferente entre los clientes. Haga clic para compararlos lado a lado.", + readsEnv: (keys: string[]) => `Lee ${keys.join(", ")}`, + remote: "Remoto", + thirdParty: "Terceros", + thirdPartyTip: "El contexto se envía a esta dirección", + viewConfig: "Configuración de vista", + actionsFor: (name: string) => `Acciones en relación con ${name}`, + configuredIn: (n: number) => `Configurado en ${plural(n, "cliente", "clientes")}.`, + compareDesc: "La configuración difiere entre los clientes; los campos que difieren se resaltan.", + env: "Variables ambientales", + noEnv: "(ninguno)", + unify: "Para hacerlos consistentes, elija la configuración para guardar en la matriz y copiarla a los otros clientes. El cambio se muestra antes de que se escriba nada.", + copyTitle: (name: string, to: string) => `Copia ${name} a ${to}`, + removeTitle: (name: string, from: string) => `Eliminar ${name} de ${from}`, + modifies: "Modifica", + noop: "La configuración ya está en el estado de destino; nada necesita cambiar.", + stale: "El archivo de destino cambió mientras el cambio estaba siendo revisado, por lo que no se escribió nada. El cambio de abajo fue recomputado desde el archivo actual; revíselo y confirme de nuevo.", + backup: "El archivo original está respaldado en su totalidad antes de escribir, y nada más se cambia. ", + envCopied: "El campo env puede contener secretos y también se copia.", + applyFailed: "No está escrito", + hooks: "Ganchos", + hooksNote: "Los ganchos ejecutan comandos directamente antes y después de las llamadas de la herramienta, ganando derechos de ejecución sin involucrar el modelo.", + hooksRunByGrok: (note: string) => `${note} Grok Build también ejecuta los ganchos de Claude Code y Cursor por defecto.`, + skills: "Competencias", + skillsNote: "No se admite copiar entre clientes: todavía no hay un formato común para las habilidades de los clientes.", + client: "Cliente", + sharedSkills: "Carpeta compartida", + event: "Evento", + command: "Comando", + name: "Nombre", + allowedTools: "Herramientas permitidas", + level: "Nivel", + noHooks: "Sin ganchos", + noSkills: "Sin habilidades", + copyCommand: "Copiar comando", + copyPath: "Copiar ruta", + changePath: "Cambiar la ruta…", + changePathOf: (name: string) => `Cambiar la ruta de ${name}…`, + viewFinding: "Ver la búsqueda", + newFindings: (n: number, em: Em) => (<> + {em(n === 1 ? "1 nuevo hallazgo" : `${n} nuevas conclusiones`)} que no existía en el escaneo anterior. + ), + markRead: "Marcar como leído", + scope: "Escaneado: configuración del cliente, habilidades, ganchos, comandos de barra, subagentes e instrucciones de proyecto.", + unreadable: (n: number) => n === 1 ? "1 archivo no se pudo leer y no fue escaneado" : `${n} los archivos no se pudieron leer y no fueron escaneados`, + finding: "Conclusiones", + levels: { high: "Alta", medium: "Medio", low: "Baja" }, + isNew: "Nuevo", + noIssues: "No se encontraron problemas", + checked: "Comprobado si hay personajes ocultos, inyección rápida, comandos peligrosos y permisos demasiado amplios.", + reportOnly: "Informe solamente; no se cambia ningún archivo. Abra la ruta de arriba para revisarlo antes de tomar acción.", + viewDetail: "Ver detalles", + }, + }, ); diff --git a/src/overview/Quota.i18n.ts b/src/overview/Quota.i18n.ts index 6d885dd2..3633732f 100644 --- a/src/overview/Quota.i18n.ts +++ b/src/overview/Quota.i18n.ts @@ -37,4 +37,38 @@ export const quotaText = messages( exhausted: "Used up", gaugeLabel: (name: string, window: string) => `${name} ${window} quota`, }, + { + "zh-Hant": { + title: "額度與餘額", + showUpstreams: "在上游頁中檢視", + wallet: "餘額", + total: "總額度", + gaugeTip: (window: string, percent: number, left: string | null, reset: string | null) => `${window}額度已用 ${percent}%${left ? `,${left}` : ""}${reset ? `,${reset}` : ""}`, + nearlyOut: "即將用完", + gaugeLabel: (name: string, window: string) => `${name} ${window}額度`, + }, + ja: { + title: "利用枠と残高", + showUpstreams: "アップストリームで表示", + wallet: "残高", + total: "総利用枠", + scoped: (window: string, scope: string) => `${window}(${scope})`, + resetAt: (clock: string) => `${clock} にリセット`, + used: (percent: number) => `${percent}%`, + gaugeTip: (window: string, percent: number, left: string | null, reset: string | null) => `${window}の利用枠を ${percent}% 使用${left ? `、${left}` : ""}${reset ? `、${reset}` : ""}`, + nearlyOut: "残りわずか", + exhausted: "使い切りました", + gaugeLabel: (name: string, window: string) => `${name} の${window}の利用枠`, + }, + es: { + title: "Contingentes y saldos", + showUpstreams: "Ver en corrientes ascendentes", + wallet: "Saldo", + resetAt: (clock: string) => `Reinicia ${clock}`, + gaugeTip: (window: string, percent: number, left: string | null, reset: string | null) => `${window}: ${percent}% usado${left ? `, ${left}` : ""}${reset ? `; ${reset.charAt(0).toLowerCase()}${reset.slice(1)}` : ""}`, + nearlyOut: "Casi agotado", + exhausted: "Agotado", + gaugeLabel: (name: string, window: string) => `${name} ${window} contingente`, + }, + }, ); diff --git a/src/overview/Spend.i18n.ts b/src/overview/Spend.i18n.ts index 44b7a24f..1f4d7fff 100644 --- a/src/overview/Spend.i18n.ts +++ b/src/overview/Spend.i18n.ts @@ -46,4 +46,68 @@ export const spendText = messages( unavailable: "Unavailable right now", empty: "No requests recorded in the selected range", }, + { + "zh-Hant": { + dims: { model: "模型", provider: "上游", client: "金鑰" }, + metrics: { + tokens: "按 Token", + cost: "按費用", + requests: "按請求", + cache: "按快取命中", + ttft: "按首 token", + traffic: "按流量", + }, + total: (v: string) => `合計 ${v}`, + overallHit: (v: string) => `整體命中 ${v}`, + overallP50: (v: string) => `整體 P50 ${v}`, + more: { model: (n: number) => `另有 ${n} 個模型`, provider: (n: number) => `另有 ${n} 個上游`, client: (n: number) => `另有 ${n} 把金鑰` }, + unnamed: { model: "未知模型", provider: "未到上游", client: "未知金鑰" }, + viewInTraffic: "在流量中檢視", + unavailable: "去向暫時取不到", + empty: "所選區間內無請求記錄", + }, + ja: { + label: "内訳", + dims: { model: "モデル", provider: "アップストリーム", client: "キー" }, + metrics: { + tokens: "トークン順", + cost: "費用順", + requests: "リクエスト数順", + cache: "キャッシュヒット率順", + ttft: "最初のトークンまでの時間順", + traffic: "通信量順", + }, + caption: (by: string, range: string) => `${by} · ${range}`, + total: (v: string) => `合計 ${v}`, + overallHit: (v: string) => `全体のヒット率 ${v}`, + overallP50: (v: string) => `全体の P50 ${v}`, + more: { model: (n: number) => `他 ${n} モデル`, provider: (n: number) => `他 ${n} 件`, client: (n: number) => `他 ${n} 件` }, + unnamed: { model: "不明なモデル", provider: "アップストリームなし", client: "不明なキー" }, + viewInTraffic: "トラフィックで表示", + unavailable: "現在利用できません", + empty: "選択した期間にリクエストの記録がありません", + }, + ko: { + dims: { model: "모델", provider: "업스트림", client: "키" }, + }, + es: { + label: "Distribución", + dims: { model: "Modelos", provider: "Proveedores", client: "Claves" }, + metrics: { + tokens: "Por fichas", + cost: "Por costo", + requests: "Por solicitudes", + cache: "Por caché tasa de éxito", + ttft: "Por primera token", + traffic: "Por tráfico", + }, + overallHit: (v: string) => `Tasa de impacto global ${v}`, + overallP50: (v: string) => `Total P50 ${v}`, + more: { model: (n: number) => `${n} más`, provider: (n: number) => `${n} más`, client: (n: number) => `${n} más` }, + unnamed: { model: "Modelo desconocido", provider: "Sin del proveedor", client: "Tecla desconocida" }, + viewInTraffic: "Vista en tráfico", + unavailable: "No disponible ahora mismo", + empty: "No hay solicitudes registradas en el rango seleccionado", + }, + }, ); diff --git a/src/overview/Year.i18n.ts b/src/overview/Year.i18n.ts index 3ee698ee..359ce5ce 100644 --- a/src/overview/Year.i18n.ts +++ b/src/overview/Year.i18n.ts @@ -4,7 +4,7 @@ const ZH_WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", const EN_WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const EN_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -const zhMd = (d: Date) => `${d.getMonth() + 1}月${d.getDate()}日`; +const monthDay = (d: Date) => `${d.getMonth() + 1}月${d.getDate()}日`; const enMd = (d: Date) => `${EN_MONTHS[d.getMonth()]} ${d.getDate()}`; const enDays = (n: number) => `${n} ${n === 1 ? "day" : "days"}`; @@ -14,9 +14,9 @@ export const yearText = messages( metricLabel: "指标", metric: { tokens: "Token", cost: "费用", requests: "请求" }, /** 标题行右边:一整年都在记录里 */ - spanYear: (d: Date) => `${d.getFullYear()}年${zhMd(d)} 至今`, + spanYear: (d: Date) => `${d.getFullYear()}年${monthDay(d)} 至今`, /** 标题行右边:记录不满一年 */ - spanSince: (d: Date) => `${zhMd(d)}开始记录`, + spanSince: (d: Date) => `${monthDay(d)}开始记录`, totalYear: "最近一年", totalSince: "开始记录以来", usedDays: (n: number) => `${n} 天有用量`, @@ -50,9 +50,9 @@ export const yearText = messages( gridLabel: "最近一年每天的用量", cell: (date: string, what: string) => `${date}:${what}`, /** 提示和读屏用的整个日期:2026年10月28日 周三 */ - dateFull: (d: Date) => `${d.getFullYear()}年${zhMd(d)} ${ZH_WEEKDAYS[d.getDay()]}`, + dateFull: (d: Date) => `${d.getFullYear()}年${monthDay(d)} ${ZH_WEEKDAYS[d.getDay()]}`, /** 「最多的一天」下面:10月28日 周三 */ - dateShort: (d: Date) => `${zhMd(d)} ${ZH_WEEKDAYS[d.getDay()]}`, + dateShort: (d: Date) => `${monthDay(d)} ${ZH_WEEKDAYS[d.getDay()]}`, /** 网格左边那一列:周一、周三、周五(getDay 的数) */ weekday: (day: number) => ZH_WEEKDAYS[day]!, /** 网格上方的月份(0 起) */ @@ -98,4 +98,116 @@ export const yearText = messages( weekday: (day: number) => EN_WEEKDAYS[day]!, month: (m: number) => EN_MONTHS[m]!, }, + { + "zh-Hant": { + metricLabel: "指標", + metric: { tokens: "Token", cost: "費用", requests: "請求" }, + spanSince: (d: Date) => `${monthDay(d)}開始記錄`, + totalSince: "開始記錄以來", + averageNote: "不含沒有用量的日子", + streak: "連續使用", + longest: (n: number) => `最長 ${n} 天`, + requestsMain: (n: string) => `${n} 次請求`, + unpricedShort: (n: number) => `${n} 條無法計價`, + noUsageShort: (n: number) => `${n} 條無用量`, + input: "輸入", + output: "輸出", + cacheRead: "快取讀取", + costRow: "費用", + requestsRow: "請求", + noRequests: "沒有請求", + unrecorded: "未記錄", + aged: "請求記錄已過保留期,沒有當天的明細", + unavailable: "暫時取不到", + dateFull: (d: Date) => `${d.getFullYear()}年${monthDay(d)} ${(["週日", "週一", "週二", "週三", "週四", "週五", "週六"])[d.getDay()]}`, + dateShort: (d: Date) => `${monthDay(d)} ${(["週日", "週一", "週二", "週三", "週四", "週五", "週六"])[d.getDay()]}`, + weekday: (day: number) => (["週日", "週一", "週二", "週三", "週四", "週五", "週六"])[day]!, + }, + ja: { + title: "過去 1 年間", + metricLabel: "指標", + metric: { tokens: "トークン", cost: "費用", requests: "リクエスト" }, + spanYear: (d: Date) => `${d.getFullYear()}年${monthDay(d)}から現在まで`, + spanSince: (d: Date) => `${monthDay(d)}から記録`, + totalYear: "過去 1 年間", + totalSince: "記録開始から", + usedDays: (n: number) => `使用した日数 ${n} 日`, + average: "1 日平均", + averageNote: "使用量がない日を除く", + peak: "最多の日", + streak: "連続使用日数", + days: (n: number) => `${n} 日`, + longest: (n: number) => `最長 ${n} 日`, + times: (n: string) => `${n} 件`, + tokensMain: (v: string) => `${v} トークン`, + requestsMain: (n: string) => `リクエスト ${n} 件`, + estimatedShort: (amount: string) => `推定額 ${amount} を含む`, + unpricedShort: (n: number) => `料金不明 ${n} 件`, + noUsageShort: (n: number) => `使用量なし ${n} 件`, + input: "入力", + output: "出力", + cacheRead: "キャッシュ読み取り", + tokensRow: "トークン", + costRow: "費用", + requestsRow: "リクエスト", + noRequests: "リクエストなし", + unrecorded: "未記録", + aged: "リクエストの保持期間が過ぎたため、この日の詳細は表示できません", + unavailable: "現在利用できません", + less: "少ない", + more: "多い", + gridLabel: "過去 1 年間の日別使用量", + cell: (date: string, what: string) => `${date}:${what}`, + dateFull: (d: Date) => `${d.getFullYear()}年${monthDay(d)}(${"日月火水木金土"[d.getDay()]})`, + dateShort: (d: Date) => `${monthDay(d)}(${"日月火水木金土"[d.getDay()]})`, + weekday: (day: number) => "日月火水木金土"[day]!, + month: (m: number) => `${m + 1}月`, + }, + ko: { + metric: { tokens: "토큰", cost: "비용", requests: "요청" }, + input: "입력", + output: "출력", + tokensRow: "토큰", + costRow: "비용", + requestsRow: "요청", + noRequests: "요청 없음", + }, + es: { + title: "Años anteriores", + metricLabel: "Métrico", + metric: { tokens: "Tokens", cost: "Coste", requests: "Solicitudes" }, + spanYear: (d: Date) => `Desde ${((d: Date) => `${(["Jan", "Feb", "Mar", "Abr", "Mayo", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"])[d.getMonth()]} ${d.getDate()}`)(d)}, ${d.getFullYear()}`, + spanSince: (d: Date) => `Grabación desde ${((d: Date) => `${(["Jan", "Feb", "Mar", "Abr", "Mayo", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"])[d.getMonth()]} ${d.getDate()}`)(d)}`, + totalYear: "Años anteriores", + totalSince: "Desde que comenzó la grabación", + usedDays: (n: number) => `${((n: number) => `${n} ${n === 1 ? "día" : "días"}`)(n)} con uso`, + average: "Promedio diario", + averageNote: "Días sin uso excluidos", + peak: "El día más ocupado", + streak: "Racha actual", + days: (n: number) => ((n: number) => `${n} ${n === 1 ? "día" : "días"}`)(n), + longest: (n: number) => `El más largo ${((n: number) => `${n} ${n === 1 ? "día" : "días"}`)(n)}`, + tokensMain: (v: string) => `${v} fichas`, + requestsMain: (n: string) => `${n} solicitudes`, + estimatedShort: (amount: string) => `Incluidos ${amount} estimados`, + unpricedShort: (n: number) => `${n} sin precio`, + noUsageShort: (n: number) => `${n} sin uso`, + input: "Entrada", + output: "Salida", + cacheRead: "Caché leído", + costRow: "Coste", + requestsRow: "Solicitudes", + noRequests: "Sin solicitudes", + unrecorded: "No registrado", + aged: "Solicitar registros más allá del período de retención; no hay detalles para este día", + unavailable: "No disponible ahora mismo", + less: "Menos", + more: "Más", + gridLabel: "Uso diario durante el último año", + dateFull: (d: Date) => `${(["Sol", "Mon", "Mar", "Mié", "Thu", "Fri", "Sáb"])[d.getDay()]}, ${((d: Date) => `${(["Jan", "Feb", "Mar", "Abr", "Mayo", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"])[d.getMonth()]} ${d.getDate()}`)(d)}, ${d.getFullYear()}`, + dateShort: (d: Date) => `${(["Sol", "Mon", "Mar", "Mié", "Thu", "Fri", "Sáb"])[d.getDay()]}, ${((d: Date) => `${(["Jan", "Feb", "Mar", "Abr", "Mayo", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"])[d.getMonth()]} ${d.getDate()}`)(d)}`, + weekday: (day: number) => (["Sol", "Mon", "Mar", "Mié", "Thu", "Fri", "Sáb"])[day]!, + month: (m: number) => (["Jan", "Feb", "Mar", "Abr", "Mayo", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"])[m]!, + }, + }, ); diff --git a/src/overview/overview.i18n.ts b/src/overview/overview.i18n.ts index 096299e0..6072a54b 100644 --- a/src/overview/overview.i18n.ts +++ b/src/overview/overview.i18n.ts @@ -270,4 +270,355 @@ export const overviewText = messages( recordingUnavailable: "Request recording could not start", forwardingUnaffected: "Forwarding is not affected.", }, + { + "zh-Hant": { + loadFailed: "概覽資料讀取失敗", + inFlight: (_n: number) => "個進行中", + idle: "當前空閒", + upstreams: (_n: number) => "個上游", + unavailable: (_n: number) => "個不可用", + noUpstreams: "尚未新增上游", + showUpstreams: "在上游頁中檢視", + viewInTraffic: "在流量中檢視", + metricsLabel: "指標", + kpiCost: "費用", + kpiCache: "快取命中", + kpiRequests: "請求", + chartOf: (name: string) => `${name}走勢`, + deltaTip: (period: string, before: string, now: string) => `較上一個${sp(period)}${period}:${before} → ${now}`, + now: "現在", + chartUnavailable: "暫時取不到", + unrecorded: "未記錄", + hours: (n: number) => `${n} 小時`, + costUnit: "$/小時", + otherModels: (n: number) => `其他 ${n} 個模型`, + inOut: (input: string, output: string) => `輸入 ${input} · 輸出 ${output}`, + input: "輸入", + output: "輸出", + avgCost: (amount: string) => `平均每次請求 ${amount}`, + costRate: (amount: string) => `${amount}/小時`, + noRequestsShort: "無請求", + unpricedCell: "無法計價", + noUsageCell: "無用量", + rankUnpriced: (n: number) => `${n} 條請求無法計價:模型未定價,費用未計入`, + rankNoUsage: (n: number) => `${n} 條請求沒有用量資料,費用未計入`, + rankPending: (n: number) => `${n} 條請求的費用尚在計算,暫未計入`, + shortUnpriced: (n: number) => `${n} 條請求無法計價`, + shortNoUsage: (n: number) => `${n} 條請求無用量`, + shortPending: (n: number) => `${n} 條請求尚在計算`, + tagUnpriced: "部分無法計價", + tagNoUsage: "部分無用量", + tagPending: "尚在計算", + netCost: (amount: string) => `淨增費用 ${amount}`, + noTokens: "無 token 記錄", + cacheReads: "快取讀取", + uncachedInput: "新輸入", + cacheWrites: "快取寫入", + failedSub: (n: number) => `失敗 ${n} 次`, + noFailures: "無失敗", + showFailed: "在流量中檢視失敗的請求", + showUnpriced: "在流量中檢視無法計價的請求", + failed: "失敗", + noSamples: "無樣本", + upload: (shown: string) => `上傳 ${shown}`, + download: (shown: string) => `下載 ${shown}`, + sent: "上傳", + received: "下載", + tableLabel: "明細", + tabKeys: "金鑰", + colRequests: "請求", + colCost: "費用", + colCache: "快取命中", + unknownKey: "未知金鑰", + more: (n: number) => `另有 ${n} 項`, + tableEmpty: "所選區間內無請求記錄", + tableUnavailable: "明細暫時取不到", + latencyCellTip: (p50: string, p95: string, samples: number) => `P50 ${p50} · P95 ${p95} · ${samples} 個樣本`, + speedTip: (n: string, samples: number) => `生成速度中位數 ${n} token/秒 · ${samples} 個樣本`, + viewUnpriced: "在流量中檢視無法計價的請求", + recordingUnavailable: "請求記錄未能啟動", + forwardingUnaffected: "轉發不受影響。", + }, + ja: { + loadFailed: "概要データを読み込めませんでした", + inFlight: (_n: number) => "件処理中", + idle: "処理中のリクエストなし", + upstreams: (_n: number) => "件のアップストリーム", + unavailable: (_n: number) => "件利用不可", + noUpstreams: "アップストリームがありません", + showUpstreams: "アップストリームを表示", + viewInTraffic: "トラフィックで表示", + usageLabel: "使用量", + metricsLabel: "指標", + kpiTokens: "トークン", + kpiCost: "費用", + kpiCache: "キャッシュヒット", + kpiRequests: "リクエスト", + kpiLatency: "最初のトークン", + kpiTraffic: "トラフィック", + chartOf: (name: string) => `${name}の推移`, + deltaTip: (period: string, before: string, now: string) => `前の${period}と比較:${before} → ${now}`, + now: "現在", + today: "今日", + chartUnavailable: "現在利用できません", + unrecorded: "未記録", + perSlot: (width: string) => `区間ごと(${width})`, + hours: (n: number) => `${n} 時間`, + days: (n: number) => `${n} 日`, + seconds: (n: number) => `${n} 秒`, + tokenUnit: "トークン/秒", + costUnit: "$/時間", + otherModels: (n: number) => `他 ${n} モデル`, + inOut: (input: string, output: string) => `入力 ${input} · 出力 ${output}`, + input: "入力", + output: "出力", + tokenRate: (shown: string) => `${shown} トークン/秒`, + tokens: (shown: string, _n: number) => `${shown} トークン`, + avgCost: (amount: string) => `1 リクエストあたり平均 ${amount}`, + costRate: (amount: string) => `${amount}/時間`, + noRequestsShort: "リクエストなし", + estimated: (amount: string) => `推定額 ${amount} を含む`, + unpricedCell: "料金不明", + noUsageCell: "使用量なし", + rankUnpriced: (n: number) => `${n} 件のモデルに料金が設定されていないため、費用を集計していません`, + rankNoUsage: (n: number) => `${n} 件のリクエストに使用量データがないため、費用を集計していません`, + rankPending: (n: number) => `${n} 件のリクエストは費用を計算中のため、集計に含まれていません`, + shortUnpriced: (n: number) => `料金不明 ${n} 件`, + shortNoUsage: (n: number) => `使用量なし ${n} 件`, + shortPending: (n: number) => `計算中 ${n} 件`, + tagEstimated: "推定値を含む", + tagUnpriced: "一部料金不明", + tagNoUsage: "一部使用量なし", + tagPending: "計算中", + saved: (amount: string) => `${amount} 節約`, + netCost: (amount: string) => `差し引き ${amount} 増`, + noTokens: "トークンの記録なし", + cacheReads: "キャッシュ読み取り", + uncachedInput: "未キャッシュの入力", + cacheWrites: "キャッシュ書き込み", + hitRate: (pct: string) => `ヒット率 ${pct}`, + failedSub: (n: number) => `失敗 ${n} 件`, + rateSuffix: (pct: string) => ` · ${pct}%`, + noFailures: "失敗なし", + showFailed: "失敗したリクエストをトラフィックで表示", + showUnpriced: "料金不明のリクエストをトラフィックで表示", + reqCount: (shown: string, _n: number) => `${shown} 件`, + succeeded: "成功", + failed: "失敗", + latDetail: (p50: string, p95: string) => `P50 ${p50} · P95 ${p95}`, + noSamples: "サンプルなし", + upload: (shown: string) => `送信 ${shown}`, + download: (shown: string) => `受信 ${shown}`, + sent: "送信", + received: "受信", + tableLabel: "内訳", + tabModels: "モデル", + tabUpstreams: "アップストリーム", + tabKeys: "キー", + colRequests: "リクエスト", + colTokens: "トークン", + colCost: "費用", + colCache: "キャッシュヒット", + colLatency: "最初のトークン", + colSpeed: "速度", + unknownModel: "不明なモデル", + noUpstream: "アップストリームなし", + unknownKey: "不明なキー", + more: (n: number) => `他 ${n} 件を表示`, + less: "折りたたむ", + tableEmpty: "選択した期間にリクエストの記録がありません", + tableUnavailable: "現在、内訳を取得できません", + latencyCellTip: (p50: string, p95: string, samples: number) => `P50 ${p50} · P95 ${p95} · ${samples} 件`, + speedCell: (n: string) => `${n}/秒`, + speedTip: (n: string, samples: number) => `速度の中央値 ${n} トークン/秒 · ${samples} 件`, + viewUnpriced: "料金不明のリクエストをトラフィックで表示", + recordingUnavailable: "リクエストの記録を開始できませんでした", + forwardingUnaffected: "転送は続行されます。", + }, + ko: { + upstreams: (n: number) => (n === 1 ? "업스트림" : "upstreams"), + noUpstreams: "업스트림이 없습니다.", + usageLabel: "사용량", + kpiTokens: "토큰", + kpiCost: "비용", + kpiRequests: "요청", + kpiTraffic: "트래픽", + today: "오늘", + input: "입력", + output: "출력", + noRequestsShort: "요청 없음", + succeeded: "성공", + failed: "실패", + tabModels: "모델", + tabUpstreams: "업스트림", + tabKeys: "키", + colRequests: "요청", + colTokens: "토큰", + colCost: "비용", + loadFailed: "개요를 불러올 수 없습니다", + inFlight: (_n: number) => "건 진행 중", + idle: "진행 중인 요청 없음", + unavailable: (_n: number) => "개 사용 불가", + showUpstreams: "업스트림에서 보기", + viewInTraffic: "트래픽에서 보기", + metricsLabel: "지표", + kpiCache: "캐시 적중", + kpiLatency: "첫 토큰", + chartOf: (name: string) => `${name} 추이`, + deltaTip: (period: string, before: string, now: string) => `이전 ${period}과 비교: ${before} → ${now}`, + now: "지금", + chartUnavailable: "현재 사용할 수 없음", + unrecorded: "기록 없음", + perSlot: (width: string) => `막대 간격 ${width}`, + hours: (n: number) => `${n}시간`, + days: (n: number) => `${n}일`, + seconds: (n: number) => `${n}초`, + tokenUnit: "토큰/초", + costUnit: "$/시간", + otherModels: (n: number) => `기타 모델 ${n}개`, + inOut: (input: string, output: string) => `입력 ${input} · 출력 ${output}`, + tokenRate: (shown: string) => `${shown}토큰/초`, + tokens: (shown: string, _n: number) => `${shown}토큰`, + avgCost: (amount: string) => `요청당 평균 ${amount}`, + costRate: (amount: string) => `시간당 ${amount}`, + estimated: (amount: string) => `예상 비용 ${amount} 포함`, + unpricedCell: "단가 없음", + noUsageCell: "사용량 없음", + rankUnpriced: (n: number) => `모델 단가가 없어 요청 ${n}건의 비용이 집계되지 않았습니다`, + rankNoUsage: (n: number) => `사용량 데이터가 없어 요청 ${n}건의 비용이 집계되지 않았습니다`, + rankPending: (n: number) => `요청 ${n}건의 비용을 계산 중입니다`, + shortUnpriced: (n: number) => `단가 없음 ${n}건`, + shortNoUsage: (n: number) => `사용량 없음 ${n}건`, + shortPending: (n: number) => `계산 중 ${n}건`, + tagEstimated: "예상 비용 포함", + tagUnpriced: "일부 단가 없음", + tagNoUsage: "일부 사용량 없음", + tagPending: "비용 계산 중", + saved: (amount: string) => `${amount} 절감`, + netCost: (amount: string) => `순비용 ${amount} 증가`, + noTokens: "토큰 기록 없음", + cacheReads: "캐시 읽기", + uncachedInput: "캐시되지 않은 입력", + cacheWrites: "캐시 쓰기", + hitRate: (pct: string) => `적중률 ${pct}`, + failedSub: (n: number) => `${n}건 실패`, + noFailures: "실패 없음", + showFailed: "트래픽에서 실패한 요청 보기", + showUnpriced: "트래픽에서 단가가 없는 요청 보기", + reqCount: (shown: string, _n: number) => `${shown}건`, + noSamples: "표본 없음", + upload: (shown: string) => `전송 ${shown}`, + download: (shown: string) => `수신 ${shown}`, + sent: "전송", + received: "수신", + tableLabel: "세부 내역", + colCache: "캐시 적중", + colLatency: "첫 토큰", + colSpeed: "속도", + unknownModel: "알 수 없는 모델", + noUpstream: "업스트림 없음", + unknownKey: "알 수 없는 키", + more: (n: number) => `${n}개 더 보기`, + less: "접기", + tableEmpty: "선택한 기간에 기록된 요청이 없습니다", + tableUnavailable: "현재 세부 내역을 불러올 수 없습니다", + latencyCellTip: (p50: string, p95: string, samples: number) => `P50 ${p50} · P95 ${p95} · 표본 ${samples}개`, + speedCell: (n: string) => `${n}/초`, + speedTip: (n: string, samples: number) => `중앙값 ${n}토큰/초 · 표본 ${samples}개`, + viewUnpriced: "트래픽에서 단가가 없는 요청 보기", + recordingUnavailable: "요청 기록을 시작할 수 없습니다", + forwardingUnaffected: "요청은 계속 전달됩니다.", + }, + es: { + loadFailed: "No se pudo cargar la vista general", + inFlight: (_n: number) => "en curso", + idle: "Inactivo", + upstreams: (n: number) => (n === 1 ? "proveedor" : "del proveedor"), + unavailable: (_n: number) => "no disponible", + noUpstreams: "Todavía no hay proveedores.", + showUpstreams: "Ver en corrientes ascendentes", + viewInTraffic: "Vista en tráfico", + usageLabel: "Uso", + metricsLabel: "Métricas", + kpiCost: "Coste", + kpiCache: "Caché golpea", + kpiRequests: "Solicitudes", + kpiLatency: "Primer token", + kpiTraffic: "Tráfico", + chartOf: (name: string) => `${name} Con el tiempo`, + deltaTip: (period: string, before: string, now: string) => `vs. anteriores ${period}: ${before} → ${now}`, + now: "Ahora", + today: "Hoy", + chartUnavailable: "No disponible ahora mismo", + unrecorded: "No registrado", + perSlot: (width: string) => `${width} por bar`, + hours: (n: number) => (n === 1 ? "1 hora" : `${n} horas`), + days: (n: number) => (n === 1 ? "1 día" : `${n} días`), + seconds: (n: number) => (n === 1 ? "1 segundo" : `${n} segundos`), + otherModels: (n: number) => (n === 1 ? "1 otro modelo" : `${n} otros modelos`), + inOut: (input: string, output: string) => `Entrada ${input} · Salida ${output}`, + input: "Entrada", + output: "Salida", + avgCost: (amount: string) => `${amount} por solicitud en promedio`, + noRequestsShort: "Sin solicitudes", + estimated: (amount: string) => `Incluidos ${amount} estimados`, + unpricedCell: "Sin precio", + noUsageCell: "Sin uso", + rankUnpriced: (n: number) => n === 1 + ? "1 solicitud sin precio: el modelo no tiene precio, por lo que su costo no está incluido" + : `${n} solicitudes sin precio: el modelo no tiene precio, por lo que su costo no está incluido`, + rankNoUsage: (n: number) => n === 1 + ? "1 solicitud no tiene datos de uso, por lo que su costo no está incluido" + : `${n} las solicitudes no tienen datos de uso, por lo que su costo no está incluido`, + rankPending: (n: number) => n === 1 + ? "1 solicitud todavía está en precio, por lo que su costo no está incluido todavía" + : `${n} las solicitudes todavía están siendo cotizadas, por lo que su costo aún no está incluido`, + shortUnpriced: (n: number) => (n === 1 ? "1 solicitud sin precio" : `${n} solicitudes sin precio`), + shortNoUsage: (n: number) => (n === 1 ? "1 solicitud sin uso" : `${n} solicitudes sin uso`), + shortPending: (n: number) => (n === 1 ? "1 solicitud con preciod" : `${n} solicitudes con precio`), + tagEstimated: "Incl. estimaciones", + tagUnpriced: "En parte sin precio", + tagNoUsage: "En parte sin uso", + tagPending: "Tener un precio", + saved: (amount: string) => `${amount} guardado`, + netCost: (amount: string) => `${amount} Aumento neto de los costos`, + noTokens: "No se registran tokens", + cacheReads: "Caché lee", + uncachedInput: "Entrada sin encallar", + cacheWrites: "Cache escribe", + failedSub: (n: number) => `${n} Falló`, + noFailures: "No hay fallas", + showFailed: "Ver peticiones fallidas en tráfico", + showUnpriced: "Ver solicitudes sin precio en el tráfico", + reqCount: (shown: string, n: number) => `${shown} ${n === 1 ? "solicitud" : "solicitudes"}`, + succeeded: "Correcto", + failed: "Error", + noSamples: "Sin muestras", + upload: (shown: string) => `Arriba ${shown}`, + download: (shown: string) => `Abajo ${shown}`, + sent: "Arriba", + received: "Abajo", + tableLabel: "Desglose", + tabModels: "Modelos", + tabUpstreams: "Proveedores", + tabKeys: "Claves", + colRequests: "Solicitudes", + colCost: "Coste", + colCache: "Caché golpea", + colLatency: "Primer token", + colSpeed: "Velocidad", + unknownModel: "Modelo desconocido", + noUpstream: "Sin del proveedor", + unknownKey: "Tecla desconocida", + more: (n: number) => `${n} más`, + less: "Mostrar menos", + tableEmpty: "No hay solicitudes registradas en el rango seleccionado", + tableUnavailable: "El desglose no está disponible ahora mismo.", + latencyCellTip: (p50: string, p95: string, samples: number) => `P50 ${p50} · P95 ${p95} · ${samples === 1 ? "1 muestra" : `${samples} muestras`}`, + speedTip: (n: string, samples: number) => `Velocidad media ${n} tokens/s · ${samples === 1 ? "1 muestra" : `${samples} muestras`}`, + viewUnpriced: "Ver solicitudes sin precio en el tráfico", + recordingUnavailable: "No se pudo iniciar la solicitud de grabación", + forwardingUnaffected: "El envío no se ve afectado.", + }, + }, ); diff --git a/src/overview/useLive.i18n.ts b/src/overview/useLive.i18n.ts index ae39f712..0b9b2549 100644 --- a/src/overview/useLive.i18n.ts +++ b/src/overview/useLive.i18n.ts @@ -8,4 +8,12 @@ export const liveText = messages( { unknownModel: "Unknown model", }, + { + ja: { + unknownModel: "不明なモデル", + }, + es: { + unknownModel: "Modelo desconocido", + }, + }, ); diff --git a/src/palette/items.tsx b/src/palette/items.tsx index 47e348ed..e4bd6b67 100644 --- a/src/palette/items.tsx +++ b/src/palette/items.tsx @@ -16,7 +16,7 @@ import { ZoomInIcon, ZoomOutIcon, } from "lucide-react"; -import { textOf, type Lang } from "@/i18n"; +import { LANGUAGES, textOf, type Lang, type Messages } from "@/i18n"; import { appText } from "@/App.i18n"; import { SURFACES, type Nav, type Surface } from "@/nav"; import type { ClientsResponse, Overview, RequestRow } from "@/types"; @@ -107,9 +107,9 @@ const PAGE_ICONS: Record = { settings: , }; -/** 两种语言的别名都参与搜索:中文界面里打 `dark` 也找得到外观 */ -function both(pick: (t: (typeof paletteText)["zh"]) => string | undefined): string[] { - return [pick(paletteText.zh), pick(paletteText.en)].filter((s): s is string => !!s); +/** 搜索匹配所有界面语言的名称和别名。 */ +function keywordsOf(copy: Messages, pick: (t: T) => string | undefined): string[] { + return LANGUAGES.map((lang) => pick(copy[lang])).filter((s): s is string => !!s); } /** 外壳交进来的:数据和几个只有外壳做得了的动作 */ @@ -158,7 +158,7 @@ export function buildItems(s: Sources): Item[] { id: `page:${surface}`, group: "pages", title: app.surfaces[surface], - keywords: [appText.zh.surfaces[surface], appText.en.surfaces[surface], ...both((x) => x.pageAliases[surface])], + keywords: [...keywordsOf(appText, (x) => x.surfaces[surface]), ...keywordsOf(paletteText, (x) => x.pageAliases[surface])], icon: PAGE_ICONS[surface], combo: pageCombo(surface), verb: "open", @@ -184,41 +184,40 @@ export function buildItems(s: Sources): Item[] { run, ...rest, // 两种语言的名字,加两种语言的别名 - keywords: [...keywords, ...both((x) => x.actionAliases[alias ?? id])], + keywords: [...keywords, ...keywordsOf(paletteText, (x) => x.actionAliases[alias ?? id])], }); }; - const other = (pick: (x: (typeof paletteText)["zh"]) => string) => [pick(paletteText.zh), pick(paletteText.en)]; if (writable) { action("new-upstream", t.newUpstream, , () => nav.open("upstreams", { create: "upstream" }), { - keywords: other((x) => x.newUpstream), + keywords: keywordsOf(paletteText, (x) => x.newUpstream), }); action("new-key", t.newKey, , () => nav.open("keys", { create: true }), { - keywords: other((x) => x.newKey), + keywords: keywordsOf(paletteText, (x) => x.newKey), }); if (hasUpstreams) { action("new-route", t.newRoute, , () => nav.open("routing", { create: "route" }), { - keywords: other((x) => x.newRoute), + keywords: keywordsOf(paletteText, (x) => x.newRoute), }); } } if (linked && hasUpstreams && !s.readOnly) { action("speed-test", t.speedTest, , () => nav.open("upstreams", { test: "speed" }), { - keywords: other((x) => x.speedTest), + keywords: keywordsOf(paletteText, (x) => x.speedTest), alias: "speedTest", }); action("link-test", t.linkTest, , () => nav.open("upstreams", { test: "link" }), { - keywords: other((x) => x.linkTest), + keywords: keywordsOf(paletteText, (x) => x.linkTest), alias: "linkTest", }); action("dry-run", t.dryRun, , () => nav.open("routing", { dryRun: true }), { - keywords: other((x) => x.dryRun), + keywords: keywordsOf(paletteText, (x) => x.dryRun), alias: "dryRun", }); } if (linked) { action("search-traffic", t.searchTraffic, , () => nav.open("requests", { search: true }), { - keywords: other((x) => x.searchTraffic), + keywords: keywordsOf(paletteText, (x) => x.searchTraffic), combo: COMBOS.search, alias: "searchTraffic", }); @@ -226,55 +225,55 @@ export function buildItems(s: Sources): Item[] { const profiles = s.conn?.profiles ?? []; if (profiles.length > 1) { action("switch-connection", t.switchConnection, , () => {}, { - keywords: other((x) => x.switchConnection), + keywords: keywordsOf(paletteText, (x) => x.switchConnection), alias: "switchConnection", enter: "connections", }); } action("refresh", t.refresh, , s.shell.refresh, { - keywords: other((x) => x.refresh), + keywords: keywordsOf(paletteText, (x) => x.refresh), combo: COMBOS.refresh, }); action("rail", s.railOpen ? app.collapseRail : app.expandRail, , s.shell.toggleRail, { - keywords: [appText.zh.collapseRail, appText.zh.expandRail, appText.en.collapseRail, appText.en.expandRail], + keywords: [...keywordsOf(appText, (x) => x.collapseRail), ...keywordsOf(appText, (x) => x.expandRail)], combo: COMBOS.rail, }); // 界面大小:只在搜的时候出现(平常按快捷键),设置页那一行跟着动(`ui-zoom-changed`) action("zoom-in", t.zoomIn, , () => stepZoom("in"), { - keywords: other((x) => x.zoomIn), + keywords: keywordsOf(paletteText, (x) => x.zoomIn), alias: "zoom", combo: COMBOS.zoomIn, searchOnly: true, }); action("zoom-out", t.zoomOut, , () => stepZoom("out"), { - keywords: other((x) => x.zoomOut), + keywords: keywordsOf(paletteText, (x) => x.zoomOut), alias: "zoom", combo: COMBOS.zoomOut, searchOnly: true, }); action("zoom-reset", t.zoomReset, , () => stepZoom("reset"), { - keywords: other((x) => x.zoomReset), + keywords: keywordsOf(paletteText, (x) => x.zoomReset), alias: "zoom", combo: COMBOS.zoomReset, searchOnly: true, }); if (linked) { action("config-file", app.configFile, , s.shell.configFile, { - keywords: [appText.zh.configFile, appText.en.configFile], + keywords: keywordsOf(appText, (x) => x.configFile), alias: "configFile", }); action("version-history", app.versionHistory, , s.shell.history, { - keywords: [appText.zh.versionHistory, appText.en.versionHistory], + keywords: keywordsOf(appText, (x) => x.versionHistory), alias: "versionHistory", }); } action("check-updates", t.checkUpdates, , s.shell.checkUpdates, { - keywords: other((x) => x.checkUpdates), + keywords: keywordsOf(paletteText, (x) => x.checkUpdates), alias: "checkUpdates", }); - action("notices", t.notices, , s.shell.notices, { keywords: other((x) => x.notices) }); + action("notices", t.notices, , s.shell.notices, { keywords: keywordsOf(paletteText, (x) => x.notices) }); action("shortcuts", t.shortcuts, , s.shell.shortcuts, { - keywords: other((x) => x.shortcuts), + keywords: keywordsOf(paletteText, (x) => x.shortcuts), combo: COMBOS.shortcuts, }); @@ -282,26 +281,26 @@ export function buildItems(s: Sources): Item[] { if (writable) { if (hasUpstreams) { action("new-group", t.newGroup, , () => nav.open("routing", { create: "group" }), { - keywords: other((x) => x.newGroup), + keywords: keywordsOf(paletteText, (x) => x.newGroup), searchOnly: true, }); } action("new-proxy", t.newProxy, , () => nav.open("upstreams", { create: "proxy" }), { - keywords: other((x) => x.newProxy), + keywords: keywordsOf(paletteText, (x) => x.newProxy), searchOnly: true, }); action("new-sheet", t.newSheet, , () => nav.open("upstreams", { create: "sheet" }), { - keywords: other((x) => x.newSheet), + keywords: keywordsOf(paletteText, (x) => x.newSheet), searchOnly: true, }); action("new-plugin", t.newPlugin, , () => nav.open("plugins", { add: true }), { - keywords: other((x) => x.newPlugin), + keywords: keywordsOf(paletteText, (x) => x.newPlugin), alias: "newPlugin", searchOnly: true, }); } action("add-connection", t.addConnection, , s.addConnection, { - keywords: other((x) => x.addConnection), + keywords: keywordsOf(paletteText, (x) => x.addConnection), alias: "addConnection", searchOnly: true, }); @@ -427,7 +426,7 @@ export function buildItems(s: Sources): Item[] { group: "connections", title: profileName(p), detail: p.local ? undefined : (p.addr ?? undefined), - keywords: p.local ? [connText.zh.local, connText.en.local] : [p.name, p.host ?? ""], + keywords: p.local ? keywordsOf(connText, (x) => x.local) : [p.name, p.host ?? ""], icon: p.local ? : , meta: current ? : undefined, disabled: current, @@ -447,7 +446,7 @@ export function buildItems(s: Sources): Item[] { group: "settings", title: sec.title[s.lang], detail: app.surfaces.settings, - keywords: [sec.title.zh, sec.title.en, ...both((x) => x.sectionAliases[sec.id])], + keywords: [...Object.values(sec.title), ...keywordsOf(paletteText, (x) => x.sectionAliases[sec.id])], icon: , verb: "open", searchOnly: true, diff --git a/src/palette/palette.i18n.ts b/src/palette/palette.i18n.ts index 3e35c54a..4ed602fe 100644 --- a/src/palette/palette.i18n.ts +++ b/src/palette/palette.i18n.ts @@ -307,4 +307,417 @@ export const paletteText = messages( close: "Close", }, }, + { + "zh-Hant": { + placeholder: "搜尋頁面、操作、上游、金鑰、請求…", + placeholderUnlinked: "搜尋頁面、操作…", + connectionsPlaceholder: "選擇連線", + groups: { + recent: "最近使用", + pages: "頁面", + actions: "操作", + upstreams: "上游", + keys: "金鑰", + routes: "路由", + groups: "策略組", + clients: "用戶端", + connections: "連線", + settings: "設定", + requests: "請求", + }, + none: (q: string) => `無與「${q}」匹配的結果`, + noConnections: "無匹配的連線", + verbs: { + open: "開啟", + run: "執行", + switch: "切換", + }, + move: "選擇", + newSheet: "新建價目表…", + newPlugin: "新增外掛…", + speedTest: "推理測速…", + linkTest: "鏈路測速…", + newKey: "新建金鑰…", + newGroup: "新建策略組…", + dryRun: "路由試算…", + switchConnection: "切換連線…", + addConnection: "新增遠端連線…", + searchTraffic: "搜尋流量", + notices: "開啟提醒", + refresh: "重新整理資料", + zoomIn: "放大介面", + zoomOut: "縮小介面", + zoomReset: "介面恢復為 100%", + checkUpdates: "檢查更新", + shortcuts: "鍵盤快捷鍵", + checking: "正在檢查更新…", + found: (v: string) => `發現新版本 ${v}`, + checkFailed: "檢查更新失敗", + current: "當前", + circuitOpen: "熔斷中", + authRejected: "憑據被拒", + needsLogin: "需要重新登入", + defaultMark: "預設", + defaultRoute: "預設路由", + rules: (n: number) => `${n} 條規則`, + upstreamCount: (n: number) => `${n} 個上游`, + inFlight: "進行中", + failed: "失敗", + notInstalled: "未安裝", + manualSetup: "手動配置", + openRequest: (id: number) => `開啟請求 #${id}`, + pageAliases: { + dashboard: "總覽 首頁 統計 用量 費用", + requests: "請求 日誌 會話 記錄", + clients: "應用 接管", + keys: "令牌 憑據", + upstreams: "服務商 模型 代理 價目表", + routing: "規則 策略組 試算 輔助請求", + security: "防護 脫敏 掃描 日誌", + mcp: "擴充套件 伺服器 工具", + plugins: "指令碼 改寫 擴充套件", + settings: "偏好 選項", + } as Record, + sectionAliases: { + connections: "遠端 本機 伺服器", + language: "中文 英文 介面語言", + appearance: "深色 淺色 主題", + zoom: "縮放 字號 字型 文字 放大 縮小 顯示比例", + menubar: "狀態列 托盤", + autostart: "開機 登入 自啟", + listen: "埠 地址 區域網 網絡卡", + retention: "日誌 天數 清理", + updates: "版本 升級", + notices: "通知", + about: "版本 資料目錄", + diagnostics: "診斷 匯出", + uninstall: "刪除 移除", + } as Record, + actionAliases: { + refresh: "重新讀取", + rail: "側欄 源列表 邊欄", + zoom: "介面大小 縮放 字號 字型 文字 顯示比例", + shortcuts: "快捷鍵 按鍵 幫助 ?", + checkUpdates: "版本 升級", + configFile: "配置 yaml", + versionHistory: "備份 恢復 歷史 回滾 版本", + speedTest: "測速 延遲 模型", + linkTest: "測速 連通 網路", + dryRun: "測試 規則", + switchConnection: "遠端 本機 伺服器", + addConnection: "遠端 伺服器", + searchTraffic: "查詢 請求", + notices: "通知 鈴鐺", + newPlugin: "指令碼 javascript", + } as Record, + sheet: { + title: "鍵盤快捷鍵", + pages: "頁面", + general: "通用", + traffic: "流量", + palette: "命令面板", + openPalette: "開啟命令面板", + refresh: "重新整理資料", + rail: "收起或展開源列表", + zoomIn: "放大介面", + zoomOut: "縮小介面", + zoomReset: "介面恢復為 100%", + shortcuts: "顯示鍵盤快捷鍵", + search: "搜尋流量", + rowMove: "上一條、下一條", + rowOpen: "開啟詳情", + groupToggle: "展開、收起會話", + detailClose: "關閉詳情", + itemMove: "上一項、下一項", + groupMove: "上一組、下一組", + itemRun: "執行選中項", + levelBack: "返回上一級", + close: "關閉", + }, + }, + ja: { + title: "コマンドパレット", + placeholder: "ページ、操作、アップストリーム、キー、リクエストを検索…", + placeholderUnlinked: "ページや操作を検索…", + connectionsPlaceholder: "接続を選択", + groups: { + recent: "最近使った項目", pages: "ページ", actions: "操作", upstreams: "アップストリーム", + keys: "キー", routes: "ルート", groups: "グループ", clients: "クライアント", + connections: "接続", settings: "設定", requests: "リクエスト", + }, + none: (q: string) => `「${q}」に一致する結果がありません`, + noConnections: "一致する接続がありません", + verbs: { open: "開く", run: "実行", switch: "切り替え" }, + move: "選択", + back: "戻る", + newUpstream: "アップストリームを追加…", + newProxy: "プロキシを追加…", + newSheet: "料金表を作成…", + newPlugin: "プラグインを追加…", + speedTest: "推論速度テスト…", + linkTest: "接続速度テスト…", + newKey: "キーを作成…", + newRoute: "ルートを作成…", + newGroup: "グループを作成…", + dryRun: "ルーティングをシミュレーション…", + switchConnection: "接続を切り替え…", + addConnection: "リモート接続を追加…", + searchTraffic: "トラフィックを検索", + notices: "通知を開く", + refresh: "データを更新", + zoomIn: "拡大", + zoomOut: "縮小", + zoomReset: "表示を 100% に戻す", + checkUpdates: "更新を確認", + shortcuts: "キーボードショートカット", + checking: "更新を確認しています…", + latest: (v: string) => `最新バージョンです(${v})`, + found: (v: string) => `バージョン ${v} を利用できます`, + checkFailed: "更新の確認に失敗しました", + current: "現在の設定", + disabled: "無効", + circuitOpen: "一時停止中", + authRejected: "認証情報が拒否されました", + needsLogin: "再ログインが必要", + defaultMark: "既定", + defaultRoute: "既定のルート", + route: (name: string) => `ルート ${name}`, + rules: (n: number) => `ルール ${n} 件`, + upstreamCount: (n: number) => `アップストリーム ${n} 件`, + inFlight: "処理中", + failed: "失敗", + notInstalled: "未インストール", + adopted: "接続済み", + manualSetup: "手動設定", + requestNo: (id: number) => `#${id}`, + openRequest: (id: number) => `リクエスト #${id} を開く`, + pageAliases: { + dashboard: "ホーム 統計 使用量 費用", requests: "リクエスト ログ 履歴 セッション", + clients: "アプリ 接続", keys: "トークン 認証情報 APIキー", upstreams: "プロバイダー モデル プロキシ 料金", + routing: "ルール グループ テスト", security: "保護 マスキング スキャン ログ", + mcp: "拡張 サーバー ツール", plugins: "スクリプト 拡張", settings: "環境設定 オプション", + }, + sectionAliases: { + connections: "リモート ローカル サーバー", language: "日本語 英語 中国語", + appearance: "ダーク ライト テーマ", zoom: "拡大 縮小 文字 フォント", + menubar: "ステータス トレイ", autostart: "ログイン 起動", listen: "ポート アドレス LAN", + retention: "ログ 履歴 保持", updates: "バージョン アップグレード", notices: "通知", + about: "バージョン データ", diagnostics: "診断 エクスポート", uninstall: "削除", + }, + actionAliases: { + refresh: "再読み込み", rail: "サイドバー", zoom: "文字 フォント 表示サイズ", + shortcuts: "キー ヘルプ ?", checkUpdates: "バージョン アップグレード", + configFile: "設定 yaml", versionHistory: "履歴 復元 ロールバック", + speedTest: "速度 レイテンシ モデル", linkTest: "ネットワーク 速度 レイテンシ", + dryRun: "テスト ルール", switchConnection: "リモート ローカル サーバー", + addConnection: "リモート サーバー", searchTraffic: "ログ リクエスト 履歴", + notices: "通知 ベル", newPlugin: "スクリプト javascript", + }, + sheet: { + title: "キーボードショートカット", pages: "ページ", general: "一般", traffic: "トラフィック", + palette: "コマンドパレット", openPalette: "コマンドパレットを開く", refresh: "データを更新", + rail: "サイドバーを折りたたむ・展開", zoomIn: "拡大", zoomOut: "縮小", + zoomReset: "表示を 100% に戻す", shortcuts: "キーボードショートカットを表示", search: "トラフィックを検索", + rowMove: "前・次のリクエスト", rowOpen: "詳細を開く", groupToggle: "セッションを展開・折りたたむ", + detailClose: "詳細を閉じる", itemMove: "前・次の項目", groupMove: "前・次のグループ", + itemRun: "選択した項目を実行", levelBack: "前の階層に戻る", close: "閉じる", + }, + }, + ko: { + title: "명령 팔레트", + connectionsPlaceholder: "연결 선택", + groups: { + recent: "Recent", + pages: "Pages", + actions: "작업", + upstreams: "업스트림", + keys: "키", + routes: "Routes", + groups: "Groups", + clients: "클라이언트", + connections: "Connections", + settings: "설정", + requests: "요청", + }, + none: (q: string) => `「${q}」에 대한 검색 결과가 없습니다.`, + noConnections: "일치하는 연결이 없습니다.", + verbs: { + open: "Open", + run: "Run", + switch: "전환", + }, + addConnection: "원격 연결 추가…", + checkUpdates: "업데이트 확인", + shortcuts: "키보드 단축키", + checking: "업데이트 확인 중…", + found: (v: string) => `버전 ${v}을(를) 사용할 수 있습니다`, + current: "현재", + disabled: "비활성화됨", + defaultMark: "기본값", + upstreamCount: (n: number) => count(n, "업스트림", "upstreams"), + inFlight: "진행 중", + failed: "실패", + manualSetup: "수동 설정", + sheet: { + title: "키보드 단축키", + pages: "Pages", + general: "일반", + traffic: "트래픽", + palette: "명령 팔레트", + openPalette: "Open the command palette", + refresh: "Refresh data", + rail: "Collapse or expand the sidebar", + zoomIn: "Zoom in", + zoomOut: "Zoom out", + zoomReset: "Reset zoom to 100%", + shortcuts: "Show keyboard shortcuts", + search: "Search traffic", + rowMove: "Previous / next request", + rowOpen: "Open details", + groupToggle: "Expand / collapse a session", + detailClose: "Close details", + itemMove: "Previous / next item", + groupMove: "Previous / next group", + itemRun: "Run the selected item", + levelBack: "Back one level", + close: "닫기", + }, + }, + es: { + title: "Paleta de comandos", + placeholder: "Buscar páginas, acciones, del proveedor, claves, peticiones…", + placeholderUnlinked: "Buscar páginas y acciones…", + connectionsPlaceholder: "Elegir una conexión", + groups: { + recent: "Reciente", + pages: "Páginas", + actions: "Acciones", + upstreams: "Proveedores", + keys: "Claves", + routes: "Rutas", + groups: "Grupos", + clients: "Clientes", + connections: "Conectaciones", + settings: "Configuración", + requests: "Solicitudes", + }, + none: (q: string) => `No hay resultados para «${q}».`, + noConnections: "No hay conexiones que coincidan.", + verbs: { + open: "Abrir", + run: "Corre", + switch: "Cambiar", + }, + move: "Seleccionar", + back: "Atrás", + newUpstream: "Nuevo río arriba…", + newProxy: "Nuevo proxy…", + newSheet: "Nueva hoja de precios…", + newPlugin: "Añadir complemento…", + speedTest: "Prueba de inferencia…", + linkTest: "Prueba de conexión…", + newKey: "Nueva llave…", + newRoute: "Nueva ruta…", + newGroup: "Nuevo grupo…", + dryRun: "Enrutamiento en seco…", + switchConnection: "Cambiar la conexión…", + addConnection: "Añadir conexión remota…", + searchTraffic: "Tráfico de búsqueda", + notices: "Avisos abiertos", + refresh: "Actualizar los datos", + zoomIn: "Ampliar", + zoomOut: "Reducir", + zoomReset: "Reiniciar el zoom al 100%", + checkUpdates: "Buscar actualizaciones", + shortcuts: "Atajos de teclado", + checking: "Buscando actualizaciones…", + latest: (v: string) => `Hasta la fecha ${v}`, + found: (v: string) => `Hay una nueva versión disponible (${v})`, + checkFailed: "No se pudo comprobar si había actualizaciones", + current: "Actual", + disabled: "Desactivado", + circuitOpen: "Circuito abierto", + authRejected: "Credenciales rechazadas", + needsLogin: "Inicie sesión de nuevo", + defaultMark: "Predeterminado", + defaultRoute: "Ruta predeterminada", + route: (name: string) => `Ruta ${name}`, + rules: (n: number) => count(n, "regla", "normas"), + upstreamCount: (n: number) => count(n, "proveedor", "del proveedor"), + inFlight: "En curso", + failed: "Error", + notInstalled: "No instalado", + adopted: "Adoptada", + manualSetup: "Configuración manual", + openRequest: (id: number) => `Abrir petición #${id}`, + pageAliases: { + dashboard: "costo de uso de las estadísticas domésticas", + requests: "peticiones registro de sesiones de historial", + clients: "las aplicaciones adoptan", + keys: "acreditaciones tokens api key", + upstreams: "proveedores modelos proxies hojas de precios", + routing: "reglas grupos de sondas de secado", + security: "Guard redaction scan log", + mcp: "herramientas de servidores de extensiones", + plugins: "scripts rewrite javascript", + settings: "opciones de preferencias", + } as Record, + sectionAliases: { + connections: "servidor local remoto", + language: "chino inglés", + appearance: "modo de la luz oscura tema", + zoom: "tamaño de la interfaz zoom escala fuente texto más grande más pequeño", + menubar: "bandeja de estado de la barra de menú", + autostart: "Lanzamiento de inicio de sesión", + listen: "puerto dirección lan interfaz bind", + retention: "logs días de limpieza del historial", + updates: "actualización de la versión", + notices: "notificaciones", + about: "directorio de datos de versión", + diagnostics: "Exportación del paquete de diagnósticos", + uninstall: "eliminar borrar", + } as Record, + actionAliases: { + refresh: "recargar", + rail: "lista de fuentes de la barra lateral", + zoom: "tamaño de la interfaz escala de texto fuente más grande más pequeño", + shortcuts: "¿Las teclas de acceso rápido ayudan?", + checkUpdates: "actualización de la versión", + configFile: "config yaml", + versionHistory: "copia de seguridad restaurar la versión de reversión del historial", + speedTest: "Modelo de latencia de velocidad", + linkTest: "latencia de la red de velocidad", + dryRun: "normas de ensayo", + switchConnection: "servidor local remoto", + addConnection: "servidor remoto", + searchTraffic: "buscar solicitudes", + notices: "notificaciones campana", + newPlugin: "script javascript", + } as Record, + sheet: { + title: "Atajos de teclado", + pages: "Páginas", + general: "General", + traffic: "Tráfico", + palette: "Paleta de comandos", + openPalette: "Abrir la paleta de comandos", + refresh: "Actualizar los datos", + rail: "Contraer o expandir la barra lateral", + zoomIn: "Ampliar", + zoomOut: "Reducir", + zoomReset: "Reiniciar el zoom al 100%", + shortcuts: "Mostrar accesos rápidos de teclado", + search: "Tráfico de búsqueda", + rowMove: "Petición anterior / siguiente", + rowOpen: "Abrir detalles", + groupToggle: "Expandir / colapsar una sesión", + detailClose: "Cerrar detalles", + itemMove: "Punto anterior / siguiente", + groupMove: "Grupo anterior / siguiente", + itemRun: "Ejecutar el elemento seleccionado", + levelBack: "Atrás de un nivel", + close: "Cerrar", + }, + }, + }, ); diff --git a/src/palette/sections.ts b/src/palette/sections.ts index 09bcc3c6..15022ee5 100644 --- a/src/palette/sections.ts +++ b/src/palette/sections.ts @@ -1,4 +1,4 @@ -import type { Messages } from "@/i18n"; +import { LANGUAGES, type Messages } from "@/i18n"; import { isMac } from "@/platform"; import { generalText } from "@/settings/GeneralSection.i18n"; import { settingsText } from "@/settings/SettingsPage.i18n"; @@ -49,7 +49,8 @@ interface SectionDef { local?: boolean; } -const pick = (m: Messages, get: (t: T) => string): Messages => ({ zh: get(m.zh), en: get(m.en) }); +const pick = (m: Messages, get: (t: T) => string): Messages => + Object.fromEntries(LANGUAGES.map((lang) => [lang, get(m[lang])])) as Messages; export const SETTINGS_SECTIONS: readonly SectionDef[] = [ { id: "connections", title: pick(connText, (t) => t.title) }, diff --git a/src/plugins/ChangedDialog.i18n.tsx b/src/plugins/ChangedDialog.i18n.tsx index 3f850b7b..e70d1173 100644 --- a/src/plugins/ChangedDialog.i18n.tsx +++ b/src/plugins/ChangedDialog.i18n.tsx @@ -36,4 +36,36 @@ export const changedDialogText = messages( edit: "Edit code…", cancelled: "Cancelled. The configuration was not changed.", }, + { + "zh-Hant": { + title: "稽核檔案更改", + lead: (name: ReactNode) => <>外掛「{name}」的檔案在確認之後被改動過。確認之前,此外掛不執行。, + rejecting: "出錯時設為拒絕這次請求:在此期間,適用範圍內的請求將被拒絕。", + fullCode: "完整程式碼", + code: "程式碼", + cannotLoad: "更改後的程式碼無法載入", + missing: "外掛檔案已不存在或無法讀取。", + missingHint: "可以編輯程式碼後儲存,或刪除此外掛。", + loadFailed: "檔案內容讀取失敗", + approve: "確認更改", + edit: "編輯程式碼…", + cancelled: "已取消,配置未改動。", + }, + es: { + title: "Cambios en el archivo de revisión", + lead: (name: ReactNode) => <>El archivo del complemento “{name}” fue cambiado después de que fue aprobado. Hasta que el cambio sea aprobado, el plugin no se ejecuta., + rejecting: "En caso de error se establece para rechazar la solicitud: mientras tanto, las solicitudes a las que se aplica son rechazadas.", + changes: "Cambios", + fullCode: "Código completo", + code: "Código", + cannotLoad: "El código modificado no se puede cargar", + at: (where: string) => `En ${where}.`, + missing: "El archivo de complemento ya no existe o no se puede leer.", + missingHint: "Editar y guardar el código, o eliminar el complemento.", + loadFailed: "El archivo no se pudo leer", + approve: "Aprobar cambios", + edit: "Editar código…", + cancelled: "Cancelada. La configuración no fue cambiada.", + }, + }, ); diff --git a/src/plugins/Editor.i18n.ts b/src/plugins/Editor.i18n.ts index 7a2ee7c5..0b8964b6 100644 --- a/src/plugins/Editor.i18n.ts +++ b/src/plugins/Editor.i18n.ts @@ -154,4 +154,130 @@ export const editorText = messages( keepEditing: "Keep editing", discard: "Discard changes", }, + { + "zh-Hant": { + tabSettings: "設定", + tabCode: "程式碼", + codeHasError: "程式碼無法載入", + newTitle: "新增外掛", + install: "安裝", + idLabel: "外掛 ID", + idHint: "小寫字母、數字和連字元,最多 40 個;安裝後不可修改。", + idProblems: { + bad: "只能使用小寫字母、數字和連字元,最多 40 個。", + reserved: "此 ID 為保留詞,不能使用。", + taken: "已有外掛使用此 ID。", + }, + templateFailed: "無法開啟外掛模板", + template: template([ + "// 外掛在請求發往上游之前改寫請求,也可以在回答交給用戶端之前改寫回答。", + "// manifest 須為純資料;「設定」頁中的修改寫回 manifest。", + "", + "export const manifest = {", + " name: \"新外掛\",", + " api: 1,", + " description: \"在系統提示詞末尾附加「附加內容」中的文字。\",", + ' permissions: ["system"],', + ' on_error: "reject",', + " settings: { note: { type: \"string\", label: \"附加內容\", value: \"\" } },", + "};", + "", + "// 請求發往上游之前呼叫:修改 req 即生效,ctx.settings 為設定項的值。", + "// tw 提供常用的改寫函式,例如 tw.appendSystem 在系統提示詞末尾附加一段文字。", + "export function onRequest(req, ctx) {", + ' const note = String(ctx.settings.note ?? "").trim();', + ' if (note !== "") tw.appendSystem(req, note);', + "}", + ]), + enabled: "啟用", + enabledHint: "停用後此外掛不執行,適用範圍內的請求照常轉發。", + codeError: "程式碼無法載入", + codeErrorHint: "修復程式碼之後才能修改以下設定。", + codeErrorNoForm: "修復程式碼之後才能修改此外掛的設定。", + viewCode: "檢視程式碼", + diskChanged: "磁碟上的檔案已更改", + diskChangedHint: "此處是已確認的程式碼。儲存時將以此處的程式碼覆蓋磁碟上的檔案。", + reviewChanges: "稽核更改", + importFile: "從檔案匯入…", + tooLarge: (size: string) => `檔案為 ${size},超過 1 MB 的上限。`, + readFailed: "無法讀取此檔案。", + checking: "正在檢查程式碼", + cannotLoad: "程式碼無法載入", + loadFailed: "外掛程式碼讀取失敗", + noCode: "外掛檔案和已確認的程式碼均無法讀取。", + unsaved: "有未儲存的更改", + cancelled: "已取消,配置未改動。", + discardTitle: "放棄未儲存的更改", + discardDescription: "關閉之後,對設定和程式碼的更改都不會儲存。", + discardNewDescription: "關閉之後,此外掛不會安裝,程式碼和設定都不會保留。", + keepEditing: "繼續編輯", + discard: "放棄更改", + }, + ko: { + tabSettings: "설정", + enabled: "활성화됨", + unsaved: "저장하지 않은 변경 사항", + discard: "변경 사항 취소", + }, + es: { + tabSettings: "Configuración", + tabCode: "Código", + codeHasError: "El código no se puede cargar", + newTitle: "Añadir complemento", + install: "Instalar", + idLabel: "ID del complemento", + idHint: "Letras minúsculas, dígitos y guiones, hasta 40. No se puede cambiar después de la instalación.", + idProblems: { + bad: "Utilice solo letras minúsculas, dígitos y guiones, hasta 40.", + reserved: "Este ID está reservado y no se puede utilizar.", + taken: "Otro plugin ya utiliza este ID.", + }, + templateFailed: "No se pudo abrir la plantilla del complemento", + template: template([ + "// Un plugin cambia las peticiones antes de que lleguen a un nivel superior, y puede cambiar las respuestas antes de", + "// llegan al cliente. El manifiesto debe ser de datos simples: la pestaña Configuración escribe su", + "// cambia en ella.", + "", + "manifiesto de const de exportación = {", + " nombre: \"Nuevo plugin\",", + " api: 1,", + " descripción: \"Añade el texto de la configuración de la nota al final del prompt del sistema.\",", + " permisos: [\"sistema\"],", + " on_error: \"rechazar\",", + " configuración: { nota: < tipo: \"cadena\", etiqueta: \"Nota\", valor: \"\" } },", + "};", + "", + "// Ejecuta antes de que una solicitud vaya al upstream: los cambios a req surten efecto, y", + "// ctx.settings contiene los valores de la configuración. tw proporciona ediciones comunes, como", + "// tw.appendSystem, que añade texto al final del prompt del sistema.", + "función de exportación onRequest(req, ctx) {", + " const note = String(ctx.settings.note ??\").trim();", + " if (nota !== \"\") tw.appendSystem(req, nota);", + "}", + ]), + enabled: "Activado", + enabledHint: "Cuando está desactivado, el plugin no se ejecuta y las solicitudes a las que se aplica se reenvían como de costumbre.", + codeError: "El código no se puede cargar", + codeErrorHint: "Corregir el código para cambiar la configuración de abajo.", + codeErrorNoForm: "Fijar el código para cambiar la configuración de este complemento.", + viewCode: "Ver el código", + diskChanged: "El archivo en el disco cambió", + diskChangedHint: "Este es el código aprobado. Guardar sobreescribe el archivo en disco con él.", + reviewChanges: "Cambios en la revisión", + importFile: "Importar desde el archivo…", + tooLarge: (size: string) => `El archivo es ${size}, sobre el límite de 1 MB.`, + readFailed: "El archivo no se pudo leer.", + checking: "Comprobación del código", + cannotLoad: "El código no se puede cargar", + loadFailed: "El código del complemento no se pudo leer", + noCode: "Ni el archivo de plugin ni el código aprobado pueden ser leídos.", + unsaved: "Cambios sin guardar", + cancelled: "Cancelada. La configuración no fue cambiada.", + discardTitle: "Desechar los cambios no guardados", + discardDescription: "Una vez que el editor se cierra, los cambios en la configuración y el código no se guardan.", + discardNewDescription: "Una vez que el editor se cierra, el plugin no está instalado y el código y la configuración no se mantienen.", + keepEditing: "Seguir editando", + discard: "Descartar cambios", + }, + }, ); diff --git a/src/plugins/LogsDialog.i18n.tsx b/src/plugins/LogsDialog.i18n.tsx index a67fa966..5d498617 100644 --- a/src/plugins/LogsDialog.i18n.tsx +++ b/src/plugins/LogsDialog.i18n.tsx @@ -28,4 +28,36 @@ export const logsDialogText = messages( openRequest: (id: string) => `Open request #${id}`, close: "Close", }, + { + "zh-Hant": { + title: "日誌", + lead: (name: ReactNode) => <>外掛「{name}」透過 console 寫下的內容,新的在前。, + refresh: "重新整理", + empty: "尚無日誌", + emptyHint: "外掛呼叫 console.log 等方法時,寫下的內容顯示在這裡。", + loadFailed: "日誌讀取失敗", + levels: { log: "日誌", info: "資訊", warn: "警告", error: "錯誤" } as Record, + hooks: { request: "請求", reply: "回答" } as Record, + request: (id: string) => `請求 #${id}`, + openRequest: (id: string) => `開啟請求 #${id}`, + close: "關閉", + }, + ko: { + hooks: { request: "요청", reply: "Reply" } as Record, + close: "닫기", + }, + es: { + title: "Registros", + lead: (name: ReactNode) => <>Qué complemento “{name}” escribió a través de consola, el más nuevo primero., + refresh: "Actualizar", + empty: "Todavía no hay registros.", + emptyHint: "Lo que el plugin escribe con console.log y métodos similares aparece aquí.", + loadFailed: "Los registros no se pudieron cargar", + levels: { log: "registro", info: "info", warn: "advert", error: "error" } as Record, + hooks: { request: "Solicitud", reply: "Respuesta" } as Record, + request: (id: string) => `Solicitud #${id}`, + openRequest: (id: string) => `Abrir petición #${id}`, + close: "Cerrar", + }, + }, ); diff --git a/src/plugins/PluginsPage.i18n.tsx b/src/plugins/PluginsPage.i18n.tsx index b4b89df4..194d0520 100644 --- a/src/plugins/PluginsPage.i18n.tsx +++ b/src/plugins/PluginsPage.i18n.tsx @@ -110,6 +110,141 @@ export const pluginsPageText = messages( moveDown: (name: string) => `Move “${name}” down`, dragPlugin: (name: string) => `Drag to reorder “${name}”`, }, + { + "zh-Hant": { + pluginsUnit: (_n: number) => "個外掛", + changed: "檔案已更改", + failed: "載入失敗", + reorder: "調整順序", + add: "新增外掛", + emptyTitle: "尚無外掛", + emptyDescription: "外掛是一段 JavaScript,在請求發往上游之前改寫請求,在回答交給用戶端之前改寫回答。外掛在沙箱中執行,無法聯網、讀寫檔案,也看不到金鑰。", + loadFailed: "外掛列表讀取失敗", + order: (n: number) => `第 ${n} 個執行`, + appliesTo: "適用於", + settings: "設定", + trial: "試執行", + logs: "日誌", + remove: "刪除", + review: "稽核更改", + editCode: "編輯程式碼", + menu: { + settings: "設定…", + code: "程式碼…", + trial: "試執行…", + logs: "日誌…", + review: "稽核更改…", + remove: "刪除…", + }, + toggleFor: (name: string) => `啟用「${name}」`, + turnedOn: (name: ReactNode) => <>已啟用外掛「{name}」, + turnedOff: (name: ReactNode) => <>已停用外掛「{name}」, + changedTitle: (name: ReactNode) => <>外掛「{name}」的檔案已更改, + failedTitle: (name: ReactNode) => <>外掛「{name}」載入失敗, + changedRejecting: "確認更改之前,適用範圍內的請求將被拒絕。", + changedSkipping: "確認更改之前,此外掛不執行。", + failedRejecting: "修復之前,適用範圍內的請求將被拒絕。", + failedSkipping: "修復之前,此外掛不執行。", + deleteTitle: (name: ReactNode) => <>刪除外掛「{name}」, + deleteDescription: "外掛和它的設定將從配置中刪除,此後不再執行。", + reorderTitle: "調整順序", + reorderDescription: "外掛按此順序依次執行,後一個外掛處理的是前一個改寫後的內容。拖動或用箭頭調整位置。", + dragPlugin: (name: string) => `拖動調整「${name}」的位置`, + }, + ja: { + pluginsUnit: (_n: number) => "件のプラグイン", + active: "有効", + disabled: "無効", + changed: "ファイルが変更済み", + failed: "読み込み失敗", + reorder: "並べ替え", + add: "プラグインを追加", + emptyTitle: "プラグインがありません", + emptyDescription: "プラグインは JavaScript で、転送前にリクエストを、クライアントに返す前にレスポンスを書き換えます。サンドボックスで動作し、ネットワーク、ファイル、機密情報にはアクセスできません。", + loadFailed: "プラグイン一覧を読み込めませんでした", + order: (n: number) => `${n} 番目に実行`, + appliesTo: "適用先", + settings: "設定", + trial: "試行", + logs: "ログ", + remove: "削除", + review: "変更を確認", + editCode: "コードを編集", + menu: { settings: "設定…", code: "コード…", trial: "試行…", logs: "ログ…", review: "変更を確認…", remove: "削除…" }, + toggleFor: (name: string) => `「${name}」を有効にする`, + turnedOn: (name: ReactNode) => <>プラグイン「{name}」を有効にしました, + turnedOff: (name: ReactNode) => <>プラグイン「{name}」を無効にしました, + changedTitle: (name: ReactNode) => <>プラグイン「{name}」のファイルが変更されました, + failedTitle: (name: ReactNode) => <>プラグイン「{name}」を読み込めませんでした, + changedRejecting: "変更を確認するまで、対象のリクエストは拒否されます。", + changedSkipping: "変更を確認するまで、このプラグインは実行されません。", + failedRejecting: "問題を修正するまで、対象のリクエストは拒否されます。", + failedSkipping: "問題を修正するまで、このプラグインは実行されません。", + deleteTitle: (name: ReactNode) => <>プラグイン「{name}」を削除, + deleteDescription: "プラグインとその設定を削除します。削除すると実行されなくなります。", + reorderTitle: "並べ替え", + reorderDescription: "プラグインを一覧の順番に実行します。各プラグインは直前のプラグインが変更した内容を処理します。ドラッグまたは矢印で順番を変えられます。", + moveUp: (name: string) => `「${name}」を上に移動`, + moveDown: (name: string) => `「${name}」を下に移動`, + dragPlugin: (name: string) => `ドラッグして「${name}」を移動`, + }, + ko: { + settings: "설정", + remove: "삭제", + menu: { + settings: "설정…", + code: "Code…", + trial: "Trial run…", + logs: "Logs…", + review: "Review changes…", + remove: "Delete…", + }, + }, + es: { + pluginsUnit: (n: number) => (n === 1 ? "complemento" : "complementos"), + active: "activo", + disabled: "desactivado", + changed: "con un archivo cambiado", + failed: "no se pudo cargar", + reorder: "Reordenar", + add: "Añadir complemento", + emptyTitle: "Todavía no hay complementos", + emptyDescription: "Un plugin es una pieza de JavaScript que reescribe las peticiones antes de ir río arriba y responde antes de llegar al cliente. Los complementos se ejecutan en una caja de arena sin red, sin acceso a archivos y sin vista de secretos.", + loadFailed: "La lista de complementos no se pudo cargar", + order: (n: number) => `Corre ${ordinal(n)}`, + appliesTo: "Se aplica a", + settings: "Configuración", + trial: "Ejecución del ensayo", + logs: "Registros", + remove: "Eliminar", + review: "Cambios en la revisión", + editCode: "Editar código", + menu: { + settings: "Configuración…", + code: "Código…", + trial: "Carrera de prueba…", + logs: "Registros…", + review: "Revisión de cambios…", + remove: "Eliminar…", + }, + toggleFor: (name: string) => `Habilitar “${name}”`, + turnedOn: (name: ReactNode) => <>Complemento “{name}” activado, + turnedOff: (name: ReactNode) => <>Complemento “{name}” inhabilitado, + changedTitle: (name: ReactNode) => <>El archivo del complemento “{name}” cambiado, + failedTitle: (name: ReactNode) => <>Complemento “{name}” no se pudo cargar, + changedRejecting: "Hasta que se apruebe el cambio, las solicitudes a las que se aplica son rechazadas.", + changedSkipping: "Hasta que el cambio sea aprobado, el plugin no se ejecuta.", + failedRejecting: "Hasta que se fije, las solicitudes a las que se aplica son rechazadas.", + failedSkipping: "Hasta que no se arregle, el plugin no se ejecuta.", + deleteTitle: (name: ReactNode) => <>Eliminar el complemento “{name}”, + deleteDescription: "El plugin y sus ajustes se eliminan de la configuración y ya no se ejecuta.", + reorderTitle: "Reordenar", + reorderDescription: "Los plugins se ejecutan en este orden. Cada plugin funciona en lo que el antes de que se produjo. Arrastre un plugin o utilizar las flechas para moverlo.", + moveUp: (name: string) => `Mover “${name}” hacia arriba`, + moveDown: (name: string) => `Mover “${name}” hacia abajo`, + dragPlugin: (name: string) => `Arrastre para reordenar “${name}”`, + }, + }, ); function ordinal(n: number): string { diff --git a/src/plugins/TrialDialog.i18n.tsx b/src/plugins/TrialDialog.i18n.tsx index 5b5ad360..f476f866 100644 --- a/src/plugins/TrialDialog.i18n.tsx +++ b/src/plugins/TrialDialog.i18n.tsx @@ -44,4 +44,49 @@ export const trialDialogText = messages( noLogs: "This run wrote no logs.", close: "Close", }, + { + "zh-Hant": { + title: "試執行", + lead: (name: ReactNode) => <>用一條已記錄的請求執行「{name}」,不發往上游。, + request: "請求", + noneInScope: "最近的請求都不在此外掛的適用範圍內,以下是全部最近的請求。", + noRequests: "尚無可用的請求記錄。", + loadFailed: "請求記錄讀取失敗", + run: "執行", + runAgain: "再次執行", + result: "結果", + sides: { request: "請求", reply: "回答" } as Record, + unchanged: "外掛未改動這一部分。", + rejected: "外掛拒絕了這次請求。", + skipped: "外掛未在這一部分執行。", + failed: "執行出錯", + logs: "日誌", + noLogs: "這次執行沒有寫日誌。", + close: "關閉", + }, + ko: { + request: "요청", + sides: { request: "요청", reply: "Reply" } as Record, + close: "닫기", + }, + es: { + title: "Ejecución del ensayo", + lead: (name: ReactNode) => <>Ejecutar “{name}” en una solicitud registrada. Nada se envía del proveedor., + request: "Solicitud", + noneInScope: "Ninguna de las peticiones recientes están en el ámbito de este plugin, por lo que todas las solicitudes recientes se enumeran.", + noRequests: "No se dispone de solicitudes registradas.", + loadFailed: "No se pudo cargar el historial de peticiones", + run: "Corre", + runAgain: "Ejecutar de nuevo", + result: "Resultado", + sides: { request: "Solicitud", reply: "Respuesta" } as Record, + unchanged: "El plugin dejó esta parte sin cambios.", + rejected: "El complemento rechazó la solicitud.", + skipped: "El plugin no se ejecutó en esta parte.", + failed: "Falló la ejecución", + logs: "Registros", + noLogs: "Esta carrera no escribió ningún registro.", + close: "Cerrar", + }, + }, ); diff --git a/src/plugins/defaults.ts b/src/plugins/defaults.ts index 0a0aeaed..6ef539be 100644 --- a/src/plugins/defaults.ts +++ b/src/plugins/defaults.ts @@ -20,17 +20,15 @@ import type { SettingSpecView } from "@/types"; interface Words { name?: string; description?: string; - settings?: Record; + settings?: Partial>; } -interface Entry { +type Entry = { id: string; manifest_name: string; - zh: Words; - en: Words; -} +} & Record; -const ENTRIES = (TABLE as unknown as { plugins: Entry[] }).plugins; +const ENTRIES: Entry[] = TABLE.plugins; function wordsOf(id: string | null | undefined, name: string): Words | null { if (!id) return null; diff --git a/src/plugins/fields.i18n.ts b/src/plugins/fields.i18n.ts index 03da6d71..a556e2f0 100644 --- a/src/plugins/fields.i18n.ts +++ b/src/plugins/fields.i18n.ts @@ -42,4 +42,49 @@ export const pluginFieldsText = messages( settings: "Settings", numberBad: (label: string) => `“${label}” needs a number.`, }, + { + "zh-Hant": { + matches: { + clients: "", + models: "按發給上游的模型名匹配;路由改寫過模型名的,按改寫之後的名字。", + upstreams: "按發往的上游匹配,請求和回答都適用。", + }, + hint: { + clients: "用戶端的名字,例如 claude-code。可新增多個,支援 * 通配。", + models: "模型名,例如 deepseek-*。可新增多個,支援 * 通配。", + upstreams: "上游的名字。可新增多個,支援 * 通配。", + }, + placeholder: { clients: "新增用戶端", models: "新增模型", upstreams: "新增上游" }, + enterToAdd: "回車新增", + removeShort: "刪除", + remove: (x: string) => `刪除 ${x}`, + needOne: (part: string) => `${part}選了「指定」,至少新增一項。`, + settings: "設定項", + numberBad: (label: string) => `「${label}」需要填寫數字。`, + }, + ko: { + removeShort: "제거", + settings: "설정", + }, + es: { + some: "Específico", + matches: { + clients: "", + models: "Coincide con el nombre del modelo enviado en sentido ascendente; cuando el enrutamiento lo reescriba, el nombre reescrito.", + upstreams: "Coincide con el curso anterior a la solicitud va a, para solicitudes y respuestas por igual.", + }, + hint: { + clients: "Nombres de clientes, como claude-code. Añadir tantos como sea necesario; * coincide con cualquier cosa.", + models: "Nombres de modelos, como deepseek-*. Agregue tantos como sea necesario; * coincide con cualquier cosa.", + upstreams: "Nombres ascendentes. Agrega tantos como sea necesario; * coincide con cualquier cosa.", + }, + placeholder: { clients: "Añadir un cliente", models: "Añadir un modelo", upstreams: "Añadir un curso ascendente" }, + enterToAdd: "Introduzca para añadir", + removeShort: "Quitar", + remove: (x: string) => `Eliminar ${x}`, + needOne: (part: string) => `${part} se establece en Específico: añadir al menos uno.`, + settings: "Configuración", + numberBad: (label: string) => `“${label}” necesita un número.`, + }, + }, ); diff --git a/src/plugins/labels.i18n.ts b/src/plugins/labels.i18n.ts index 1483f44e..4328782f 100644 --- a/src/plugins/labels.i18n.ts +++ b/src/plugins/labels.i18n.ts @@ -133,6 +133,124 @@ export const pluginLabelsText = messages( cpu: (ms: string) => `${ms} ms`, lessThanMs: "under 0.1 ms", }, + { + "zh-Hant": { + permissions: { + system: { short: "系統提示詞", what: "讀取和修改系統提示詞", note: "" }, + messages: { + short: "對話訊息", + what: "讀取和修改對話訊息中的文字和工具結果", + note: "可以向對話中加入指令", + }, + tools: { short: "工具定義", what: "讀取和修改工具定義", note: "會改變模型可用的工具" }, + params: { + short: "請求引數", + what: "讀取和修改模型名、max_tokens、溫度等引數", + note: "可能改變發給上游的模型和產生的費用", + }, + reply_text: { short: "回答文字", what: "讀取和修改回答中的文字", note: "" }, + reply_tool_calls: { + short: "回答中的工具呼叫", + what: "修改、刪除和新增回答中的工具呼叫", + note: "高風險:可以改寫用戶端將要執行的命令和檔案路徑", + }, + } as Record, + highRisk: "高風險", + blockMode: "回答文字整段到齊後才顯示", + kinds: { conversation: "對話", embeddings: "向量化", completions: "補全" } as Record, + alsoHandles: (list: string) => `也處理:${list}`, + onlyHandles: (list: string) => `僅處理:${list}`, + status: { + ok: "生效中", + disabled: "已停用", + changed: "檔案已更改", + error: "載入失敗", + } as Record, + outcomes: { + unchanged: "未改動", + changed: "已改寫", + rejected: "已拒絕", + error: "出錯", + skipped: "已跳過", + } as Record, + hooks: { request: "請求", reply: "回答" } as Record, + onError: "出錯時", + onErrorOptions: { reject: "拒絕這次請求", skip: "跳過此外掛" }, + scope: "適用範圍", + scopeParts: { clients: "用戶端", models: "模型", upstreams: "上游" }, + allRequests: "全部請求", + allOf: { clients: "全部用戶端", models: "全部模型", upstreams: "全部上游" }, + }, + ko: { + status: { + ok: "Active", + disabled: "비활성화됨", + changed: "File changed", + error: "Failed to load", + } as Record, + hooks: { request: "요청", reply: "Reply" } as Record, + scopeParts: { clients: "클라이언트", models: "모델", upstreams: "업스트림" }, + allOf: { clients: "All clients", models: "All models", upstreams: "모든 업스트림" }, + }, + es: { + permissions: { + system: { short: "Indicación del sistema", what: "Lea y cambie el prompt del sistema", note: "" }, + messages: { + short: "Mensajes", + what: "Leer y cambiar el texto y la herramienta resulta en mensajes de conversación", + note: "Puede añadir instrucciones a la conversación", + }, + tools: { short: "Definiciones de las herramientas", what: "Lea y cambie las definiciones de la herramienta", note: "Cambios en las herramientas que el modelo puede utilizar" }, + params: { + short: "Parámetros", + what: "Leer y cambiar el modelo, max_tokens, temperatura y otros parámetros", + note: "Puede cambiar el modelo enviado arriba y lo que cuesta", + }, + reply_text: { short: "Responder texto", what: "Leer y cambiar el texto de las respuestas", note: "" }, + reply_tool_calls: { + short: "Llamadas de herramientas en las respuestas", + what: "Cambiar, eliminar y añadir llamadas de herramientas en las respuestas", + note: "Alto riesgo: puede reescribir los comandos y las rutas de archivo que un cliente está a punto de ejecutar", + }, + } as Record, + highRisk: "Alto riesgo", + added: "Nuevo", + blockMode: "Responder texto aparece una vez que cada bloque está completo", + kinds: { conversation: "conversaciones", embeddings: "incrustaciones", completions: "finalizaciones" } as Record, + alsoHandles: (list: string) => `También manijas: ${list}`, + onlyHandles: (list: string) => `Solo manijas: ${list}`, + status: { + ok: "Activo", + disabled: "Desactivado", + changed: "Archivo cambiado", + error: "Fallo al cargar", + } as Record, + outcomes: { + unchanged: "Sin cambios", + changed: "Cambiado", + rejected: "Rechazada", + error: "Error", + skipped: "Omitir", + } as Record, + hooks: { request: "Solicitud", reply: "Respuesta" } as Record, + onError: "Error", + onErrorOptions: { reject: "Rechazar la solicitud", skip: "Omitir este complemento" }, + scope: "Se aplica a", + scopeParts: { clients: "Clientes", models: "Modelos", upstreams: "Proveedores" }, + all: "Todos", + allRequests: "Todas las solicitudes", + allOf: { clients: "Todos los clientes", models: "Todos los modelos", upstreams: "Todos los proveedores" }, + lessThanMs: "menos de 0,1 ms", + }, + }, ); /** 统计:运行几次、改写几次。插件页的那一格和它的悬停 */ @@ -167,4 +285,36 @@ export const pluginStatsText = messages( lastError: "Last error", }, }, + { + "zh-Hant": { + runs: (n: number) => `${n.toLocaleString()} 次執行`, + changedShort: (n: number) => `改寫 ${n.toLocaleString()}`, + errorsShort: (n: number) => `出錯 ${n.toLocaleString()}`, + noRuns: "尚未執行", + since: "閘道器啟動以來", + lines: { + calls: "執行", + changed: "改寫", + rejected: "拒絕", + errors: "出錯", + cpu: "平均 CPU 時間", + lastError: "最近一次出錯", + }, + }, + es: { + runs: (n: number) => plural(n, "ejecutar", "corre"), + changedShort: (n: number) => `${n.toLocaleString()} cambiado`, + errorsShort: (n: number) => plural(n, "error", "errores"), + noRuns: "Todavía no corre.", + since: "Desde que comenzó el portal", + lines: { + calls: "Corre", + changed: "Cambiado", + rejected: "Rechazada", + errors: "Errores", + cpu: "Tiempo medio de la CPU", + lastError: "Último error", + }, + }, + }, ); diff --git a/src/plugins/parts.i18n.ts b/src/plugins/parts.i18n.ts index 78b1a2fc..ca3159f2 100644 --- a/src/plugins/parts.i18n.ts +++ b/src/plugins/parts.i18n.ts @@ -27,4 +27,28 @@ export const pluginPartsText = messages( permissionRemoved: "No longer requested", errorAt: (line: number, column: number | null) => (column != null ? `line ${line}, column ${column}` : `line ${line}`), }, + { + "zh-Hant": { + unchangedLines: (n: number) => `${n.toLocaleString()} 行未改動`, + tally: (added: number, removed: number) => `新增 ${added.toLocaleString()} 行,刪除 ${removed.toLocaleString()} 行`, + noDifference: "內容相同", + invisible: (code: string) => `看不見的字元 ${code}`, + loadingCode: "正在開啟程式碼", + codeLabel: "外掛程式碼", + permissions: "申請的許可權", + permissionRemoved: "不再申請", + }, + es: { + lines: (n: number) => `${n.toLocaleString()} ${n === 1 ? "línea" : "líneas"}`, + unchangedLines: (n: number) => `${n.toLocaleString()} sin cambios ${n === 1 ? "línea" : "líneas"}`, + tally: (added: number, removed: number) => `${added.toLocaleString()} añadido, ${removed.toLocaleString()} eliminado`, + noDifference: "Los contenidos son los mismos", + invisible: (code: string) => `Carácter invisible ${code}`, + loadingCode: "Apertura del código", + codeLabel: "Código del complemento", + permissions: "Permisos solicitados", + permissionRemoved: "Ya no se ha solicitado", + errorAt: (line: number, column: number | null) => (column != null ? `línea ${line}, columna ${column}` : `línea ${line}`), + }, + }, ); diff --git a/src/plugins/write.i18n.ts b/src/plugins/write.i18n.ts index e6ba8819..7d3a4b20 100644 --- a/src/plugins/write.i18n.ts +++ b/src/plugins/write.i18n.ts @@ -9,4 +9,12 @@ export const writeText = messages( approvedMissing: "The approved code of this plugin is missing, so it cannot be switched on or off. Save the code in the plugin's Code tab first.", }, + { + "zh-Hant": { + approvedMissing: "此外掛已確認的程式碼不存在,無法切換開關。請先在此外掛的內碼表中儲存程式碼。", + }, + es: { + approvedMissing: "Falta el código aprobado de este plugin, por lo que no se puede activar o desactivar. Guardar el código en la pestaña Código del plugin primero.", + }, + }, ); diff --git a/src/repair.i18n.ts b/src/repair.i18n.ts index 03e36860..b909caa3 100644 --- a/src/repair.i18n.ts +++ b/src/repair.i18n.ts @@ -19,4 +19,23 @@ export const repairText = messages( line: (n: number) => `Line ${n}`, history: "The version before the repair is kept in the backups.", }, + { + "zh-Hant": { + title: "可以一鍵修復", + action: "一鍵修復", + value: (field: string, value: string, now: string) => `${field}:${value} 改為預設值 ${now}`, + valueNoDefault: (field: string, value: string) => `${field}:刪除 ${value},改用預設值`, + field: (field: string) => `刪除不認識的欄位 ${field}`, + history: "修復前的版本儲存在備份中。", + }, + es: { + title: "Se puede reparar con un solo clic", + action: "Reparación", + value: (field: string, value: string, now: string) => `${field}: ${value} → por defecto ${now}`, + valueNoDefault: (field: string, value: string) => `${field}: eliminar ${value} y utilizar el valor predeterminado`, + field: (field: string) => `Eliminar el campo desconocido ${field}`, + line: (n: number) => `Línea ${n}`, + history: "La versión anterior a la reparación se mantiene en las copias de seguridad.", + }, + }, ); diff --git a/src/routing/ChainMap.i18n.ts b/src/routing/ChainMap.i18n.ts index 105303ea..67722806 100644 --- a/src/routing/ChainMap.i18n.ts +++ b/src/routing/ChainMap.i18n.ts @@ -41,4 +41,36 @@ export const chainMapText = messages( denyBy: (route: string, rule: string) => `${route} · ${rule}`, inFlight: (n: number) => (n === 1 ? "1 request in progress" : `${n} requests in progress`), }, + { + "zh-Hant": { + label: (keys: number, routes: number, groups: number, upstreams: number) => `路由圖:${keys} 把金鑰、${routes} 條路由、${groups} 個策略組、${upstreams} 個上游`, + keys: "金鑰", + groups: "策略組", + defaultRoute: "預設路由", + ruleCount: (n: number) => `${n} 條規則`, + keyCount: (n: number) => `${n} 把金鑰`, + unusedRoute: "未被金鑰使用", + inFlight: (n: number) => `${n} 個請求進行中`, + }, + ko: { + label: (keys: number, routes: number, groups: number, upstreams: number) => `Routing map: ${keys} ${keys === 1 ? "key" : "keys"}, ${routes} ${routes === 1 ? "route" : "routes"}, ${groups} ${groups === 1 ? "group" : "groups"}, ${upstreams} ${upstreams === 1 ? "업스트림" : "upstreams"}`, + keys: "키", + upstreams: "업스트림", + }, + es: { + label: (keys: number, routes: number, groups: number, upstreams: number) => `Mapa de enrutamiento: ${keys} ${keys === 1 ? "tecla" : "teclas"}, ${routes} ${routes === 1 ? "ruta" : "rutas"}, ${groups} ${groups === 1 ? "grupo" : "grupos"}, ${upstreams} ${upstreams === 1 ? "proveedor" : "del proveedor"}`, + keys: "Claves", + routes: "Rutas", + groups: "Grupos", + upstreams: "Proveedores", + defaultRoute: "Ruta predeterminada", + usesRoute: (name: string) => `Utiliza la ruta “${name}”`, + ruleCount: (n: number) => (n === 1 ? "1 artículo" : `${n} normas`), + keyCount: (n: number) => (n === 1 ? "1 tecla" : `${n} teclas`), + unusedRoute: "No utilizado por ninguna tecla", + unreferenced: "Sin referencia", + unreachable: "No utilizado por ninguna ruta", + inFlight: (n: number) => (n === 1 ? "1 solicitud en curso" : `${n} solicitudes en curso`), + }, + }, ); diff --git a/src/routing/DryRunDialog.i18n.ts b/src/routing/DryRunDialog.i18n.ts index ec158413..430c5332 100644 --- a/src/routing/DryRunDialog.i18n.ts +++ b/src/routing/DryRunDialog.i18n.ts @@ -114,4 +114,107 @@ export const dryRunText = messages( missedBecause: (why: string) => `Not matched: ${why}`, missed: "Not matched", }, + { + "zh-Hant": { + description: "按給定請求計算匹配結果。不發出請求,不產生費用。", + unsaved: "未儲存", + key: "金鑰", + keyConditions: "規則中的金鑰條件按此金鑰判斷。", + dialect: "用戶端格式", + inputTokens: "輸入 token", + notSet: "不設定", + flags: { cache: "帶快取", tools: "帶工具", image: "帶圖片", thinking: "擴充套件思考", stream: "流式" }, + toolCount: "工具數", + intent: "輔助請求", + userRequest: "無(使用者請求)", + failed: "無法計算", + defaultRoute: " · 預設路由", + unsavedChanges: " · 未儲存的修改", + matchedRule: "命中規則", + position: (n: number) => ` · 第 ${n} 條`, + attempts: "嘗試順序", + circuitOpen: "熔斷中,將跳過", + weight: (n: number) => `權重 ${n}`, + ttftNone: "首 token 暫無資料", + successNone: "成功率暫無資料", + share: (pct: string) => `佔比 ${pct}`, + converted: (formats: string) => `需轉換格式:${formats}`, + skipped: "已跳過", + rewrites: "引數改寫", + trace: "規則匹配明細", + viaGroup: (name: string) => `轉發至策略組「${name}」`, + toUpstream: (name: string) => `轉發至上游「${name}」`, + toPinned: (provider: string, model: string) => `轉發至指定模型 ${provider} · ${model}`, + sends: "發出 ", + via: { alias: "別名", rule: "規則改寫", pinned: "指定模型" }, + denied: "拒絕", + unavailable: "選中的上游均無法服務此請求,請求將返回錯誤", + noMatch: "無規則命中,請求將返回錯誤", + intercepted: "本地應答", + interceptedWhat: "閘道器直接應答這一類請求,不傳送到上游,也不產生費用。路由規則不參與。", + howToRoute: "要讓它按規則走,在「輔助請求」中將這一類改為「轉發」。", + decides: "命中 · 決定去向", + applies: "命中 · 應用改寫引數或安全要求", + decidedBy: (n: number) => `命中 · 去向已由第 ${n} 條決定`, + phaseTwo: "選定上游後判斷,試算不計算此條", + }, + ko: { + key: "키", + model: "모델", + notSet: "설정되지 않음", + }, + es: { + description: "Calcula cómo se enrutaría la solicitud dada. No se envía ninguna solicitud y no se incurre en ningún costo.", + route: "Ruta", + unsaved: "Sin guardar", + key: "Clave", + usesRoute: (name: string) => `Utiliza la ruta “${name}”`, + keyConditions: "Las condiciones clave de las normas se evalúan en relación con esta clave.", + noKey: "No especificado", + model: "Modelo", + dialect: "Formato del cliente", + inputTokens: "tokens de entrada", + notSet: "Sin configurar", + flags: { cache: "Con caché", tools: "Con herramientas", image: "Con imágenes", thinking: "Pensar", stream: "Streaming" }, + toolCount: "Conteo de herramientas", + intent: "Solicitud complementaria", + userRequest: "Ninguno (solicitud de usuario)", + failed: "No se pudo calcular", + reason: (reason: string) => `Motivo: ${reason}`, + defaultRoute: " · Ruta predeterminada", + unsavedChanges: " · Cambios no guardados", + matchedRule: "Regla armonizada", + position: (n: number) => ` · regla ${n}`, + attempts: "Intentos", + circuitOpen: "Circuito abierto, se saltará", + weight: (n: number) => `Peso ${n}`, + ttft: (ms: string) => `Primer token ${ms}`, + ttftNone: "No hay datos de primera toma todavía", + success: (pct: string) => `Tasa de éxito ${pct}`, + successNone: "Todavía no hay tasa de éxito", + share: (pct: string) => `Parte ${pct}`, + converted: (formats: string) => `Conversión de formato: ${formats}`, + skipped: "Omitir", + rewrites: "Reescribe", + trace: "Detalles de coincidencia de reglas", + viaGroup: (name: string) => `Reenviado al grupo “${name}”`, + toUpstream: (name: string) => `Reenviado a del proveedor “${name}”`, + toPinned: (provider: string, model: string) => `Reenviado al modelo especificado ${provider} · ${model}`, + sends: "Envíos ", + via: { alias: "alias", rule: "reescribir la regla", pinned: "modelo especificado" }, + denied: "Denegado", + unavailable: "Ningún upstream seleccionado puede servir a esta solicitud; devolverá un error", + noMatch: "Ninguna regla coincide; la solicitud devolverá un error", + intercepted: "Respuestas locales", + interceptedWhat: "La puerta de enlace responde directamente a este tipo. Nada se envía del proveedor y no se incurre en ningún costo. Las reglas de enrutamiento no toman parte.", + howToRoute: "Para que las reglas decidan, establecer este tipo de \"Adelante\" bajo Auxiliar.", + decides: "Coincidido · decide el destino", + applies: "Coincidido · aplica reescrituras de parámetros o requisitos de seguridad", + decidedBy: (n: number) => `Coincidido · destino ya decidido por regla ${n}`, + matched: "Coincidencia", + phaseTwo: "Evaluado después de seleccionar una corriente ascendente; no se calcula en seco", + missedBecause: (why: string) => `No coincide: ${why}`, + missed: "No coincide", + }, + }, ); diff --git a/src/routing/GroupDialog.i18n.ts b/src/routing/GroupDialog.i18n.ts index f68e3676..6c2881d0 100644 --- a/src/routing/GroupDialog.i18n.ts +++ b/src/routing/GroupDialog.i18n.ts @@ -71,4 +71,73 @@ export const groupDialogText = messages( "latency-health": "Starting from the weights, faster upstreams that fail less get more requests.", } satisfies Record, }, + { + "zh-Hant": { + noMembers: "至少選擇一個上游", + editTitle: (name: string) => `編輯策略組「${name}」`, + duplicateTitle: "複製策略組", + intro: "規則可以轉發至策略組,由策略決定使用其中哪個上游。", + selectedCount: (n: number) => `已選 ${n} 個`, + noUpstreams: "尚無上游", + dragMember: (name: string) => `拖動調整 ${name} 的位置`, + preferred: "優先使用", + selectUpstream: "選中", + orderSelectOnly: "儲存後,下一次請求發往選中的上游。無法讀取的加密歷史或上游儲存的歷史會報錯。", + setPreferred: "設為優先", + orderSelect: "拖動調整順序。選定的上游不可用時,按順序使用其餘成員。", + orderFallback: "拖動調整順序:依次使用,前一個不可用時使用下一個。", + orderOther: "拖動調整順序。排序依據相同時按此順序。", + orderBalance: "權重為 1 到 100 的整數。拖動調整順序。排序依據相同時按此順序。", + weight: "權重", + weightOf: (name: string) => `${name} 的權重`, + weightInvalid: (name: string) => `${name} 的權重須為 1 到 100 的整數`, + balanceBy: "分配依據", + balanceDesc: { + weights: "請求按成員權重的比例分配。", + latency: "以權重為基礎,速度快的上游分到更多請求。", + health: "以權重為基礎,失敗少的上游分到更多請求。", + "latency-health": "以權重為基礎,速度快、失敗少的上游分到更多請求。", + } satisfies Record, + }, + ko: { + noUpstreams: "업스트림이 없습니다.", + upstream: "업스트림", + toggleMember: (on: boolean, name: string) => `${on ? "제거" : "Add"} ${name}`, + }, + es: { + noMembers: "Seleccionar por lo menos una del proveedor", + editTitle: (name: string) => `Editar grupo “${name}”`, + duplicateTitle: "Grupo duplicado", + referencedBy: (refs: { + route: string; + rule: string; + }[]) => `Referenciada por ${andList(refs.map((r) => `“${r.route} · ${r.rule}”`))}.`, + intro: "Las reglas pueden transmitirse a un grupo, y su estrategia decide cuál de sus principios se utiliza.", + selectedCount: (n: number) => `${n} seleccionado`, + noUpstreams: "Todavía no hay proveedores.", + upstream: "Proveedor", + dragMember: (name: string) => `Arrastre para reordenar ${name}`, + toggleMember: (on: boolean, name: string) => `${on ? "Quitar" : "Añadir"} ${name}`, + disabledSuffix: " · Discapacitados", + preferred: "Preferido", + activeUpstream: "Activo", + selectUpstream: "Seleccionar", + orderSelectOnly: "Una vez guardada, la siguiente petición va a la fuente seleccionada. El historial cifrado ilegible o almacenado ascendentemente devuelve un error.", + setPreferred: "Establecer como prefiera", + orderSelect: "Arrastrar para reordenar. Cuando el upstream seleccionado no está disponible, los otros miembros se utilizan en orden.", + orderFallback: "Arrastrar para reordenar: los miembros se utilizan a su vez, moviéndose al siguiente cuando uno no está disponible.", + orderOther: "Arrastrar para reordenar. Las corbatas se rompen por esta orden.", + orderBalance: "Los pesos son números enteros de 1 a 100. Arrastrar a reordenar. Los lazos se rompen por este orden.", + weight: "Peso", + weightOf: (name: string) => `Peso de ${name}`, + weightInvalid: (name: string) => `El peso de ${name} debe ser un número entero de 1 a 100`, + balanceBy: "Distribuir por", + balanceDesc: { + weights: "Las solicitudes se dividen por pesos de los miembros.", + latency: "A partir de los pesos, las del proveedor más rápidas reciben más peticiones.", + health: "A partir de los pesos, del proveedor que fallan menos obtener más solicitudes.", + "latency-health": "A partir de las pesas, las del proveedor más rápidas que fallan menos reciben más peticiones.", + } satisfies Record, + }, + }, ); diff --git a/src/routing/GroupTable.i18n.ts b/src/routing/GroupTable.i18n.ts index 223b99a4..c7d7ac5b 100644 --- a/src/routing/GroupTable.i18n.ts +++ b/src/routing/GroupTable.i18n.ts @@ -31,4 +31,34 @@ export const groupTableText = messages( noGroups: "No custom groups yet", noGroupsDesc: "Rules can forward to a group, and its strategy decides which of its upstreams is used.", }, + { + "zh-Hant": { + builtin: "內建", + listOrder: "按上游列表順序", + prefer: "優先使用", + preferredTag: "優先", + selectedTag: "已選", + selectedOnly: "僅轉發到選中的上游", + switchTo: "切換到", + noGroups: "尚無自定義策略組", + noGroupsDesc: "規則可以轉發至策略組,由策略決定使用其中哪個上游。", + }, + ko: { + allUpstreams: "모든 업스트림", + }, + es: { + references: "Referenciada por", + allUpstreams: "Todos los proveedores", + builtin: "Incorporado", + listOrder: "En orden de lista ascendente", + unreferenced: "Sin referencia", + prefer: "Preferido en la fase anterior", + preferredTag: "Preferido", + selectedTag: "Seleccionado", + selectedOnly: "Sólo el administrador seleccionado recibe solicitudes", + switchTo: "Cambiar a", + noGroups: "Todavía no hay grupos personalizados", + noGroupsDesc: "Las reglas pueden transmitirse a un grupo, y su estrategia decide cuál de sus principios se utiliza.", + }, + }, ); diff --git a/src/routing/PinnedModels.i18n.ts b/src/routing/PinnedModels.i18n.ts index e55c24b0..a26bfcc8 100644 --- a/src/routing/PinnedModels.i18n.ts +++ b/src/routing/PinnedModels.i18n.ts @@ -23,4 +23,25 @@ export const pinnedModelsText = messages( model: "Model name", remove: (n: number) => `Remove specified model ${n}`, }, + { + "zh-Hant": { + addModel: "新增模型", + addBackup: "新增備用", + note: "按順序傳送,前一個失敗換下一個。模型名原樣發出,不經過別名表。", + provider: (n: number) => `第 ${n} 個指定模型的上游`, + chooseProvider: "選擇上游", + remove: (n: number) => `刪除第 ${n} 個指定模型`, + }, + es: { + addModel: "Añadir modelo", + addBackup: "Añadir copia de seguridad", + note: "Enviado en orden; cuando uno falla, se usa el siguiente. Los nombres de los modelos se envían como escritos, sin pasar por la tabla de alias.", + provider: (n: number) => `Corriente ascendente del modelo especificado ${n}`, + chooseProvider: "Seleccione un cursor", + missing: (name: string) => `${name} (no encontrado)`, + disabled: (name: string) => `${name} (inhabilitado)`, + model: "Nombre del modelo", + remove: (n: number) => `Eliminar el modelo especificado ${n}`, + }, + }, ); diff --git a/src/routing/ProbesTab.i18n.ts b/src/routing/ProbesTab.i18n.ts index 392de9a4..d94ae4bb 100644 --- a/src/routing/ProbesTab.i18n.ts +++ b/src/routing/ProbesTab.i18n.ts @@ -22,4 +22,26 @@ export const probesTabText = messages( ruleHint: "Rules can match the kinds set to “Forward” with the “Auxiliary request” condition, for example to send them to a lower-cost upstream.", }, + { + "zh-Hant": { + intro: "配置用戶端輔助請求及聯網工具的執行方式。設為轉發的請求繼續按路由規則選擇上游。", + kind: "請求/工具", + mode: "處理方式", + intercept: "本地應答", + interceptWhat: "由閘道器直接應答,不傳送到上游,不產生費用。", + forward: "轉發", + forwardWhat: "和普通請求一樣按路由規則轉發,按轉發到的上游產生費用。", + ruleHint: "規則可用「輔助請求」條件匹配設為轉發的類別,例如分流至費用更低的上游。", + }, + es: { + intro: "Elija cómo se manejan las peticiones auxiliares del cliente y las herramientas web. Las solicitudes reenviadas continúan a través de las reglas de enrutamiento.", + kind: "Solicitud / herramienta", + mode: "Manipulación", + intercept: "Respuesta local", + interceptWhat: "La puerta de enlace responde directamente. Nada se envía del proveedor y no se incurre en ningún costo.", + forward: "Adelante", + forwardWhat: "Reenviado por las reglas de encaminamiento como cualquier otra petición, con los costos de acuerdo con la corriente ascendente a la que va.", + ruleHint: "Las reglas pueden coincidir con los tipos establecidos en “Avanzar” con la condición “Solicitud auxiliar”, por ejemplo para enviarlos a un costo ascendente más bajo.", + }, + }, ); diff --git a/src/routing/RouteConfirmDialogs.i18n.ts b/src/routing/RouteConfirmDialogs.i18n.ts index 6332de54..bf0b526a 100644 --- a/src/routing/RouteConfirmDialogs.i18n.ts +++ b/src/routing/RouteConfirmDialogs.i18n.ts @@ -30,4 +30,33 @@ export const routeConfirmText = messages( defaultOption: (name: string) => `${name} (default route)`, defaultRoute: "Default route", }, + { + "zh-Hant": { + setDefaultTitle: (name: string) => `將「${name}」設為預設路由`, + keysWillMove: "未指定路由的金鑰將改用此路由。", + noKeysMove: "當前所有金鑰均已指定路由,更換預設路由不影響現有金鑰。", + cutover: "儲存後,下一次請求使用新路由。已發出的請求可以完成。如果新上游無法讀取加密歷史或上游儲存的歷史,用戶端會收到錯誤並提示新建對話。", + previousDefault: "預設", + keepsRoute: (name: string) => `「${name}」保留為普通路由,可繼續指定給金鑰。`, + deleteTitle: (name: string) => `刪除路由「${name}」`, + usersMove: "以下金鑰使用此路由,刪除後改用所選路由。可從備份中恢復。", + unused: "此路由未被金鑰使用。刪除後可從備份中恢復。", + defaultOption: (name: string) => `${name}(預設路由)`, + defaultRoute: "預設路由", + }, + es: { + setDefaultTitle: (name: string) => `Establecer “${name}” como la ruta predeterminada`, + keysWillMove: "Las teclas sin una ruta asignada cambiarán a esta ruta.", + noKeysMove: "Cada clave ya tiene una ruta asignada, por lo que cambiar la ruta predeterminada no afecta a las claves existentes.", + cutover: "Una vez guardada, la siguiente petición utiliza la nueva ruta. Las peticiones ya enviadas pueden terminar. Si el nuevo historial cifrado o almacenado en el inicio del proceso, el cliente recibe un error pidiéndole que inicie una nueva conversación.", + previousDefault: "predeterminado", + keepsRoute: (name: string) => `“${name}” sigue siendo una ruta regular y todavía se puede asignar a las teclas.`, + deleteTitle: (name: string) => `Suprímase la ruta “${name}”`, + usersMove: "Las teclas de abajo usan esta ruta y cambiarán a la ruta seleccionada. La ruta se puede restaurar desde las copias de seguridad.", + unused: "Ninguna clave usa esta ruta. Una vez eliminada, puede restaurarse desde las copias de seguridad.", + reassignTo: "Reasignar a", + defaultOption: (name: string) => `${name} (ruta predeterminada)`, + defaultRoute: "Ruta predeterminada", + }, + }, ); diff --git a/src/routing/RouteDialog.i18n.ts b/src/routing/RouteDialog.i18n.ts index 09357392..3a145360 100644 --- a/src/routing/RouteDialog.i18n.ts +++ b/src/routing/RouteDialog.i18n.ts @@ -96,4 +96,90 @@ export const routeDialogText = messages( `Also matches the ${aliases.length === 1 ? "alias that points" : "aliases that point"} to these models: ${aliases.join(", ")}`, backups: (list: string[]) => `Backup: ${list.join(", ")}`, }, + { + "zh-Hant": { + duplicate: "複製", + editTitle: (name: string) => `編輯路由「${name}」`, + duplicateTitle: "複製路由", + intro: "請求自上而下逐條匹配,第一條命中的轉發或拒絕規則決定去向。", + keys: "使用此路由的金鑰", + defaultKeys: "未指定路由的金鑰使用預設路由。", + allAssigned: "所有金鑰均已指定其他路由", + keyMoves: (joining: string[], leaving: string[]) => [ + joining.length ? `${joining.join("、")} 將改用此路由` : "", + leaving.length ? `${leaving.join("、")} 將改用預設路由` : "", + ] + .filter(Boolean) + .join(";") + "。", + usesRoute: (name: string) => `當前使用路由「${name}」`, + usesDefault: "當前使用預設路由", + rules: "規則", + rule: "規則", + conditions: "條件", + onMatch: "命中後", + dragRule: (name: string) => `拖動調整規則「${name}」的位置`, + noEffect: "不會生效", + phaseTwo: "選定上游後", + noHits: (span: HitSpan) => `${spanZh(span)}內未命中`, + ruleActions: (name: string) => `規則「${name}」的操作`, + noRules: "尚無規則", + shadowed: (names: string[]) => `${names.map((n) => `「${n}」`).join("、")}位於兜底規則之後,轉發與拒絕不會生效。`, + liftShadowed: "移至兜底規則之前", + noCatchAll: "尚無兜底規則。未命中任何規則的請求將返回錯誤。", + addCatchAll: "新增兜底規則", + alsoAliasesOf: (aliases: string[]) => `也匹配指向它的別名 ${aliases.join("、")}`, + alsoAliases: (aliases: string[]) => `也匹配指向這些模型的別名 ${aliases.join("、")}`, + backups: (list: string[]) => `備用 ${list.join("、")}`, + }, + ko: { + rules: "규칙", + rule: "규칙", + }, + es: { + catchAllName: "Atrapa todo", + insertAbove: "Insertar arriba…", + duplicate: "Duplicar", + moveUp: "Subir", + moveDown: "Bajar", + editTitle: (name: string) => `Editar ruta “${name}”`, + duplicateTitle: "Duplicar ruta", + intro: "Las peticiones se comparan con las reglas de arriba a abajo; la primera regla de emparejamiento hacia adelante o negar decide el destino.", + keys: "Teclas usando esta ruta", + defaultKeys: "Las teclas sin una ruta asignada usan la ruta predeterminada.", + allAssigned: "Todas las teclas se asignan a otras rutas", + keyMoves: (joining: string[], leaving: string[]) => [ + joining.length ? `${andList(joining)} cambiará a esta ruta` : "", + leaving.length ? `${andList(leaving)} cambiará a la ruta predeterminada` : "", + ] + .filter(Boolean) + .join("; ") + ".", + usesRoute: (name: string) => `Actualmente utiliza la ruta “${name}”`, + usesDefault: "Actualmente utiliza la ruta predeterminada", + rules: "Reglas", + rule: "Regla", + conditions: "Condiciones", + onMatch: "En el partido", + dragRule: (name: string) => `Arrastre para reordenar la regla “${name}”`, + noEffect: "Sin efecto", + phaseTwo: "Después de la selección", + hits: (span: HitSpan, n: number) => `${n === 1 ? "1 pulsación" : `${n.toLocaleString()} hits`} en ${spanEn(span)}`, + noHits: (span: HitSpan) => `No hay coincidencias en ${spanEn(span)}`, + ruleActions: (name: string) => `Medidas relativas a la regla “${name}”`, + noRules: "Todavía no hay reglas.", + shadowed: (names: string[]) => { + const list = andList(names.map((n) => `“${n}”`)); + return names.length === 1 + ? `${list} está detrás de la regla de la captura-todo, por lo que nunca se adelanta o niega.` + : `${list} están detrás de la regla de la captura-todo, por lo que nunca avanzan o niegan.`; + }, + liftShadowed: "Mover por encima de la regla de la captura-todo", + noCatchAll: "Todavía no hay regla general. Las solicitudes que coincidan con ninguna regla devolverán un error.", + addCatchAll: "Añadir regla general", + untitled: "Sin título", + conditionJoin: " y ", + alsoAliasesOf: (aliases: string[]) => `También coincide con el ${aliases.length === 1 ? "alias que apunta" : "alias ese punto"}: ${aliases.join(", ")}`, + alsoAliases: (aliases: string[]) => `También coincide con el ${aliases.length === 1 ? "alias que apunta" : "alias ese punto"} de estos modelos: ${aliases.join(", ")}`, + backups: (list: string[]) => `Respaldo: ${list.join(", ")}`, + }, + }, ); diff --git a/src/routing/RouteTable.i18n.ts b/src/routing/RouteTable.i18n.ts index 5184baf1..f0c2fb51 100644 --- a/src/routing/RouteTable.i18n.ts +++ b/src/routing/RouteTable.i18n.ts @@ -19,4 +19,28 @@ export const routeTableText = messages( noDecidingRule: "No rule decides the destination", dryRunMenu: "Dry run…", }, + { + "zh-Hant": { + keys: "使用金鑰", + rules: "規則", + defaultBadge: "預設", + unused: "未被金鑰使用", + noDecidingRule: "無決定去向的規則", + dryRunMenu: "試算…", + }, + ko: { + keys: "키", + rules: "규칙", + defaultBadge: "기본값", + }, + es: { + route: "Ruta", + keys: "Claves", + rules: "Reglas", + defaultBadge: "Predeterminado", + unused: "No utilizado por ninguna tecla", + noDecidingRule: "Ninguna regla decide el destino", + dryRunMenu: "Rumbo seco…", + }, + }, ); diff --git a/src/routing/RoutingPage.i18n.ts b/src/routing/RoutingPage.i18n.ts index 965c0f8c..6c2abae1 100644 --- a/src/routing/RoutingPage.i18n.ts +++ b/src/routing/RoutingPage.i18n.ts @@ -40,4 +40,59 @@ export const routingPageText = messages( switched: (group: string, provider: string) => `“${group}” switched to ${provider}`, preferred: (group: string, provider: string) => `“${group}” now prefers ${provider}`, }, + { + "zh-Hant": { + noUpstreams: "尚無上游", + noUpstreamsDesc: "路由規則將請求轉發至上游或策略組。新增上游後,預設路由將請求依次轉發至全部上游。", + groups: "策略組", + probes: "輔助請求", + routesUnit: (_n: number) => "條路由", + rulesUnit: (_n: number) => "條規則", + groupsUnit: (_n: number) => "個策略組", + shadowedUnit: (_n: number) => "條規則不會生效", + noCatchAllUnit: (_n: number) => "條路由無兜底規則", + allInEffect: "規則均生效", + group: "策略組", + deleteGroupConsequence: "刪除後,此策略組將從配置檔案中移除,可從備份中恢復。", + switched: (group: string, provider: string) => `「${group}」已切換到 ${provider}`, + preferred: (group: string, provider: string) => `「${group}」優先使用 ${provider}`, + }, + ja: { + noUpstreams: "アップストリームがありません", + noUpstreamsDesc: "ルーティングルールはリクエストをアップストリームまたはグループへ転送します。アップストリームを追加すると、既定のルートがすべてのアップストリームへ順番に転送します。", + routes: "ルート", + groups: "グループ", + probes: "補助リクエスト", + routesUnit: (_n: number) => "件のルート", + rulesUnit: (_n: number) => "件のルール", + groupsUnit: (_n: number) => "件のグループ", + shadowedUnit: (_n: number) => "件のルールが適用されません", + noCatchAllUnit: (_n: number) => "件のルートに既定のルールがありません", + allInEffect: "すべてのルールが有効", + group: "グループ", + deleteGroupConsequence: "このグループを設定ファイルから削除します。バックアップから復元できます。", + switched: (group: string, provider: string) => `「${group}」を ${provider} に切り替えました`, + preferred: (group: string, provider: string) => `「${group}」で ${provider} を優先します`, + }, + ko: { + noUpstreams: "업스트림이 없습니다.", + }, + es: { + noUpstreams: "Todavía no hay proveedores.", + noUpstreamsDesc: "Las reglas de enrutamiento reenvían las solicitudes a las del proveedor o a los grupos. Una vez que se añade una corriente arriba, la ruta predeterminada reenvia las peticiones a todas las aguas abajo en orden.", + routes: "Rutas", + groups: "Grupos", + probes: "Auxiliar", + routesUnit: (n: number) => (n === 1 ? "ruta" : "rutas"), + rulesUnit: (n: number) => (n === 1 ? "regla" : "normas"), + groupsUnit: (n: number) => (n === 1 ? "grupo" : "grupos"), + shadowedUnit: (n: number) => (n === 1 ? "la regla no tiene efecto" : "las normas no surten efecto"), + noCatchAllUnit: (n: number) => (n === 1 ? "ruta no tiene ninguna regla de alcance general" : "rutas no tienen ninguna regla de alcance general"), + allInEffect: "Todas las normas en vigor", + group: "grupo", + deleteGroupConsequence: "Una vez eliminado, este grupo se elimina del archivo de configuraciónuración. Se puede restaurar desde las copias de seguridad.", + switched: (group: string, provider: string) => `“${group}” cambiado a ${provider}`, + preferred: (group: string, provider: string) => `“${group}” ahora prefiere ${provider}`, + }, + }, ); diff --git a/src/routing/RuleDialog.i18n.ts b/src/routing/RuleDialog.i18n.ts index 7f42d2da..be30052e 100644 --- a/src/routing/RuleDialog.i18n.ts +++ b/src/routing/RuleDialog.i18n.ts @@ -102,4 +102,95 @@ export const ruleDialogText = messages( anyProbe: "Any auxiliary request", removeCondition: (name: string) => `Remove condition ${name}`, }, + { + "zh-Hant": { + editTitle: (name: string) => `編輯規則「${name}」`, + position: (route: string, n: number) => `路由「${route}」· 第 ${n} 條`, + namePlaceholder: "例如 長上下文", + conditions: "條件", + allOf: "同時滿足以下條件", + intercepted: (probes: string[]) => `${probes.join("、")}當前由閘道器本地應答,不會進入路由,此條件對其不成立。`, + toForward: "可在「輔助請求」中改為轉發。", + onMatch: "命中後", + forward: "轉發", + forwardTo: "轉發至", + toTarget: "上游或策略組", + chooseTarget: "選擇去向", + groups: "策略組", + newGroupMenu: "新建策略組…", + denyReason: "拒絕原因", + denyReasonDesc: "返回給用戶端。", + denyPlaceholder: "例如 此金鑰不提供 Opus 模型", + continueDesc: "應用下方的改寫引數與安全要求,然後繼續匹配後續規則。", + phaseTwo: "含「選定上游」條件的規則在選定上游之後判斷,只能拒絕或繼續匹配。", + rewrite: "改寫引數", + notSet: "未設定", + setModel: "模型改為", + unchanged: "不改變", + off: "關閉", + reasoningNote: "指定檔位時,僅改寫已開啟推理的請求;未開啟推理的請求(如生成標題)保持不變。", + modelChangeNote: "更換模型後,已快取的 prompt 不再命中。", + add: "新增", + addCondition: "新增條件", + globMatches: (n: number) => `匹配 ${n} 個已知模型`, + aliasOnly: (alias: string) => `匹配用別名 ${alias} 請求的。直接用上游模型名請求的不匹配。`, + alsoAliasesOf: (aliases: string[]) => `也匹配指向它的別名 ${aliases.join("、")}`, + alsoAliases: (aliases: string[]) => `也匹配指向這些模型的別名 ${aliases.join("、")}`, + compareOp: (name: string) => `${name}的比較方式`, + compareAmount: (name: string) => `${name}的數值`, + chooseKey: "選擇金鑰", + anyProbe: "任一輔助請求", + removeCondition: (name: string) => `刪除條件 ${name}`, + }, + ko: { + upstreams: "업스트림", + notSet: "설정되지 않음", + off: "끄기", + }, + es: { + editTitle: (name: string) => `Editar la regla “${name}”`, + position: (route: string, n: number) => `Ruta “${route}” · regla ${n}`, + namePlaceholder: "Por ejemplo, contexto largo", + conditions: "Condiciones", + allOf: "Todo lo siguiente debe cumplirse", + intercepted: (probes: string[]) => `${andList(probes)} ${probes.length === 1 ? "es" : "son"} respondió localmente por la puerta de entrada y nunca ${probes.length === 1 ? "alcances" : "alcance"} enrutamiento, por lo que esta condición nunca se mantiene ${probes.length === 1 ? "it" : "ellos"}.`, + toForward: "Esto puede ser cambiado a “Adelante” bajo Auxiliar.", + onMatch: "En el partido", + forward: "Adelante", + forwardTo: "Adelante a", + toTarget: "Upstream o grupo", + toPinned: "Modelos especificados", + chooseTarget: "Seleccionar un destino", + groups: "Grupos", + newGroupMenu: "Nuevo grupo…", + upstreams: "Proveedores", + denyReason: "Denegar la razón", + denyReasonDesc: "Volvió con el cliente.", + denyPlaceholder: "Por ejemplo, los modelos de Opus no están disponibles con esta clave", + continueDesc: "Aplica el parámetro reescribir y los requisitos de seguridad a continuación, luego continúa con las siguientes reglas.", + phaseTwo: "Las reglas con una condición “Seleccionada arriba” se evalúan después de que se selecciona una corriente arriba, y sólo pueden negar o continuar emparejando.", + rewrite: "Reescritura del parámetro", + notSet: "Sin configurar", + setModel: "Cambiar el modelo a", + unchanged: "Sin cambios", + reasoning: "Razonamiento", + off: "Desactivado", + reasoningNote: "Un nivel se aplica sólo a las solicitudes que ya tienen razonamiento sobre; las solicitudes sin razonamiento (como la generación de títulos) se mantienen sin cambios.", + modelChangeNote: "Una vez que se cambia el modelo, los avisos en caché ya no se golpean.", + add: "Añadir", + addCondition: "Añadir condición", + globPlaceholder: "Por ejemplo, claude-opus-*", + globMatches: (n: number) => (n === 1 ? "Coincide con 1 modelo conocido" : `Coincide con ${n} modelos conocidos`), + globNone: "No coincide con ningún modelo conocido", + aliasOnly: (alias: string) => `Las solicitudes de coincidencias que utilizan el alias ${alias}. Las solicitudes que utilizan un nombre de modelo de origen directamente no coinciden.`, + alsoAliasesOf: (aliases: string[]) => `También coincide con el ${aliases.length === 1 ? "alias que apunta" : "alias ese punto"}: ${aliases.join(", ")}`, + alsoAliases: (aliases: string[]) => `también coincide con el ${aliases.length === 1 ? "alias que apunta" : "alias ese punto"} de estos modelos: ${aliases.join(", ")}`, + compareOp: (name: string) => `Comparación de ${name}`, + compareAmount: (name: string) => `Valor de ${name}`, + yes: "Sí", + chooseKey: "Seleccione una clave", + anyProbe: "Cualquier solicitud auxiliar", + removeCondition: (name: string) => `Eliminar condición ${name}`, + }, + }, ); diff --git a/src/routing/TimeCondition.i18n.ts b/src/routing/TimeCondition.i18n.ts index bf10db22..22b9c3ff 100644 --- a/src/routing/TimeCondition.i18n.ts +++ b/src/routing/TimeCondition.i18n.ts @@ -24,4 +24,29 @@ export const timeConditionText = messages( rawHint: "Unrecognised form; example: mon-fri 09:00-18:00", note: "Local time of the machine the gateway runs on. An end earlier than the start is an overnight window; a whole day is 00:00–24:00.", }, + { + "zh-Hant": { + window: (n: number) => `第 ${n} 個時段`, + start: (n: number) => `第 ${n} 個時段的開始時間`, + end: (n: number) => `第 ${n} 個時段的結束時間`, + removeWindow: (n: number) => `移除第 ${n} 個時段`, + addWindow: "新增時段", + rawHint: "無法識別的寫法,示例:mon-fri 09:00-18:00", + note: "按閘道器所在機器的本地時間。結束早於開始的為跨夜時段;全天寫 00:00–24:00。", + }, + ko: { + remove: "제거", + }, + es: { + days: { mon: "Mon", tue: "Mar", wed: "Mié", thu: "Thu", fri: "Fri", sat: "Sáb", sun: "Sol" }, + window: (n: number) => `Ventana temporal ${n}`, + start: (n: number) => `Inicio de la ventana de tiempo ${n}`, + end: (n: number) => `Ventana de fin de tiempo ${n}`, + remove: "Quitar", + removeWindow: (n: number) => `Eliminar ventana de tiempo ${n}`, + addWindow: "Añadir ventana de tiempo", + rawHint: "Forma no reconocida; ejemplo: mon-fri 09:00-18:00", + note: "Hora local de la máquina en la puerta de entrada. Un final anterior al inicio es una ventana de noche; todo el día es de 00:00 a 24:00.", + }, + }, ); diff --git a/src/routing/WebTools.i18n.ts b/src/routing/WebTools.i18n.ts index 4df7922c..53e8ec27 100644 --- a/src/routing/WebTools.i18n.ts +++ b/src/routing/WebTools.i18n.ts @@ -27,4 +27,159 @@ export const webToolsText = messages( fallback: "Allow upstream fallback if a standalone search fails", fallbackHelp: "Fallback may incur upstream model and search fees. Tool results already given to the model are not replayed.", advanced: "Limits and cache", readHelp: "Zero returns snippets only from searches. The model can still explicitly request a page.", search: "Search", open: "Read page", find: "Find in page", query: "Query", url: "Page URL", pattern: "Find text", run: "Run test", testing: "Running…", testHelp: "Uses the saved configuration and makes real network requests from the connected Core.", noResults: "No matching results.", cached: "Cache hit", fetched: "Fetched", elapsed: (ms: number) => `${ms} ms`, partial: "Some sources failed", truncated: "Content was truncated to the configured limit", invalid: "Check the numeric ranges and domain names.", }, + { + "zh-Hant": { + title: "聯網搜尋與網頁讀取", + intro: "選擇搜尋、讀取網頁和頁內查詢由誰執行。普通對話繼續按路由規則選擇模型。", + core: "Core 執行", + upstream: "上游執行", + coreHelp: "獨立搜尋直接返回結果;對話中的聯網操作執行後交回模型。主模型仍按實際用量計費。", + upstreamHelp: "保留用戶端原有請求,按路由規則交給上游。", + test: "測試", + save: "儲存", + retry: "重試", + loading: "正在讀取搜尋配置…", + unavailable: "無法讀取聯網工具配置。請確認連線正常,且 Core 已支援聯網工具。", + local: "執行位置:本機 Core", + remote: (name: string) => `執行位置:${name}`, + googleDocsHelp: "Google (Docs) 搜尋公開網頁,請求間隔至少 6 秒,不支援地區偏好。", + engines: "搜尋引擎", + auto: "自動", + findEngine: "查詢引擎", + noEngineMatch: "沒有匹配的引擎", + engineCount: (n: number) => `已選 ${n} 個引擎`, + proxy: "網路出口", + system: "跟隨系統", + direct: "直連", + language: "搜尋語言", + region: "國家或地區", + automatic: (name: string) => `跟隨系統(${name})`, + automaticUnknown: "跟隨系統(由搜尋引擎決定)", + unknownLocale: "當前設定", + noLocaleMatch: "沒有匹配的語言或地區", + localeLocal: "自動使用本機 Core 的系統設定。", + localeRemote: (name: string) => `自動使用遠端 Core「${name}」的系統設定。`, + localeHelp: "可按名稱搜尋並單獨修改語言或地區;搜尋引擎會盡量按此偏好返回結果。", + allowed: "允許的域名", + domainsHelp: "支援貼上多行域名,規則包含子域名並同時約束網頁讀取。排除優先。", + allowedHelp: "留空時不限制域名。", + blockedHelp: "留空時不排除域名。", + add: "新增", + remove: "刪除", + removeDomain: (domain: string) => `刪除 ${domain}`, + domainPlaceholder: "新增域名,例如 sqlite.org", + invalidDomains: (names: string) => `域名格式不正確:${names}`, + tooManyDomains: "每份列表最多 100 個域名。", + domainConflict: (names: string) => `以下域名同時出現在兩份列表中,將被排除:${names}`, + engineHelp: "自動按 Core 推薦順序搜尋,失敗或無可用結果時切換引擎;也可多選指定優先順序。", + maxResults: "搜尋結果數", + readPages: "摘要不足時讀取網頁數", + pageChars: "每頁最多返回字元", + timeout: "每次操作超時(秒)", + concurrent: "最大併發", + interval: "同一引擎請求間隔(毫秒)", + cache: "快取有效期(秒)", + toolCalls: "每個請求最多執行工具次數", + fallback: "獨立搜尋失敗時允許回退上游", + fallbackHelp: "回退可能產生上游模型和搜尋費用;已交回模型的工具結果不重放。", + advanced: "限額與快取", + readHelp: "設為 0 時搜尋只返回摘要;模型仍可明確請求讀取網頁。", + search: "搜尋", + open: "讀取網頁", + find: "頁內查詢", + query: "查詢詞", + url: "網頁 URL", + pattern: "查詢文字", + run: "執行測試", + testing: "正在執行…", + testHelp: "使用已儲存的配置,由當前連線的 Core 實際聯網執行。", + noResults: "沒有匹配的結果。", + cached: "命中快取", + fetched: "實際獲取", + partial: "部分來源未成功", + truncated: "內容已按配置截斷", + invalid: "請檢查數值範圍和域名格式。", + }, + ko: { + save: "저장", + cancel: "취소", + retry: "다시 시도", + remove: "삭제", + }, + es: { + title: "Búsqueda en la Web y lectura de páginas", + intro: "Elija quién ejecuta la búsqueda, lectura de páginas y búsqueda en página. Las solicitudes de modelos continúan siguiendo las reglas de enrutamiento.", + core: "Ejecutar en el núcleo", + upstream: "Ejecutar del proveedor", + coreHelp: "Las búsquedas independientes devuelven resultados directamente. Operaciones web dentro de una conversación regresan al modelo. El uso del modelo principal todavía está facturado.", + upstreamHelp: "Reenvíe las solicitudes originales del cliente a través de las reglas de enrutamiento.", + configure: "Configurar", + test: "Ensayo", + save: "Guardar", + cancel: "Cancelar", + retry: "Reintentar", + loading: "Cargando configuración web-herramienta…", + unavailable: "La configuración Web-tool no está disponible. Compruebe la conexión y que Core admite herramientas web.", + local: "Funciona en: local Core", + remote: (name: string) => `Corre en: ${name}`, + googleDocsHelp: "Google (Docs) busca en la web, con al menos 6 segundos entre solicitudes. Las preferencias regionales no son compatibles.", + engines: "Buscadores", + auto: "Automático", + findEngine: "Encontrar un motor", + noEngineMatch: "No hay motores que coincidan", + engineCount: (n: number) => `${n} motores seleccionados`, + proxy: "Red", + system: "Proxy del sistema", + direct: "Directo", + language: "Idioma de búsqueda", + region: "País o región", + automatic: (name: string) => `Sistema ${name}`, + automaticUnknown: "Sistema (por defecto del motor de búsqueda)", + unknownLocale: "Selección actual", + noLocaleMatch: "No hay idioma o región que coincida", + localeLocal: "Automático utiliza la configuración del sistema local del núcleo.", + localeRemote: (name: string) => `Automático utiliza la configuración del sistema de núcleo remoto “${name}”.`, + localeHelp: "Busca por nombre para anular cualquiera de las preferencias. Los motores de búsqueda aplican estas preferencias cuando son compatibles.", + allowed: "Dominios permitidos", + blocked: "Dominios bloqueados", + domainsHelp: "Pegar varios nombres de host en líneas separadas. Las reglas incluyen subdominios y se aplican a la lectura de páginas. Los dominios bloqueados tienen prioridad.", + allowedHelp: "Vacío permite todos los dominios.", + blockedHelp: "Bloques vacíos sin dominios.", + add: "Añadir", + remove: "Eliminar", + removeDomain: (domain: string) => `Suprímase ${domain}`, + domainPlaceholder: "Añadir un nombre de host, por ejemplo sqlite.org", + invalidDomains: (names: string) => `Nombres de host no válidos: ${names}`, + tooManyDomains: "Cada lista admite hasta 100 nombres de host.", + domainConflict: (names: string) => `Estos dominios aparecen en ambas listas y serán bloqueados: ${names}`, + engineHelp: "Automático sigue el orden recomendado de Core y conmuta los motores en caso de fallo o ningún resultado utilizable. Seleccione motores para establecer su propia prioridad.", + maxResults: "Resultados de la búsqueda", + readPages: "Leer páginas cuando los fragmentos son insuficientes", + pageChars: "Caracteres máximos por página", + timeout: "Tiempo límite de funcionamiento (segundos)", + concurrent: "Operaciones simultáneas", + interval: "Intervalo por motor (milisegundos)", + cache: "Vida útil en caché (segundos)", + toolCalls: "Máximo de llamadas de herramientas por petición", + fallback: "Permitir un retroceso previo si falla una búsqueda independiente", + fallbackHelp: "Los resultados de la herramienta ya dada al modelo no se repiten.", + advanced: "Límites y caché", + readHelp: "Zero devuelve fragmentos sólo de búsquedas. El modelo todavía puede solicitar explícitamente una página.", + search: "Buscar", + open: "Leer página", + find: "Buscar en la página", + query: "Consulta", + url: "URL de página", + pattern: "Buscar texto", + run: "Prueba de ejecución", + testing: "Corriendo…", + testHelp: "Utiliza la configuración guardada y realiza peticiones de red reales desde el núcleo conectado.", + noResults: "No hay resultados coincidentes.", + cached: "Choque caché", + fetched: "Obtenido", + partial: "Algunas fuentes fallaron", + truncated: "El contenido fue truncado al límite configurado", + invalid: "Compruebe los rangos numéricos y los nombres de dominio.", + }, + }, ); diff --git a/src/routing/fields.i18n.ts b/src/routing/fields.i18n.ts index 9229583e..8cba103d 100644 --- a/src/routing/fields.i18n.ts +++ b/src/routing/fields.i18n.ts @@ -15,4 +15,16 @@ export const fieldsText = messages( hiddenFromClients: "hidden from client lists", providers: (ps: readonly string[]) => ps.join(", "), }, + { + "zh-Hant": { + noMatch: "無匹配項,可直接輸入完整模型名", + alias: "別名", + hiddenFromClients: "用戶端列表已隱藏", + }, + es: { + modelName: "Nombre del modelo", + noMatch: "No hay modelo de coincidencia; cualquier nombre de modelo completo puede ser introducido", + hiddenFromClients: "ocultado de las listas de clientes", + }, + }, ); diff --git a/src/routing/model.i18n.ts b/src/routing/model.i18n.ts index c338b1d9..1b33c46c 100644 --- a/src/routing/model.i18n.ts +++ b/src/routing/model.i18n.ts @@ -82,4 +82,83 @@ export const modelText = messages( cheapest: "Prefers the upstream with the lowest input price.", }, }, + { + "zh-Hant": { + condGroups: { request: "請求", features: "特徵", source: "來源", upstream: "上游" }, + compareOps: { gt: "大於", ge: "不小於", lt: "小於", le: "不大於", eq: "等於" }, + amountMissing: (name: string) => `填寫條件「${name}」的數值`, + amountInvalid: (name: string) => `條件「${name}」的數值有誤,示例:200k`, + valueMissing: (name: string) => `填寫條件「${name}」的取值`, + timeInvalid: (name: string) => `條件「${name}」須選擇至少一天,時間寫成 HH:MM,示例:09:00`, + ruleNameMissing: "填寫規則名稱", + ruleNameTaken: (name: string) => `規則名稱「${name}」已存在`, + phaseTwoForward: "含「選定上游」條件的規則不能轉發", + targetMissing: "選擇轉發去向", + pinnedMissing: "新增至少一個指定模型", + pinnedProviderMissing: (n: number) => `選擇第 ${n} 個指定模型的上游`, + pinnedModelMissing: (n: number) => `填寫第 ${n} 個指定模型的模型名`, + denyReasonMissing: "填寫拒絕原因", + continueNeedsAddOns: "繼續匹配的規則須設定改寫引數或安全要求", + maxTokensInvalid: "max_tokens 須為正整數", + ruleCount: (n: number) => `${n} 條規則`, + shadowedCount: (n: number) => `${n} 條位於兜底規則之後,不會生效`, + noCatchAll: "尚無兜底規則", + builtinGroup: "內建策略組 · 按上游列表順序", + groupTarget: (kind: string, members: string) => `策略組 · ${kind}${members ? `:${members}` : ""}`, + setModel: (model: string) => `模型改為 ${model}`, + setModelAlias: (model: string) => `模型改為 ${model},按別名表對應到各上游`, + withBackups: (first: string, n: number) => `${first},備用 ${n} 個`, + setMaxTokens: (value: string) => `max_tokens 改為 ${value}`, + strategies: { + fallback: "依次使用成員,前一個不可用時使用下一個。", + selectOnly: "只使用選定的成員。要自動切換,請選擇按順序或其他自動策略。", + select: "使用選定的上游;它不可用時,按順序使用其餘成員。", + loadBalance: "在成員之間輪流分配請求。", + urlTest: "優先使用首 token 時間最短的上游。", + cheapest: "優先使用輸入單價最低的上游。", + }, + }, + ko: { + condGroups: { request: "요청", features: "Features", source: "출처", upstream: "업스트림" }, + }, + es: { + condGroups: { request: "Solicitud", features: "Características", source: "Origen", upstream: "Proveedor" }, + compareOps: { gt: "Mayor que", ge: "Al menos", lt: "Menos de", le: "Como mucho", eq: "Igual a" }, + amountMissing: (name: string) => `Introduzca un número para la condición “${name}”`, + amountInvalid: (name: string) => `El número de la condición “${name}” no es válido; ejemplo: 200k`, + valueMissing: (name: string) => `Introduzca un valor para la condición “${name}”`, + timeInvalid: (name: string) => `La condición “${name}” necesita al menos un día y tiempos escritos como HH:MM; ejemplo: 09:00`, + ruleNameMissing: "Introduzca un nombre de regla", + ruleNameTaken: (name: string) => `Una regla llamada “${name}” ya existe`, + phaseTwoForward: "Las reglas con una condición “Seleccionada en sentido ascendente” no se pueden transmitir", + targetMissing: "Seleccione un destino al que dirigirse", + pinnedMissing: "Añadir al menos un modelo especificado", + pinnedProviderMissing: (n: number) => `Seleccione el nivel anterior del modelo especificado ${n}`, + pinnedModelMissing: (n: number) => `Introduzca el nombre del modelo del modelo especificado ${n}`, + denyReasonMissing: "Introduzca una razón de denegación", + continueNeedsAddOns: "Una regla que continúa emparejando necesidades de parámetros reescribe o requisitos de seguridad", + maxTokensInvalid: "max_tokens debe ser un entero positivo", + ruleCount: (n: number) => (n === 1 ? "1 artículo" : `${n} normas`), + shadowedCount: (n: number) => n === 1 + ? "1 es después de la regla general y no tiene ningún efecto" + : `${n} están siguiendo la regla general y no tienen efecto`, + noCatchAll: "Todavía no hay regla general.", + builtinGroup: "Grupo integrado · En orden de lista ascendente", + groupTarget: (kind: string, members: string) => `Grupo · ${kind}${members ? `: ${members}` : ""}`, + upstreamTarget: (protocol: string, disabled: boolean) => `Corriente ascendente · ${protocol}${disabled ? " · Discapacitados" : ""}`, + unknownTarget: "Destino no encontrado", + setModel: (model: string) => `Modelo establecido en ${model}`, + setModelAlias: (model: string) => `Modelo establecido para ${model}, mapeado a cada río arriba a través de la tabla alias`, + withBackups: (first: string, n: number) => `${first}, ${n === 1 ? "1 respaldo" : `${n} copias de seguridad`}`, + setMaxTokens: (value: string) => `max_tokens establecidos en ${value}`, + strategies: { + fallback: "Utiliza los miembros en orden, pasando al siguiente cuando uno no está disponible.", + selectOnly: "Utiliza sólo el miembro seleccionado. Elija En orden u otra estrategia automática para el failover.", + select: "Utiliza el upstream seleccionado; cuando no está disponible, utiliza los otros miembros en orden.", + loadBalance: "Distribuye las solicitudes entre los miembros a su vez.", + urlTest: "Prefiere la corriente ascendente con el tiempo más corto al primer token.", + cheapest: "Prefiere el upstream con el precio de entrada más bajo.", + }, + }, + }, ); diff --git a/src/routing/parts.i18n.ts b/src/routing/parts.i18n.ts index 353c4f1a..6e246175 100644 --- a/src/routing/parts.i18n.ts +++ b/src/routing/parts.i18n.ts @@ -16,4 +16,22 @@ export const partsText = messages( authRejected: "Credential rejected", keyDisabled: "Disabled", }, + { + "zh-Hant": { + circuitOpen: "熔斷中", + needsLogin: "需要重新登入", + authRejected: "憑據被拒", + }, + ko: { + disabled: "비활성화됨", + keyDisabled: "비활성화됨", + }, + es: { + disabled: "Desactivado", + circuitOpen: "Circuito abierto", + needsLogin: "Inicie sesión de nuevo", + authRejected: "Credenciales rechazadas", + keyDisabled: "Desactivado", + }, + }, ); diff --git a/src/routing/routing.i18n.ts b/src/routing/routing.i18n.ts index 1dd3bf9f..a685a405 100644 --- a/src/routing/routing.i18n.ts +++ b/src/routing/routing.i18n.ts @@ -88,4 +88,60 @@ export const routingText = messages( listSep: ", ", clauseSep: " · ", }, + { + "zh-Hant": { + name: "名稱", + nameMissing: "填寫名稱", + nameReserved: "名稱不能以 __ 開頭", + nameTaken: (name: string) => `名稱「${name}」已被使用`, + create: "建立", + members: "成員", + newGroup: "新建策略組", + addRule: "新增規則", + dryRun: "試算", + editMenu: "編輯…", + duplicateMenu: "複製…", + deleteMenu: "刪除…", + locate: "在配置檔案中定位", + showUpstreams: "前往上游頁", + setDefault: "設為預設路由", + deny: "拒絕", + continueMatching: "繼續匹配", + allRequests: "全部請求(兜底)", + requestsIn: (span: HitSpan, n: number) => `${spanZh(span)} ${n.toLocaleString()} 次請求`, + noRequestsIn: (span: HitSpan) => `${spanZh(span)}內無請求`, + noRecords: "尚無請求記錄", + }, + ko: { + name: "이름", + nameMissing: "이름을 입력하세요.", + }, + es: { + name: "Nombre", + nameMissing: "Introduce un nombre.", + nameReserved: "Los nombres no pueden comenzar con __", + nameTaken: (name: string) => `El nombre “${name}” ya está en uso`, + create: "Crear", + strategy: "Estrategia", + members: "Miembros", + newRoute: "Nueva ruta", + newGroup: "Nuevo grupo", + addRule: "Añadir regla", + dryRun: "Ejecución en seco", + editMenu: "Editar…", + duplicateMenu: "Duplicar…", + deleteMenu: "Eliminar…", + locate: "Mostrar en el archivo de configuraciónuración", + showUpstreams: "Ir hacia arriba", + actionsFor: (name: string) => `Acciones en relación con ${name}`, + setDefault: "Establecer como ruta predeterminada", + deny: "Negar", + continueMatching: "Continuar emparejando", + allRequests: "Todas las solicitudes (completas)", + noHits: "Sin resultados", + requestsIn: (span: HitSpan, n: number) => `${n === 1 ? "1 solicitud" : `${n.toLocaleString()} solicitudes`} en ${spanEn(span)}`, + noRequestsIn: (span: HitSpan) => `Ninguna solicitud en ${spanEn(span)}`, + noRecords: "Todavía no se han registrado solicitudes", + }, + }, ); diff --git a/src/routing/timeWindow.i18n.ts b/src/routing/timeWindow.i18n.ts index d312fcbc..85a66ea0 100644 --- a/src/routing/timeWindow.i18n.ts +++ b/src/routing/timeWindow.i18n.ts @@ -24,4 +24,14 @@ export const timeWindowText = messages( withDays: (days: string, time: string) => `${days} ${time}`, nextDay: "next day", }, + { + "zh-Hant": { + days: { mon: "週一", tue: "週二", wed: "週三", thu: "週四", fri: "週五", sat: "週六", sun: "週日" }, + }, + es: { + days: { mon: "Mon", tue: "Mar", wed: "Mié", thu: "Thu", fri: "Fri", sat: "Sáb", sun: "Sol" }, + overnight: (start: string, end: string) => `${start}–${end} al día siguiente`, + nextDay: "al día siguiente", + }, + }, ); diff --git a/src/security/Exceptions.i18n.ts b/src/security/Exceptions.i18n.ts index 216d141d..1dddab79 100644 --- a/src/security/Exceptions.i18n.ts +++ b/src/security/Exceptions.i18n.ts @@ -73,4 +73,55 @@ export const exceptionsText = messages( tag: "Exception", trial: "Exception, not handled", }, + { + "zh-Hant": { + count: (n: number) => `${n} 個值`, + none: "無例外值。被誤認的值可在安全日誌中列為例外,或在此新增。", + add: "新增例外", + full: (max: number) => `已達上限 ${max} 個`, + rule: "首次認出的規則", + ruleLabel: "規則", + addedAt: "加入時間", + removeFor: (masked: string) => `將 ${masked} 移出例外`, + addTitle: "新增例外", + addDesc: "此值今後在任何規則下都不替換,也不記錄。", + addPlaceholder: "貼上要列為例外的值", + addFailed: "未能新增", + exceptTitle: "列為例外", + exceptDesc: "此值今後不再替換,也不再記錄。", + exceptFailed: "未能列為例外", + removeDesc: "此值今後照常替換並記錄。", + trial: "例外,不處理", + }, + ko: { + ruleLabel: "규칙", + remove: "제거", + }, + es: { + title: "Excepciones", + count: (n: number) => plural(n, "valor", "valores"), + none: "No hay excepciones. Un valor igualado por error puede ser listado como una excepción del registro de seguridad, o añadido aquí.", + add: "Añadir excepción", + full: (max: number) => `Límite de ${max} alcanzado`, + value: "Valor", + rule: "Encontrado por primera vez por", + ruleLabel: "Regla", + addedAt: "Añadido", + remove: "Quitar", + removeFor: (masked: string) => `Eliminar ${masked} de las excepciones`, + addTitle: "Añadir excepción", + addDesc: "Este valor ya no se sustituye ni se registra bajo ninguna regla.", + addLabel: "Valor", + addPlaceholder: "Pegar el valor a except", + addFailed: "Sin añadir", + exceptTitle: "Listar como excepción", + exceptDesc: "Este valor ya no se sustituye ni se registra.", + exceptFailed: "No incluido como excepción", + removeTitle: "Eliminar las excepciones", + removeDesc: "Este valor se reemplaza y se registra de nuevo.", + removeFailed: "Sin eliminar", + tag: "Excepción", + trial: "Excepción, no manipulada", + }, + }, ); diff --git a/src/security/GuardTab.i18n.tsx b/src/security/GuardTab.i18n.tsx index 7226b949..67919063 100644 --- a/src/security/GuardTab.i18n.tsx +++ b/src/security/GuardTab.i18n.tsx @@ -77,6 +77,74 @@ export const guardTabText = messages( toggleFor: (name: string) => `Turn on “${name}”`, modeFor: (guard: string) => `${guard} state`, }, + { + "zh-Hant": { + now: { + enforce: "開啟:命中內容按各條規則設定的動作處理。", + observe: { + redact: "監控:命中內容記入日誌併發出通知,請求不作修改。", + inspect_tools: "監控:命中的工具呼叫記入日誌併發出通知,照常返回用戶端。", + content: "監控:命中內容記入日誌併發出通知,請求與回答不作修改。", + }, + off: "關閉:不檢查,不記錄。", + } as { + enforce: string; + observe: Record; + off: string; + }, + ruleCount: (on: number, all: number) => `已啟用 ${on} 條,共 ${all} 條。`, + search: "檢索規則", + noMatch: "無匹配的規則", + test: "測試…", + newRule: "新建規則", + enabled: "啟用", + rule: "規則", + match: "匹配內容", + scope: "檢查物件", + action: "動作", + groupCount: (all: number, on: number) => `${all} 條 · 已開 ${on} 條`, + actionFor: (name: string) => `「${name}」的動作`, + replaceWith: (text: string) => `替換為 ${text}`, + turnOn: "啟用", + copyAsCustom: "複製為自定義規則", + toggleFor: (name: string) => `啟用「${name}」`, + modeFor: (guard: string) => `${guard}的狀態`, + }, + ko: { + rule: "규칙", + }, + es: { + now: { + enforce: "Activar: las coincidencias son manejadas por la acción establecida en cada regla.", + observe: { + redact: "Monitor: las coincidencias se registran en el registro y se notifican; las solicitudes no se modifican.", + inspect_tools: "Monitor: las llamadas de herramientas coincidentes se registran en el registro y se notifican, y se devuelven al cliente como de costumbre.", + content: "Monitor: las coincidencias se registran en el registro y se notifican; las solicitudes y respuestas no se modifican.", + }, + off: "Desactivado: no se comprueba ni se registra nada.", + }, + ruleCount: (on: number, all: number) => `${on} de ${plural(all, "regla", "normas")} en adelante.`, + search: "Reglas de búsqueda", + noMatch: "No hay reglas coincidentes", + test: "Prueba…", + newRule: "Nueva regla", + enabled: "Activar", + rule: "Regla", + match: "Coincidencia", + scope: "Comprobaciones", + action: "Medidas adoptadas", + groupCount: (all: number, on: number) => `${plural(all, "regla", "normas")} · ${on}`, + groupHits: (n: number) => `${plural(n, "igualar", "coincidencias")} en los últimos 7 días`, + actionFor: (name: string) => `Acción para “${name}”`, + replaceWith: (text: string) => `Sustitúyase por ${text}`, + turnOn: "Activar", + turnOff: "Apague", + copyAsCustom: "Copiar como regla personalizada", + actionsFor: (name: string) => `Acciones en relación con ${name}`, + toggleFor: (name: string) => `Activar “${name}”`, + modeFor: (guard: string) => `${guard} estado`, + }, + }, ); /** 「开启」「监控」「关闭」下那一句 */ diff --git a/src/security/GuardTab.tsx b/src/security/GuardTab.tsx index 608e7489..a3c9864a 100644 --- a/src/security/GuardTab.tsx +++ b/src/security/GuardTab.tsx @@ -256,7 +256,7 @@ export function RuleTable({ mode: GuardMode; rules: SecurityRuleView[]; /** 分组和分组名,core 给的(旧的 core 不给) */ - kinds: SecurityKindView[] | undefined; + kinds: readonly Pick[] | undefined; query: string; /** 最近 7 天每条规则的命中次数。还没读到、读不到是 `undefined`:组头不写次数,组照 core 的顺序 */ hits: RuleHits | undefined; @@ -295,7 +295,7 @@ export function RuleTable({ }, [rules, hits]); const groups = useMemo(() => { const shown = present.filter( - ({ item: r, presence }) => presence === "exit" || ruleMatches(r, viewName(r), query), + ({ item: r, presence }) => presence === "exit" || ruleMatches(r, viewName(guard, r), query), ); return hitsFirst(groupRules(shown, (p) => p.item), (g) => hitKinds.has(g.key)); }, [present, guard, query, hitKinds]); @@ -331,7 +331,7 @@ export function RuleTable({ {groups.map((g) => { const live = g.rows.filter((p) => p.presence !== "exit").map((p) => p.item); // 分组名由 core 给(`kinds`),按界面语言取 - const title = kindName(kinds, g.key); + const title = kindName(guard, kinds, g.key); const expanded = groupOpen(g.key, searching, open, closedInSearch); return ( @@ -430,7 +430,7 @@ function RuleRow({ }) { const t = useText(guardTabText); const lt = useText(securityLabelsText); - const name = viewName(r); + const name = viewName(guard, r); const why = ruleWhy(guard, r); const pattern = r.matcher.kind === "regex" ? r.matcher.pattern : ""; return ( @@ -464,7 +464,7 @@ function RuleRow({ ) : ( - + )} {guard === "content" && ( diff --git a/src/security/HitDetail.i18n.tsx b/src/security/HitDetail.i18n.tsx index e8dd6566..190431c7 100644 --- a/src/security/HitDetail.i18n.tsx +++ b/src/security/HitDetail.i18n.tsx @@ -111,4 +111,88 @@ export const hitDetailText = messages( openRequest: (id: number) => `Open request #${id}`, openSession: "View session", }, + { + "zh-Hant": { + rule: "規則", + outcome: "處置", + request: "請求", + session: "會話", + total: (where: string, n: number) => `${where}中共 ${n.toLocaleString()} 處`, + more: (n: number) => `另有 ${n.toLocaleString()} 處未列出`, + showAll: (n: number) => `展開全部(共 ${n.toLocaleString()} 處)`, + showAllText: "展開全部", + collapse: "摺疊", + builtinOf: (version: string) => `core ${version} 內建`, + recorded: { + request: "命中的內容照常發往上游,未做改動。", + response: "命中的內容照常返回用戶端,未做改動。", + }, + replacedWith: "發往上游的內容中替換為", + cutCall: (tool: string) => `被切斷的 ${tool} 呼叫,引數如下`, + truncated: "引數超過 4 KiB,僅保留開頭部分。", + clientNotice: "用戶端收到的提示", + notSent: "請求未發往上游。", + clientReply: "用戶端收到的回覆", + stripped: { + request: (n: number) => `刪除 ${n.toLocaleString()} 處:命中內容在發往上游之前刪除。`, + response: (n: number) => `刪除 ${n.toLocaleString()} 處:命中內容在返回用戶端之前刪除。`, + }, + replacedText: { + request: (n: number, text: ReactNode) => (<> + 替換 {n.toLocaleString()} 處:命中內容在發往上游之前替換為 {text},不可還原。 + ), + response: (n: number, text: ReactNode) => (<> + 替換 {n.toLocaleString()} 處:命中內容在返回用戶端之前替換為 {text},不可還原。 + ), + }, + sentModel: (model: string) => `發往上游的模型為 ${model}`, + openRequest: (id: number) => `開啟請求 #${id}`, + openSession: "檢視會話", + }, + ko: { + locations: "위치", + rule: "규칙", + request: "요청", + }, + es: { + locations: "Ubicación", + rule: "Regla", + outcome: "Medidas adoptadas", + request: "Solicitud", + session: "Sesión", + total: (where: string, n: number) => `${count(n, "igualar", "coincidencias")} en el ${where.toLowerCase()}`, + more: (n: number) => `${count(n, "más coincidencia", "más coincidencias")} no incluido en la lista`, + showAll: (n: number) => `Mostrar todo (${n.toLocaleString()})`, + showAllText: "Mostrar todo", + collapse: "Colapso", + builtinOf: (version: string) => `Construido en el núcleo ${version}`, + recorded: { + request: "El contenido emparejado se envió al principio sin cambios.", + response: "El contenido emparejado fue devuelto al cliente sin cambios.", + }, + replacedWith: "Reemplazado en lo que se envió a la corriente", + cutCall: (tool: string) => `La ${tool} llamada que fue cortada, con sus argumentos`, + truncated: "Los argumentos superan los 4 KiB; sólo se mantiene el principio.", + clientNotice: "Aviso recibido por el cliente", + notSent: "La solicitud no se envió a las del proveedor.", + clientReply: "Respuesta recibida por el cliente", + stripped: { + request: (n: number) => `${count(n, "el segmento correspondiente fue", "los segmentos emparejados fueron")} Suprimida antes de que se enviara la solicitud.`, + response: (n: number) => `${count(n, "el segmento correspondiente fue", "los segmentos emparejados fueron")} eliminado antes de que la respuesta llegara al cliente.`, + }, + replacedText: { + request: (n: number, text: ReactNode) => (<> + {count(n, "el segmento correspondiente fue", "los segmentos emparejados fueron")} sustituido por {text} before the request was sent; this + cannot be restored. + ), + response: (n: number, text: ReactNode) => (<> + {count(n, "el segmento correspondiente fue", "los segmentos emparejados fueron")} sustituido por {text} before the answer reached the + client; this cannot be restored. + ), + }, + sentModel: (model: string) => `enviado a la parte anterior como ${model}`, + openRequest: (id: number) => `Abrir petición #${id}`, + openSession: "Ver sesión", + }, + }, ); diff --git a/src/security/LogTab.i18n.ts b/src/security/LogTab.i18n.ts index c5a4ec9f..fdd3ab32 100644 --- a/src/security/LogTab.i18n.ts +++ b/src/security/LogTab.i18n.ts @@ -69,4 +69,63 @@ export const logTabText = messages( exportCsv: "CSV (one row per entry)", exported: (n: number) => (n === 1 ? "Exported 1 entry" : `Exported ${n.toLocaleString()} entries`), }, + { + "zh-Hant": { + time: "時間", + type: "型別", + allTypes: "全部型別", + noneOfType: (guard: string, range: string, custom: boolean) => custom ? `${range}無${guard}記錄` : `${range}內無${guard}記錄`, + showAllTypes: "顯示全部型別", + action: "處置", + request: "請求", + from: (ip: string) => `來自 ${ip}`, + count: (n: number) => `${n} 條`, + viewRequest: "檢視請求", + viewRule: "檢視規則", + disableRule: "停用此規則", + emptyIn: (range: string, custom: boolean) => (custom ? `${range}無記錄` : `${range}內無記錄`), + emptyHint: "命中任一項防護的請求將記錄在此。", + widen: "檢視 30 天", + allOff: "各項防護均已關閉", + allOffHint: "開啟任一項防護後,命中的請求將記錄在此。", + loadMore: "載入更多", + loadFailed: "安全日誌讀取失敗", + export: "匯出", + exportJson: "JSON(完整細節)", + exportCsv: "CSV(每條一行)", + exported: (n: number) => `已匯出 ${n.toLocaleString()} 條`, + }, + ko: { + time: "시간", + request: "요청", + }, + es: { + time: "Hora", + type: "Tipo", + allTypes: "Todos los tipos", + noneOfType: (_guard: string, range: string, custom: boolean) => custom ? `No hay entradas de este tipo ${lower(range)}` : `No hay entradas de este tipo en el último ${range}`, + showAllTypes: "Mostrar todos los tipos", + hit: "Coincidencia", + action: "Medidas adoptadas", + request: "Solicitud", + from: (ip: string) => `de ${ip}`, + count: (n: number) => (n === 1 ? "1 entrada" : `${n} entradas`), + viewRequest: "Ver solicitud", + viewRule: "Regla de vista", + disableRule: "Apaga esta regla.", + actionsFor: (rule: string) => `Acciones en relación con ${rule}`, + emptyIn: (range: string, custom: boolean) => custom ? `Sin entradas ${lower(range)}` : `No hay entradas en el último ${range}`, + emptyHint: "Las solicitudes que coincidan con cualquier protección se registran aquí.", + widen: "Mostrar 30 días", + allOff: "Todas las protecciones están apagadas.", + allOffHint: "Una vez que una protección está activada, las solicitudes que coinciden se registran aquí.", + goTo: (guard: string) => `Ir a ${guard}`, + loadMore: "Cargar más", + loadFailed: "No se pudo cargar el registro de seguridad", + export: "Exportar", + exportJson: "JSON (detalles completos)", + exportCsv: "CSV (una fila por entrada)", + exported: (n: number) => (n === 1 ? "1 entrada exportada" : `Entradas exportadas ${n.toLocaleString()}`), + }, + }, ); diff --git a/src/security/RuleDialog.i18n.ts b/src/security/RuleDialog.i18n.ts index 675a855f..0f379216 100644 --- a/src/security/RuleDialog.i18n.ts +++ b/src/security/RuleDialog.i18n.ts @@ -257,4 +257,240 @@ export const ruleDialogText = messages( deleteDesc: "The rule is no longer checked. Entries already in the log are kept.", deleteFailed: "Not deleted", }, + { + "zh-Hant": { + title: { + redact: { create: "新建金鑰與隱私規則", edit: "編輯金鑰與隱私規則" }, + inspect_tools: { create: "新建危險命令規則", edit: "編輯危險命令規則" }, + content: { create: "新建內容規則", edit: "編輯內容規則" }, + }, + testTitle: { + redact: "測試金鑰與隱私", + inspect_tools: "測試危險命令", + content: "測試內容過濾", + }, + name: "名稱", + nameHint: "記入日誌及發出通知時顯示此名稱。", + namePlaceholder: { + redact: "內部令牌", + inspect_tools: "刪除叢集資源", + content: "專案代號", + }, + scope: "檢查物件", + scopes: { + request: "請求", + response: "回答", + both: "請求和回答", + }, + scopeHint: "請求:使用者訊息與工具結果。回答:模型輸出的正文,不含工具呼叫與思考過程。", + matchKinds: { + contains: "包含", + regex: "正則", + codepoints: "碼位", + }, + caseSensitive: "區分大小寫", + patternLabel: "匹配內容", + toolHint: "按工具呼叫的引數匹配,使用正規表示式。", + matchHint: { + contains: (cased: boolean) => `按原文查詢,「.」「*」等字元不作特殊處理;${cased ? "區分" : "不區分"}大小寫。`, + regex: (cased: boolean) => `按正規表示式匹配;${cased ? "區分" : "不區分"}大小寫。`, + codepoints: "碼位或碼位範圍,多個之間用逗號分隔,如 U+200B, U+E0000–U+E007F。", + }, + codepointsRequestOnly: "碼位僅適用於請求。", + regexAnswerLimit: "回答中超過 256 個字元的命中,起始部分可能已送達用戶端。", + switchedMatch: "檢查物件含回答,匹配方式已改為「包含」。", + switchedAction: "檢查物件含回答,動作已改為「刪除」。", + codepointsBad: { + syntax: (item: string) => `「${item}」不是碼位寫法,應寫成 U+200B 或 U+E0000–U+E007F。`, + range: (item: string) => `「${item}」超出碼位範圍,最大為 U+10FFFF。`, + surrogate: (item: string) => `「${item}」落在代理區(U+D800–U+DFFF),不能單獨作為碼位。`, + order: (item: string) => `「${item}」的起點大於終點。`, + count: (max: number) => `最多 ${max} 項。`, + }, + label: "佔位符名稱", + labelHint: "替換為 <>。只能使用大寫字母、數字和下劃線。", + labelBad: "須以大寫字母開頭,只能使用大寫字母、數字和下劃線,最多 24 個字元。", + action: "動作", + actionWhat: { + placeholder: "命中內容替換為佔位符後發出,回答中出現該佔位符時還原為原值。", + cut: "命中的呼叫不完整送達用戶端,用戶端無法執行該呼叫。", + block: "命中的請求不發出,用戶端收到拒絕的原因。", + strip: "刪除命中內容,不保留任何標記。", + replace: "命中內容替換為下方的替換文字。", + record: { + redact: "命中內容照常發出,記入日誌併發出系統通知。", + inspect_tools: "命中的呼叫照常返回,記入日誌併發出系統通知。", + content: "命中內容不作修改,記入日誌併發出系統通知。", + }, + }, + blockRequestOnly: "拒絕僅適用於請求:回答以流式輸出,已送達的內容無法撤回。", + replacement: "替換文字", + replacementHint: "命中內容替換為此文字,不可還原。", + replacementRequired: "請填寫替換文字", + builtinReplace: (text: string) => `命中內容替換為 ${text},不可還原。`, + factory: (what: string) => `出廠設定為「${what}」。`, + state: "狀態", + on: "已啟用", + replacedWith: "替換為", + category: (kind: string) => `類別:${kind}`, + sample: "測試文字", + testAs: { + request: "按請求測試", + response: "按回答測試", + }, + samplePlaceholder: { + redact: "貼上一段文字,例如一段含有金鑰的環境變數", + inspect_tools: "貼上一段工具呼叫的引數,例如一條要執行的命令", + content: "貼上一段使用者訊息或工具結果", + }, + sampleAnswer: "貼上一段模型回答的正文", + hits: (n: number) => `命中 ${n} 處`, + rule: "規則", + content: "內容", + testDesc: "按當前啟用的規則檢查一段文字,不發出任何請求。", + output: "處理後", + refused: (mode: string) => `在「${mode}」狀態下,此請求不會發出,用戶端收到拒絕的原因。`, + monitoring: "當前分項處於監控狀態,規則僅記錄命中,不修改內容。", + builtin: "內建", + copyAsCustom: "複製為自定義規則", + nameRequired: "請填寫名稱", + nameTaken: "已有同名規則", + patternRequired: { + contains: "請填寫匹配內容", + regex: "請填寫正規表示式", + codepoints: "請填寫碼位", + }, + labelRequired: "請填寫佔位符名稱", + create: "建立", + saveFailed: "未能儲存", + deleteTitle: (name: string) => `刪除規則「${name}」`, + deleteDesc: "刪除後不再按此規則檢查。日誌中已有的記錄保留。", + deleteFailed: "未能刪除", + }, + ko: { + name: "이름", + scopes: { + request: "요청", + response: "Answer", + both: "Request and answer", + }, + off: "끄기", + rule: "규칙", + nameRequired: "이름을 입력하세요.", + }, + es: { + title: { + redact: { create: "Nuevas reglas de secretos y privacidad", edit: "Editar la regla de secretos y privacidad" }, + inspect_tools: { create: "Nueva regla de mando peligrosa", edit: "Editar regla de comando peligrosa" }, + content: { create: "Nueva regla de contenido", edit: "Editar la regla de contenido" }, + }, + testTitle: { + redact: "Secretos de prueba y privacidad", + inspect_tools: "Probar órdenes peligrosas", + content: "Probar el filtro de contenido", + }, + name: "Nombre", + nameHint: "Se muestran en el registro y en las notificaciones.", + namePlaceholder: { + redact: "Token interno", + inspect_tools: "Suprimir los recursos de los grupos temáticos", + content: "Nombre del código del proyecto", + }, + scope: "Comprobaciones", + scopes: { + request: "Solicitud", + response: "Respuesta", + both: "Solicitud y respuesta", + }, + scopeHint: "Solicitud: mensajes de usuario y resultados de la herramienta. Respuesta: el texto que el modelo escribe, excluyendo las llamadas a la herramienta y el pensamiento.", + matchKind: "Coincidencia por", + matchKinds: { + contains: "Contiene", + regex: "Regex", + codepoints: "Puntos de código", + }, + caseSensitive: "Coincidencia", + patternLabel: "Coincidencia", + toolHint: "Una expresión regular coincide con los argumentos de cada llamada de la herramienta.", + matchHint: { + contains: (cased: boolean) => `Buscado como escrito; caracteres como . y * no tienen un significado especial. ${cased ? "El caso debe coincidir" : "El caso es ignorado"}.`, + regex: (cased: boolean) => `Una expresión regular. ${cased ? "El caso debe coincidir" : "El caso es ignorado"}.`, + codepoints: "Puntos o rangos de código, separados por comas, como U+200B, U+E0000–U+E007F.", + }, + codepointsRequestOnly: "Los puntos de código se aplican únicamente a las solicitudes.", + regexAnswerLimit: "En las respuestas, el comienzo de una coincidencia de más de 256 caracteres puede haber llegado ya al cliente.", + switchedMatch: "La regla comprueba las respuestas, por lo que el partido fue cambiado a Contiene.", + switchedAction: "La regla comprueba las respuestas, por lo que la acción se cambió a Borrar.", + codepointsBad: { + syntax: (item: string) => `“${item}” no es un punto de código; escriba U+200B o U+E0000–U+E007F.`, + range: (item: string) => `“${item}” está fuera de rango; el punto de código más grande es U+10FFFF.`, + surrogate: (item: string) => `“${item}” se encuentra en el rango sustituto (U+D800–U+DFFF), que no puede mantenerse por sí solo.`, + order: (item: string) => `“${item}” comienza después de que termina.`, + count: (max: number) => `Como máximo ${max} artículos.`, + }, + label: "Nombre del marcador de posición", + labelHint: "Reemplazado con ?TW_NAME_n>>. Utilice letras mayúsculas, dígitos y subrayados solamente.", + labelBad: "Empieza con una letra mayúscula y usa solo letras mayúsculas, dígitos y subrayados, hasta 24 caracteres.", + match: "Coincidencia", + action: "Medidas adoptadas", + actionWhat: { + placeholder: "Las coincidencias se reemplazan con marcadores de posición antes de enviar; un marcador de posición que aparece en la respuesta se restaura al valor original. ", + cut: "Una llamada que coincida nunca llega completamente al cliente, por lo que el cliente no puede ejecutarla. ", + block: "No se envía una solicitud correspondiente, y se le dice al cliente por qué. ", + strip: "Las coincidencias se eliminan sin dejar ningún marcador. ", + replace: "Las coincidencias se sustituyen por el texto de reemplazo que figura a continuación. ", + record: { + redact: "Las coincidencias se envían como de costumbre, se registran en el registro y se notifican. ", + inspect_tools: "Una llamada coincidente es devuelta como de costumbre, registrada en el registro y notificada. ", + content: "Las coincidencias se dejan sin cambios, registradas en el registro y notificadas. ", + }, + }, + blockRequestOnly: "El rechazo se aplica sólo a las solicitudes: las respuestas se transmiten, y el texto ya entregado no puede ser retirado.", + replacement: "Texto de sustitución", + replacementHint: "Las coincidencias se sustituyen por este texto, que no se puede restaurar.", + replacementRequired: "Introduzca el texto de reemplazo", + builtinReplace: (text: string) => `Las coincidencias se sustituyen por ${text}, que no pueden ser restauradas. `, + factory: (what: string) => `La configuración de la fábrica es “${what}”.`, + state: "Estado", + on: "Activar", + off: "Desactivado", + replacedWith: "Reemplazado por", + category: (kind: string) => `Categoría: ${kind}`, + sample: "Texto de prueba", + testAs: { + request: "Ensayo a petición", + response: "Prueba como respuesta", + }, + samplePlaceholder: { + redact: "Pegar algún texto, como variables de entorno que contienen una clave", + inspect_tools: "Pegar los argumentos de una llamada de herramienta, como un comando a ejecutar", + content: "Pegar un mensaje de usuario o un resultado de la herramienta", + }, + sampleAnswer: "Pegar el texto de una respuesta modelo", + hits: (n: number) => (n === 1 ? "1 partido" : `${n} coincidencias`), + rule: "Regla", + noHit: "No coincide.", + content: "Contenido", + line: (n: number) => `Línea ${n}`, + testDesc: "Comprueba un texto con las reglas que están en marcha. No se envía ninguna solicitud.", + output: "Después del procesamiento", + refused: (mode: string) => `Cuando la protección es ${mode}, esta solicitud no se envía, y se le dice al cliente por qué.`, + monitoring: "Esta protección está en Monitor: las reglas sólo registran coincidencias y no cambian nada.", + builtin: "Incorporado", + copyAsCustom: "Copiar como regla personalizada", + nameRequired: "Introduce un nombre.", + nameTaken: "Una regla con este nombre ya existe", + patternRequired: { + contains: "Introduzca el texto a buscar", + regex: "Introduzca una expresión regular", + codepoints: "Introduzca los puntos de código", + }, + labelRequired: "Introduzca un nombre de marcador de posición", + create: "Crear", + saveFailed: "No guardado", + deleteTitle: (name: string) => `Suprímase la regla “${name}”`, + deleteDesc: "La regla ya no se comprueba. Las entradas que ya están en el registro se mantienen.", + deleteFailed: "No eliminado", + }, + }, ); diff --git a/src/security/RuleDialog.tsx b/src/security/RuleDialog.tsx index 7ec09b30..4620b9b7 100644 --- a/src/security/RuleDialog.tsx +++ b/src/security/RuleDialog.tsx @@ -728,10 +728,10 @@ export function BuiltinRuleDialog({ - {viewName(rule)} + {viewName(guard, rule)} {t.builtin} - {why || t.category(kindName(catalogKinds(guard), rule.kind))} + {why || t.category(kindName(guard, catalogKinds(guard), rule.kind))}
@@ -740,7 +740,7 @@ export function BuiltinRuleDialog({ {written?.match === "regex" ? ( {written.pattern} ) : ( - + )}
diff --git a/src/security/SecurityPage.i18n.tsx b/src/security/SecurityPage.i18n.tsx index eb7c0893..eb83cf23 100644 --- a/src/security/SecurityPage.i18n.tsx +++ b/src/security/SecurityPage.i18n.tsx @@ -66,4 +66,65 @@ export const securityPageText = messages( modeSet: (guard: string, mode: string) => `${guard} set to ${mode}`, ruleCreated: (name: string) => `Rule “${name}” created`, }, + { + "zh-Hant": { + log: "日誌", + modes: { + enforce: "項開啟", + observe: "項監控", + off: "項關閉", + }, + hits: (_count: number, n: ReactNode, range: string, custom: boolean) => (<> + {custom ? range : `${range}內`} {n} 次命中 + ), + outcomes: { + cut: "已切斷", + blocked: "已拒絕", + stripped: "已刪除", + replaced: "已替換", + recorded: "僅記錄", + } satisfies Record, + loadFailed: "安全設定讀取失敗", + ruleOn: (name: string) => `已啟用「${name}」`, + actionSet: (name: string, action: string) => `「${name}」的動作已改為「${action}」`, + modeSet: (guard: string, mode: string) => `${guard}已切換為「${mode}」`, + ruleCreated: (name: string) => `已建立規則「${name}」`, + }, + ja: { + log: "ログ", + modes: { enforce: "件有効", observe: "件監視中", off: "件無効" }, + hits: (_count: number, n: ReactNode, range: string, custom: boolean) => (<>{custom ? range : `過去 ${range}`} に {n} 件検出), + outcomes: { cut: "切断", blocked: "拒否", stripped: "削除", replaced: "置換", recorded: "記録のみ" }, + loadFailed: "セキュリティ設定を読み込めませんでした", + ruleOn: (name: string) => `「${name}」を有効にしました`, + ruleOff: (name: string) => `「${name}」を無効にしました`, + actionSet: (name: string, action: string) => `「${name}」の処理を「${action}」に設定しました`, + modeSet: (guard: string, mode: string) => `${guard}を「${mode}」に設定しました`, + ruleCreated: (name: string) => `ルール「${name}」を作成しました`, + }, + es: { + log: "Registro", + modes: { + enforce: "el", + observe: "seguimiento", + off: "apagado", + }, + hits: (count: number, n: ReactNode, range: string, custom: boolean) => (<> + {n} {count === 1 ? "igualar" : "coincidencias"} {custom ? lower(range) : `en el último ${range}`} + ), + outcomes: { + cut: "cortado", + blocked: "denegada", + stripped: "borrado", + replaced: "sustituido", + recorded: "registrados", + }, + loadFailed: "La configuración de seguridad no se pudo cargar", + ruleOn: (name: string) => `“${name}” activado`, + ruleOff: (name: string) => `“${name}” apagado`, + actionSet: (name: string, action: string) => `Acción «${name}» establecida en ${action}`, + modeSet: (guard: string, mode: string) => `${guard} Se fija en ${mode}`, + ruleCreated: (name: string) => `Regla “${name}” creada`, + }, + }, ); diff --git a/src/security/SecurityPage.tsx b/src/security/SecurityPage.tsx index 252f5d63..5cd6a88d 100644 --- a/src/security/SecurityPage.tsx +++ b/src/security/SecurityPage.tsx @@ -196,7 +196,7 @@ export default function SecurityPage({ /** 启用、停用一条规则。可撤销:先拨过去,写完给「撤销」 */ function toggle(guard: Guard, r: SecurityRuleView, enabled: boolean) { - const name = viewName(r); + const name = viewName(guard, r); void undoable({ message: enabled ? t.ruleOn(name) : t.ruleOff(name), apply: () => @@ -223,7 +223,7 @@ export default function SecurityPage({ ), ); void undoable({ - message: t.actionSet(viewName(r), lt.ruleActions[action] ?? action), + message: t.actionSet(viewName(guard, r), lt.ruleActions[action] ?? action), apply: () => detail.mutate((d) => ({ ...d!, @@ -264,7 +264,7 @@ export default function SecurityPage({ guard, editing: null, seed: { - name: viewName(r), + name: viewName(guard, r), pattern: written?.pattern ?? "", match: written?.match, cased: written?.cased, diff --git a/src/security/catalog.ts b/src/security/catalog.ts index 56ba76f7..857bfb98 100644 --- a/src/security/catalog.ts +++ b/src/security/catalog.ts @@ -1,4 +1,3 @@ -import { getLang } from "@/i18n"; import { peek, useResource } from "@/lib/resource"; import type { Guard, SecurityDetail, SecurityKindView, SecurityRuleView } from "@/types"; import { api } from "./api"; @@ -6,15 +5,12 @@ import { api } from "./api"; /** * 规则目录:三项防护的规则表(`GET /security`),和安全页读的是同一份缓存。 * - * **规则的名字、说明、分组名只在 core 写一份**,中英文各一个字段(`name` / `name_zh`、 - * `why` / `why_zh`、`about` / `about_zh`,分组是 `kinds`)。界面不再自己存名称表。 - * 安全日志、流量页的徽标只带规则 id 和英文名,中文名按 id 到这里查。 + * Core 给规则和分组的英文原文。Lite 按防护类型、规则 ID 和分组 slug 查译文。 */ export const CATALOG_KEY = "security-detail"; /** - * 用到规则名的地方挂上它:没取过就取一次,取到了重画。安全页之外(流量页的徽标、请求 - * 详情)也要挂,否则那里查不到中文名。 + * 用到实时规则目录的地方挂上它。界面词表本身不依赖这次读取。 */ export function useRuleCatalog(): SecurityDetail | undefined { return useResource(CATALOG_KEY, () => api.detail()).data; @@ -30,8 +26,3 @@ export function catalogRule(guard: string, id: string): SecurityRuleView | undef export function catalogKinds(guard: Guard): SecurityKindView[] | undefined { return peek(CATALOG_KEY)?.[guard]?.kinds; } - -/** 按界面语言取:中文界面用中文那一份,没有就退回英文 */ -export function localized(en: string | undefined, zh: string | undefined): string { - return (getLang() === "zh" && zh) || en || ""; -} diff --git a/src/security/exceptions.test.tsx b/src/security/exceptions.test.tsx index d2b904b2..df09a851 100644 --- a/src/security/exceptions.test.tsx +++ b/src/security/exceptions.test.tsx @@ -84,8 +84,8 @@ describe("例外一节", () => { expect(text).toContain("例外 · 2 个值"); expect(html.match(/data-slot="exception"/g)).toHaveLength(2); expect(text).toContain("sk-ant-api03-…Q3xA"); - // 规则目录没取到时写 id - expect(text).toContain("anthropic-api-key"); + // 已知规则在目录未加载时也用本地译文 + expect(text).toContain("Anthropic API 密钥"); expect(text).toContain("test…1234 —"); expect(text).toContain("移出例外"); // 只有掩码后的值,没有哈希 diff --git a/src/security/export.i18n.ts b/src/security/export.i18n.ts index 8fcca93d..bfeab7cd 100644 --- a/src/security/export.i18n.ts +++ b/src/security/export.i18n.ts @@ -92,4 +92,115 @@ export const exportText = messages( }, fileName: "security-log", }, + { + "zh-Hant": { + columns: { + time: "時間", + action: "處置", + guard: "型別", + rule: "規則", + ruleId: "規則 ID", + ruleSource: "規則來源", + pattern: "規則寫法", + matching: "匹配方式", + coreVersion: "core 版本", + excerpt: "命中", + count: "次數", + revealed: "隱藏內容", + direction: "方向", + locations: "位置", + outcome: "處置細節", + requestId: "請求", + session: "會話", + key: "金鑰", + keyMasked: "金鑰掩碼", + provider: "上游", + model: "模型", + sentModel: "發往上游的模型", + app: "應用", + peer: "來源", + }, + builtin: "內建", + custom: "自定義", + more: (n: number) => `另有 ${n} 處未列出`, + outcome: { + recorded: "僅記錄", + replaced: (placeholders: string) => `替換為 ${placeholders}`, + replacedText: (n: number, text: string) => `替換 ${n} 處,替換為 ${text}`, + cut: (tool: string, args: string, truncated: boolean) => `切斷 ${tool} 呼叫,引數${truncated ? "(僅開頭)" : ""}:${args}`, + clientNotice: (text: string) => `用戶端收到:${text}`, + blocked: "請求未發往上游", + stripped: (n: number) => `刪除 ${n} 處`, + }, + fileName: "安全日誌", + }, + ko: { + columns: { + time: "시간", + action: "Action", + guard: "Type", + rule: "규칙", + ruleId: "Rule ID", + ruleSource: "Rule source", + pattern: "Pattern", + matching: "Match by", + coreVersion: "Core version", + excerpt: "Match", + count: "Count", + revealed: "Hidden text", + direction: "Direction", + locations: "Locations", + outcome: "Action detail", + requestId: "요청", + session: "Session", + key: "키", + keyMasked: "Masked key", + provider: "업스트림", + model: "모델", + sentModel: "Model sent to the upstream", + app: "App", + peer: "From", + }, + }, + es: { + columns: { + time: "Hora", + action: "Medidas adoptadas", + guard: "Tipo", + rule: "Regla", + ruleId: "Regla ID", + ruleSource: "Fuente de la regla", + pattern: "Patrón", + matching: "Coincidencia por", + coreVersion: "Versión básica", + excerpt: "Coincidencia", + count: "Contar", + revealed: "Texto oculto", + direction: "Dirección", + locations: "Ubicaciones", + outcome: "Detalle de la acción", + requestId: "Solicitud", + session: "Sesión", + key: "Clave", + keyMasked: "Tecla enmascarada", + provider: "Proveedor", + model: "Modelo", + sentModel: "Modelo enviado a la fase anterior", + app: "App", + peer: "Desde", + }, + builtin: "Incorporado", + custom: "Personalizado", + more: (n: number) => (n === 1 ? "1 coincidencia más no listada" : `${n} más coincidencias no enumeradas`), + outcome: { + recorded: "Grabado únicamente", + replaced: (placeholders: string) => `Sustituida por ${placeholders}`, + replacedText: (n: number, text: string) => n === 1 ? `Reemplazado 1 segmento por ${text}` : `Segmentos sustituidos ${n} por ${text}`, + cut: (tool: string, args: string, truncated: boolean) => `Cortar la llamada ${tool}; argumentos${truncated ? " (A partir de sólo)" : ""}: ${args}`, + clientNotice: (text: string) => `Cliente recibido: ${text}`, + blocked: "No se envía a la línea de del proveedor", + stripped: (n: number) => (n === 1 ? "Suprimido 1 segmento" : `Segmentos suprimidos ${n}`), + }, + }, + }, ); diff --git a/src/security/export.test.ts b/src/security/export.test.ts index a74835bf..ff19c4f7 100644 --- a/src/security/export.test.ts +++ b/src/security/export.test.ts @@ -19,7 +19,6 @@ beforeAll(async () => { id: "anthropic-api-key", custom: false, name: "Anthropic API key", - name_zh: "Anthropic API 密钥", kind: "ai-services", matcher: { kind: "prefix" as const, prefix: "sk-ant-", min_tail: 20 }, enabled: true, diff --git a/src/security/groups.test.tsx b/src/security/groups.test.tsx index 59d7252b..413b33ec 100644 --- a/src/security/groups.test.tsx +++ b/src/security/groups.test.tsx @@ -33,18 +33,18 @@ const rule = (x: Partial): SecurityRuleView => ({ }); const RULES = [ - rule({ id: "anthropic-api-key", name: "Anthropic API key", name_zh: "Anthropic API 密钥", kind: "ai-services" }), - rule({ id: "openai-api-key", name: "OpenAI API key", name_zh: "OpenAI API 密钥", kind: "ai-services", enabled: false }), - rule({ id: "github-token", name: "GitHub token", name_zh: "GitHub 令牌", kind: "dev-platforms" }), - rule({ id: "passport", name: "Passport number", name_zh: "护照号码", kind: "id-documents" }), + rule({ id: "anthropic-api-key", name: "Anthropic API key", kind: "ai-services" }), + rule({ id: "openai-api-key", name: "OpenAI API key", kind: "ai-services", enabled: false }), + rule({ id: "github-personal-token", name: "GitHub personal access token", kind: "dev-platforms" }), + rule({ id: "cn-passport", name: "Chinese passport number", kind: "id-documents" }), rule({ id: "客户编号", name: "客户编号", custom: true, kind: "custom" }), ]; -const KINDS: SecurityKindView[] = [ - { slug: "ai-services", name: "AI services", name_zh: "AI 服务" }, - { slug: "dev-platforms", name: "Developer platforms", name_zh: "开发平台" }, - { slug: "id-documents", name: "ID documents", name_zh: "证件" }, - { slug: "custom", name: "Custom", name_zh: "自定义" }, +const KINDS: Pick[] = [ + { slug: "ai-services", name: "AI services" }, + { slug: "dev-platforms", name: "Developer platforms" }, + { slug: "id-documents", name: "ID documents" }, + { slug: "custom", name: "Custom" }, ]; const hit = (rule: string, count: number, custom = false): SecurityRuleHits => ({ rule, custom, count }); @@ -104,21 +104,21 @@ describe("命中次数", () => { }); it("组头写条数、启用条数和命中次数;没有命中的不写次数", () => { - const html = table("", countHits([hit("github-token", 2)])); + const html = table("", countHits([hit("github-personal-token", 2)])); expect(heads(html)).toEqual([ - "开发平台 · 1 条 · 已开 1 条 · 最近 7 天命中 2 次", + "代码托管与软件发布 · 1 条 · 已开 1 条 · 最近 7 天命中 2 次", "AI 服务 · 2 条 · 已开 1 条", - "证件 · 1 条 · 已开 1 条", + "证件号码 · 1 条 · 已开 1 条", "自定义 · 1 条 · 已开 1 条", ]); }); it("英文界面同一句", () => { setLang("en"); - expect(heads(table("", countHits([hit("passport", 3)])))[0]).toBe( + expect(heads(table("", countHits([hit("cn-passport", 3)])))[0]).toBe( "ID documents · 1 rule · 1 on · 3 matches in the last 7 days", ); - expect(heads(table("", countHits([hit("passport", 1)])))[0]).toBe( + expect(heads(table("", countHits([hit("cn-passport", 1)])))[0]).toBe( "ID documents · 1 rule · 1 on · 1 match in the last 7 days", ); }); @@ -141,14 +141,14 @@ describe("组的先后", () => { }); it("次数尚未读到:照 core 的顺序", () => { - expect(heads(table()).map((h) => h.split(" · ")[0])).toEqual(["AI 服务", "开发平台", "证件", "自定义"]); + expect(heads(table()).map((h) => h.split(" · ")[0])).toEqual(["AI 服务", "代码托管与软件发布", "证件号码", "自定义"]); }); it("检索时照样有命中的排在前面", () => { - // 「p」筛出 AI 服务的两条(api)和证件(passport) - const hits = countHits([hit("passport", 1)]); - expect(heads(table("p", hits)).map((h) => h.split(" · ")[0])).toEqual(["证件", "AI 服务"]); - expect(heads(table("", hits)).map((h) => h.split(" · ")[0])).toEqual(["证件", "AI 服务", "开发平台", "自定义"]); + // 「p」匹配 API、passport 和 personal token。命中的证件组仍然排在最前。 + const hits = countHits([hit("cn-passport", 1)]); + expect(heads(table("p", hits)).map((h) => h.split(" · ")[0])).toEqual(["证件号码", "AI 服务", "代码托管与软件发布"]); + expect(heads(table("", hits)).map((h) => h.split(" · ")[0])).toEqual(["证件号码", "AI 服务", "代码托管与软件发布", "自定义"]); }); }); @@ -170,7 +170,7 @@ describe("展开与收起", () => { const html = table(); expect(ruleRows(html)).toBe(2); expect(html).toContain("Anthropic API 密钥"); - expect(html).not.toContain("GitHub 令牌"); + expect(html).not.toContain("GitHub 个人令牌"); }); it("存的东西坏了、或者读不到:照默认收起", () => { @@ -188,10 +188,10 @@ describe("展开与收起", () => { it("检索时匹配的组自动展开,筛掉的行不画", () => { fakeStorage(); const html = table("令牌"); - expect(heads(html)).toEqual(["开发平台 · 1 条 · 已开 1 条"]); + expect(heads(html)).toEqual(["代码托管与软件发布 · 1 条 · 已开 1 条"]); expect(html).toContain('aria-expanded="true"'); expect(ruleRows(html)).toBe(1); - expect(html).toContain("GitHub 令牌"); + expect(html).toContain("GitHub 个人令牌"); }); it("检索时收起的组只在这一次检索里算;不检索时按记下的", () => { diff --git a/src/security/labels.i18n.tsx b/src/security/labels.i18n.tsx index 42dcf246..206922b6 100644 --- a/src/security/labels.i18n.tsx +++ b/src/security/labels.i18n.tsx @@ -111,7 +111,7 @@ export const securityLabelsText = messages( matcher: { /** * 危险命令里代码实现的检查(`builtin`),按检查名说它查什么。密钥与隐私的内置规则不在 - * 这里:它们的说明由 core 给(`about` / `about_zh`) + * 这里:它们使用客户端词表和 Core 的英文 `about` */ builtin: { "credential-to-network": "凭据发往本机和该凭据的服务商以外的主机", @@ -234,4 +234,213 @@ export const securityLabelsText = messages( codepoints: (code: Code, ranges: string[]) => <>Code points {or(ranges.map(code), ", ", " and ")}, }, }, + { + "zh-Hant": { + guardShort: { + redact: "金鑰與隱私", + inspect_tools: "危險命令", + content: "內容過濾", + }, + modes: { + enforce: "開啟", + observe: "監控", + off: "關閉", + }, + monitoring: "監控中", + actions: { + recorded: "僅記錄", + replaced: "已替換", + cut: "已切斷", + stripped: "已刪除", + blocked: "已拒絕", + } as Record, + ruleActions: { + placeholder: "替換為佔位符", + cut: "切斷", + block: "拒絕", + strip: "刪除", + replace: "替換", + record: "僅記錄", + } as Record, + custom: "自定義", + toolResult: "工具結果", + parts: { + system: "系統提示", + message: (n: number) => `第 ${n} 條訊息`, + tool_result: "工具結果", + tool_call: "工具呼叫", + response_text: "回答 · 正文", + }, + roles: { + user: "使用者", + assistant: "助手", + tool: "工具", + system: "系統", + developer: "開發者", + } as Record, + directions: { + request: "請求", + response: "回答", + }, + matching: { + contains: "包含", + regex: "正則", + codepoints: "碼位", + }, + caseSensitive: "區分大小寫", + savedSource: { + "upstream-key": (name: string) => `上游「${name}」的金鑰`, + "upstream-header": (name: string) => `上游「${name}」請求頭中的值`, + "access-key": (name: string) => `閘道器金鑰「${name}」`, + "proxy-password": (name: string) => `代理「${name}」的密碼`, + "control-key": () => "遠端控制金鑰", + "sync-credential": () => "同步與備份憑據", + } as Record string>, + detail: { + times: (n: number) => `出現 ${n} 次`, + revealed: (text: string) => `隱藏內容「${text}」`, + chars: (n: number) => `共 ${n.toLocaleString()} 個字元`, + }, + matcher: { + builtin: { + "credential-to-network": "憑據發往本機和該憑據的服務商以外的主機", + "file-to-network": "本地檔案的內容上傳到外部主機", + "thinkwatch-data": "路徑或命令指向 ThinkWatch 的資料目錄;只是提到不算", + } as Record, + listSep: "、", + builtinOther: "由內建檢查判斷", + regex: (code: Code, pattern: string, cased: boolean) => (<> + 正則 {code(pattern)} + {!cased && ",不区分大小写"} + ), + contains: (code: Code, text: string, cased: boolean) => (<> + 包含 {code(text)},{cased ? "區分大小寫" : "不區分大小寫"} + ), + codepoints: (code: Code, ranges: string[]) => <>碼位 {or(ranges.map(code), "、", "、")}, + }, + }, + ko: { + modes: { + enforce: "On", + observe: "Monitor", + off: "끄기", + }, + ruleActions: { + placeholder: "Replace with placeholder", + cut: "Cut off", + block: "Refuse", + strip: "삭제", + replace: "Replace", + record: "Record only", + }, + roles: { + user: "User", + assistant: "Assistant", + tool: "Tool", + system: "시스템 설정", + developer: "Developer", + }, + directions: { + request: "요청", + response: "Answer", + }, + day: { + today: "오늘", + yesterday: "Yesterday", + }, + }, + es: { + guards: { + redact: "Secretos y privacidad", + inspect_tools: "Comandos peligrosos", + content: "Filtro de contenido", + }, + guardShort: { + redact: "Secretos", + inspect_tools: "Comandos", + content: "Contenido", + }, + modes: { + enforce: "Activar", + observe: "Monitor", + off: "Desactivado", + }, + monitoring: "Supervisión", + actions: { + recorded: "Grabado", + replaced: "Reemplazado", + cut: "Cortar", + stripped: "Suprimido", + blocked: "Denegada", + }, + ruleActions: { + placeholder: "Reemplazar con marcador de posición", + cut: "Cortar", + block: "Rechazar", + strip: "Eliminar", + replace: "Sustitúyase", + record: "Grabación únicamente", + }, + custom: "Personalizado", + toolResult: "resultado de la herramienta", + parts: { + system: "Indicación del sistema", + message: (n: number) => `Mensaje ${n}`, + tool_result: "Resultado de la herramienta", + tool_call: "Llamada de la herramienta", + response_text: "Respuesta · texto", + }, + roles: { + user: "Usuario", + assistant: "Asistente", + tool: "Herramienta", + system: "Sistema", + developer: "Desarrollador", + }, + directions: { + request: "Solicitud", + response: "Respuesta", + }, + matching: { + contains: "Contiene", + regex: "Regex", + codepoints: "Puntos de código", + }, + caseSensitive: "Caso correspondiente", + day: { + today: "Hoy", + yesterday: "Ayer", + }, + savedSource: { + "upstream-key": (name: string) => `Clave de del proveedor “${name}”`, + "upstream-header": (name: string) => `Valor de la cabecera de del proveedor “${name}”`, + "access-key": (name: string) => `Clave de entrada “${name}”`, + "proxy-password": (name: string) => `Contraseña del proxy “${name}”`, + "control-key": () => "Tecla de control remoto", + "sync-credential": () => "Sincronización y credencial de respaldo", + }, + detail: { + times: (n: number) => `${n} veces`, + revealed: (text: string) => `texto oculto “${text}”`, + chars: (n: number) => (n === 1 ? "1 carácter" : `${n.toLocaleString()} caracteres`), + }, + matcher: { + builtin: { + "credential-to-network": "Una credencial enviada a un anfitrión distinto de esta máquina y al proveedor de la credencialidad", + "file-to-network": "El contenido de un archivo local subido a un host externo", + "thinkwatch-data": "Una ruta o comando que apunta al directorio de datos de ThinkWatch; una mención no cuenta", + }, + listSep: ", ", + builtinOther: "Decidido por un cheque incorporado", + regex: (code: Code, pattern: string, cased: boolean) => (<> + Regex {code(pattern)} + {!cased && ", ignoring case"} + ), + contains: (code: Code, text: string, cased: boolean) => (<> + Contiene {code(text)}, {cased ? "caso correspondiente" : "ignorando el caso"} + ), + codepoints: (code: Code, ranges: string[]) => <>Puntos de código {or(ranges.map(code), ", ", " y ")}, + }, + }, + }, ); diff --git a/src/security/labels.test.ts b/src/security/labels.test.ts index 2363a367..64a10292 100644 --- a/src/security/labels.test.ts +++ b/src/security/labels.test.ts @@ -126,14 +126,13 @@ describe("码位规则的命中", () => { }); }); -/** 内置内容规则的说明:中文取 core 给的 why_zh;英文那句以名字开头的,名字去掉(名字在上一行) */ +/** 内置内容规则的说明:中文取客户端译文;英文那句以名字开头的,名字去掉(名字在上一行) */ describe("内容规则的说明", () => { const rule = (why: string): SecurityRuleView => ({ id: "bidi-controls", custom: false, name: "Bidirectional controls", why, - why_zh: "可使屏幕上的显示顺序与实际字符顺序不一致。", kind: "invisible", matcher: { kind: "codepoints", ranges: ["U+202A–U+202E", "U+2066–U+2069"] }, enabled: true, @@ -142,7 +141,7 @@ describe("内容规则的说明", () => { default_action: "strip", }); - it("中文取 why_zh", () => { + it("中文取客户端译文", () => { expect(ruleWhy("content", rule("Bidirectional controls: they reorder text."))).toBe( "可使屏幕上的显示顺序与实际字符顺序不一致。", ); diff --git a/src/security/labels.tsx b/src/security/labels.tsx index 1d4d32dc..dbbcac7e 100644 --- a/src/security/labels.tsx +++ b/src/security/labels.tsx @@ -1,6 +1,6 @@ import { Fragment } from "react"; import { StatusLabel, type StatusTone } from "@/ui/status-dot"; -import { getLang, textOf, useText } from "@/i18n"; +import { getLang, localeTag, textOf, useText } from "@/i18n"; import type { ContentMatch, Guard, @@ -13,7 +13,8 @@ import type { SecurityOutcome, SecurityRuleView, } from "@/types"; -import { catalogRule, localized } from "./catalog"; +import { guardKind, guardRuleText } from "@/i18n/guard.i18n"; +import { catalogRule } from "./catalog"; import { securityLabelsText } from "./labels.i18n"; /** @@ -55,28 +56,26 @@ export const OUTCOMES: readonly SecurityOutcome[] = ["cut", "blocked", "stripped /** * 一条规则叫什么:日志、流量页徽标这些只带 id 的地方用。 * - * **名字由 core 给**(规则表里的 `name` / `name_zh`),这里按 id 到规则目录里查(见 - * `catalog.ts`;用到的组件要挂上 `useRuleCatalog`)。**自定义规则的 id 就是用户起的名字**, - * 原样显示。目录还没取到、或者规则已经没有了,退回日志里存的英文名,再没有就是 id。 + * 内置规则按防护类型和 id 查 Lite 译文,退回目录或日志提供的英文名。自定义名称原样显示。 */ export function ruleName(guard: string, id: string, custom?: boolean, fallback?: string): string { if (custom) return id; const r = catalogRule(guard, id); - return r ? viewName(r) : (fallback ?? id); + return guardRuleText(guard, id, "name", r?.name || fallback || id); } -/** 规则列表里的一条叫什么:内置的按界面语言取 `name` / `name_zh`,自定义的就是它的名字 */ -export function viewName(r: SecurityRuleView): string { - return r.custom ? r.name : localized(r.name, r.name_zh); +/** 内置规则查译文,自定义名称原样显示。 */ +export function viewName(guard: Guard, r: SecurityRuleView): string { + return r.custom ? r.name : guardRuleText(guard, r.id, "name", r.name || r.id); } /** * 内置规则为什么值得看一眼(危险命令、内容过滤有;规则名说得清的没有)。按界面语言取 - * `why` / `why_zh`。 + * 本地译文或 Core 的英文 `why`。 */ export function ruleWhy(guard: Guard, r: SecurityRuleView): string { if (r.custom || !r.why) return ""; - const why = localized(r.why, r.why_zh); + const why = guardRuleText(guard, r.id, "why", r.why); if (guard !== "content" || why !== r.why) return why; // 内容规则英文那句可能以名字开头(「Bidirectional controls: …」),名字已经在上一行了 const lead = `${r.name}:`.toLowerCase(); @@ -89,9 +88,11 @@ export function ruleWhy(guard: Guard, r: SecurityRuleView): string { * 规则表的分组叫什么:core 给的 `kinds` 里按 `slug` 查。查不到(旧的 core 不给)时 * 自定义那一组照样叫「自定义」,其余写 slug。 */ -export function kindName(kinds: readonly SecurityKindView[] | undefined, slug: string): string { +export function kindName(guard: Guard, kinds: readonly Pick[] | undefined, slug: string): string { + const translated = guardKind(guard, slug); + if (translated) return translated; const k = kinds?.find((x) => x.slug === slug); - if (k) return localized(k.name, k.name_zh); + if (k) return k.name; return slug === "custom" ? textOf(securityLabelsText).custom : slug; } @@ -228,12 +229,12 @@ export function CoreText({ text }: { text: string }) { /** * 一条规则认什么,写成一句话。 * - * **密钥与隐私的内置规则由 core 写**(`about` / `about_zh`)。其余的按判据写:自定义 + * 密钥与隐私的内置规则按判据或词表取说明。其余的按判据写:自定义 * 规则和内容规则是正则、包含、码位,危险命令里代码实现的检查按检查名说它查什么。 */ -export function RuleMatchText({ r }: { r: SecurityRuleView }) { +export function RuleMatchText({ guard, r }: { guard: Guard; r: SecurityRuleView }) { useText(securityLabelsText); - const about = r.custom ? "" : localized(r.about, r.about_zh); + const about = r.custom || guard !== "redact" ? "" : guardRuleText(guard, r.id, "about", r.about, r.matcher); return about ? : ; } @@ -317,9 +318,9 @@ export function dayHead(ms: number, now = Date.now()): { title: string; date: st const today = new Date(now); const yesterday = new Date(now); yesterday.setDate(today.getDate() - 1); - const date = new Intl.DateTimeFormat(getLang() === "zh" ? "zh-CN" : "en-US", { + const date = new Intl.DateTimeFormat(localeTag(getLang()), { year: d.getFullYear() === today.getFullYear() ? undefined : "numeric", - month: getLang() === "zh" ? "long" : "short", + month: getLang() === "en" ? "short" : "long", day: "numeric", weekday: "short", }).format(d); diff --git a/src/security/redact.test.tsx b/src/security/redact.test.tsx index 28e1a159..bc57181d 100644 --- a/src/security/redact.test.tsx +++ b/src/security/redact.test.tsx @@ -9,19 +9,11 @@ import { CoreText, EventDetail, kindName, RuleMatchText, ruleName, ruleWhy, save import { marksFromEvents } from "./marks"; import { groupRules } from "./rules"; -/** - * 规则的名字、说明、分组名由 core 给(规则表里的 `name_zh` / `why_zh` / `about` / - * `about_zh`,分组是 `kinds`)。界面只管按语言取、反引号画成代码,以及缺了的时候退回得 - * 体面:中文缺了用英文,规则目录没取到用日志里存的英文名,再没有就是 id。 - */ - const rule = (x: Partial): SecurityRuleView => ({ id: "anthropic-api-key", custom: false, name: "Anthropic API key", - name_zh: "Anthropic API 密钥", about: "Starts with `sk-ant-`, followed by at least 20 characters", - about_zh: "`sk-ant-` 开头,其后至少 20 个字符", kind: "ai-services", matcher: { kind: "prefix", prefix: "sk-ant-", min_tail: 20 }, enabled: true, @@ -29,10 +21,10 @@ const rule = (x: Partial): SecurityRuleView => ({ ...x, }); -const KINDS: SecurityKindView[] = [ - { slug: "saved", name: "Saved credentials", name_zh: "保存的密钥" }, - { slug: "ai-services", name: "AI services", name_zh: "AI 服务" }, - { slug: "custom", name: "Custom", name_zh: "自定义" }, +const KINDS: Pick[] = [ + { slug: "saved", name: "Saved credentials" }, + { slug: "ai-services", name: "AI services" }, + { slug: "custom", name: "Custom" }, ]; const guard = (rules: SecurityRuleView[], kinds: SecurityKindView[] = []): GuardDetail => ({ mode: "enforce", rules, kinds }); @@ -53,25 +45,25 @@ const plain = (node: React.ReactNode) => html(node).replace(/<[^>]+>/g, ""); beforeEach(() => resetResources()); describe("规则名", () => { - it("内置规则按界面语言取 core 给的名字", () => { - expect(viewName(rule({}))).toBe("Anthropic API 密钥"); + it("内置规则按界面语言取客户端译文", () => { + expect(viewName("redact", rule({}))).toBe("Anthropic API 密钥"); setLang("en"); - expect(viewName(rule({}))).toBe("Anthropic API key"); + expect(viewName("redact", rule({}))).toBe("Anthropic API key"); }); it("没有中文名的退回英文名;自定义规则就是它的名字", () => { - expect(viewName(rule({ name_zh: undefined }))).toBe("Anthropic API key"); - expect(viewName(rule({ id: "客户编号", name: "客户编号", custom: true, name_zh: undefined }))).toBe("客户编号"); + expect(viewName("redact", rule({ id: "new-key" }))).toBe("Anthropic API key"); + expect(viewName("redact", rule({ id: "客户编号", name: "客户编号", custom: true }))).toBe("客户编号"); }); it("只带 id 的地方按 id 到规则目录里查", async () => { - // 目录还没取到:日志里存的英文名,再没有就是 id - expect(ruleName("redact", "anthropic-api-key", false, "Anthropic API key")).toBe("Anthropic API key"); - expect(ruleName("redact", "anthropic-api-key")).toBe("anthropic-api-key"); + // 目录还没取到也能显示客户端译文 + expect(ruleName("redact", "anthropic-api-key", false, "Anthropic API key")).toBe("Anthropic API 密钥"); + expect(ruleName("redact", "anthropic-api-key")).toBe("Anthropic API 密钥"); await seed({ redact: guard([rule({})]), inspect_tools: guard([ - rule({ id: "curl-pipe-sh", name: "Download and run", name_zh: "下载即执行", kind: "command" }), + rule({ id: "curl-pipe-sh", name: "Download and run", kind: "command" }), ]), }); expect(ruleName("redact", "anthropic-api-key")).toBe("Anthropic API 密钥"); @@ -91,24 +83,24 @@ describe("规则名", () => { rule: "anthropic-api-key", rule_snapshot: { builtin: true, id: "anthropic-api-key", name: "Anthropic API key", core_version: "0.85.0" }, }); - expect(snapshotName(e)).toBe("Anthropic API key"); + expect(snapshotName(e)).toBe("Anthropic API 密钥"); await seed({ redact: guard([rule({})]) }); expect(snapshotName(e)).toBe("Anthropic API 密钥"); }); }); describe("规则说明", () => { - it("why:中文界面取 why_zh,缺了退回英文", () => { - const r = rule({ id: "curl-pipe-sh", why: "Runs whatever the remote serves", why_zh: "下载后直接执行" }); - expect(ruleWhy("inspect_tools", r)).toBe("下载后直接执行"); - expect(ruleWhy("inspect_tools", { ...r, why_zh: undefined })).toBe("Runs whatever the remote serves"); + it("why:取客户端译文,缺译回退英文", () => { + const r = rule({ id: "curl-pipe-sh", why: "Runs whatever the remote serves" }); + expect(ruleWhy("inspect_tools", r)).toBe("下载后直接执行,执行的内容由远端决定且无法预先查看"); + expect(ruleWhy("inspect_tools", { ...r, id: "new-rule" })).toBe("Runs whatever the remote serves"); expect(ruleWhy("inspect_tools", { ...r, why: "" })).toBe(""); setLang("en"); expect(ruleWhy("inspect_tools", r)).toBe("Runs whatever the remote serves"); }); it("about:按语言取,反引号里的画成代码", () => { - expect(html()).toBe( + expect(html()).toBe( html( <> sk-ant- @@ -117,7 +109,7 @@ describe("规则说明", () => { ), ); setLang("en"); - expect(plain()).toBe("Starts with sk-ant-, followed by at least 20 characters"); + expect(plain()).toBe("Starts with sk-ant-, followed by at least 20 characters"); }); it("反引号落单时照普通文字画", () => { @@ -126,10 +118,9 @@ describe("规则说明", () => { }); it("没有 about:列出写法;没有写法的说是内置检查", () => { - expect(plain()).toBe("sk-ant-"); + expect(plain()).toBe("sk-ant-"); const vault = rule({ about: undefined, - about_zh: undefined, matcher: { kind: "prefixes", prefixes: [ @@ -138,21 +129,21 @@ describe("规则说明", () => { ], }, }); - expect(plain()).toBe("hvs.、hvb."); - expect(plain()).toBe( + expect(plain()).toBe("hvs.、hvb."); + expect(plain()).toBe( "由内置检查判断", ); }); it("中文缺了用英文的 about", () => { - expect(plain()).toBe( + expect(plain()).toBe( "Starts with sk-ant-, followed by at least 20 characters", ); }); it("危险命令里代码实现的检查、自定义规则照判据写", () => { - const check = rule({ id: "secret-to-unknown-host", about: undefined, about_zh: undefined, matcher: { kind: "builtin", check: "credential-to-network" } }); - expect(plain()).toBe("凭据发往本机和该凭据的服务商以外的主机"); + const check = rule({ id: "secret-to-unknown-host", about: undefined, matcher: { kind: "builtin", check: "credential-to-network" } }); + expect(plain()).toBe("凭据发往本机和该凭据的服务商以外的主机"); const custom = rule({ id: "客户编号", name: "客户编号", @@ -160,21 +151,21 @@ describe("规则说明", () => { about: "ignored", matcher: { kind: "regex", pattern: "CUST-\\d+", case_sensitive: true }, }); - expect(plain()).toBe("正则 CUST-\\d+"); + expect(plain()).toBe("正则 CUST-\\d+"); }); }); describe("分组", () => { - it("分组名取 core 给的 kinds", () => { - expect(kindName(KINDS, "ai-services")).toBe("AI 服务"); + it("分组名按 slug 查客户端词表", () => { + expect(kindName("redact", KINDS, "ai-services")).toBe("AI 服务"); setLang("en"); - expect(kindName(KINDS, "ai-services")).toBe("AI services"); + expect(kindName("redact", KINDS, "ai-services")).toBe("AI services"); }); - it("旧的 core 不给 kinds:自定义照样叫自定义,其余写 slug", () => { - expect(kindName(undefined, "custom")).toBe("自定义"); - expect(kindName(undefined, "ai-services")).toBe("ai-services"); - expect(kindName(KINDS, "vehicle")).toBe("vehicle"); + it("目录没取到时还能翻译已知分组,未知分组显示 slug", () => { + expect(kindName("redact", undefined, "custom")).toBe("自定义"); + expect(kindName("redact", undefined, "ai-services")).toBe("AI 服务"); + expect(kindName("redact", KINDS, "new-group")).toBe("new-group"); }); it("按 core 给的顺序分组,保存的密钥在最前,自定义在最后", () => { diff --git a/src/settings/FailoverSection.i18n.ts b/src/settings/FailoverSection.i18n.ts index 220533b7..8ae5a8d9 100644 --- a/src/settings/FailoverSection.i18n.ts +++ b/src/settings/FailoverSection.i18n.ts @@ -72,4 +72,99 @@ export const failoverText = messages( badWait: "A whole number from 0 to 600.", saveFailed: "Not saved", }, + { + "zh-Hant": { + title: "故障轉移", + intro: "上游失敗後暫停使用一段時間,請求交給下一個上游。暫停時長按上游給出的原因確定。", + label: { + failures_to_pause: "連續失敗", + pause_secs: "暫停時長", + max_pause_secs: "暫停上限", + no_balance_pause_secs: "餘額不足", + quota_pause_secs: "額度用完", + rate_limit_max_pause_secs: "速率限制", + idle_timeout_secs: "無回應超時", + wait_secs: "最多等待", + }, + what: { + failures_to_pause: "伺服器錯誤、無法連線等未說明原因的失敗,連續達到此次數後暫停。", + pause_secs: "此類失敗第一次暫停的時長,此後每次加倍。", + max_pause_secs: "加倍後的暫停時長不超過此值。", + no_balance_pause_secs: "上游報告餘額不足時暫停的時長。", + quota_pause_secs: "上游報告額度用完、但未給出重置時間時暫停的時長。給出重置時間的,暫停到重置為止。", + rate_limit_max_pause_secs: "上游速率限制時按其要求的等待時間暫停,最長為此值。", + idle_timeout_secs: "上游連續這麼久沒有發出內容即放棄:尚未向用戶端發出內容時轉到下一個上游,已經發出時以錯誤結束。預設 300 秒。", + wait_secs: "請求排隊等待上游空出位置、速率限制結束或用量上限恢復(含金鑰的分鐘、小時上限),以及上游暫時出錯後重試,兩者合計最多等待的時長,超過後返回錯誤。預設 120 秒,0 表示不排隊也不重試。", + }, + badCount: "須為 1 到 100 之間的整數。", + badSecs: "須為 1 到 604800 之間的整數。", + badMax: "須為整數,不小於暫停時長,不超過 604800。", + badIdle: "須為 30 到 3600 之間的整數。", + badWait: "須為 0 到 600 之間的整數。", + saveFailed: "未能儲存", + }, + ja: { + title: "フェイルオーバー", + intro: "アップストリームでエラーが発生すると、その利用を一時停止し、次のアップストリームへ転送します。停止時間はエラーの種類によって異なります。", + label: { + failures_to_pause: "連続失敗回数", + pause_secs: "停止時間", + max_pause_secs: "停止時間の上限", + no_balance_pause_secs: "残高不足", + quota_pause_secs: "利用枠を消費済み", + rate_limit_max_pause_secs: "レート制限", + idle_timeout_secs: "無応答タイムアウト", + wait_secs: "最大待機時間", + }, + what: { + failures_to_pause: "サーバーエラーや接続失敗など、具体的な理由がない失敗がこの回数に達すると一時停止します。", + pause_secs: "この種の失敗に対する初回の停止時間です。以後は停止するたびに倍になります。", + max_pause_secs: "停止時間は倍になってもこの値を超えません。", + no_balance_pause_secs: "アップストリームが残高不足を報告した場合の停止時間です。", + quota_pause_secs: "利用枠のリセット時刻が不明な場合の停止時間です。時刻がわかる場合はその時刻まで停止します。", + rate_limit_max_pause_secs: "レート制限がかかった場合は、アップストリームが指定した時間だけ停止します。この値が上限です。", + idle_timeout_secs: "この時間を超えてもデータが届かない場合は、まだクライアントに送信していなければ次へ切り替え、送信済みならエラーで終了します。既定値は 300 秒です。", + wait_secs: "空きや制限の解除を待つ時間と、一時的なエラーを再試行する時間の合計上限です。キーの分・時間あたりの上限も対象です。既定値は 120 秒で、0 の場合は待機も再試行も行いません。", + }, + times: "回", + secs: "秒", + badCount: "1〜100 の整数を入力してください。", + badSecs: "1〜604800 の整数を入力してください。", + badMax: "停止時間以上で 604800 以下の整数を入力してください。", + badIdle: "30〜3600 の整数を入力してください。", + badWait: "0〜600 の整数を入力してください。", + saveFailed: "保存できませんでした", + }, + es: { + title: "Fallo", + intro: "Un curso ascendente que falla se pausa por un tiempo y las peticiones van a la siguiente. La duración depende de la razón que da el curso ascendente.", + label: { + failures_to_pause: "Fracasos consecutivos", + pause_secs: "Pausa", + max_pause_secs: "La pausa más larga", + no_balance_pause_secs: "Equilibrio insuficiente", + quota_pause_secs: "Contingente agotado", + rate_limit_max_pause_secs: "Límite de la tasa", + idle_timeout_secs: "Tiempo muerto sin respuesta", + wait_secs: "Espera a lo sumo.", + }, + what: { + failures_to_pause: "Fallos sin una razón indicada, como errores de servidor y fallas de conexión, pausar el curso anterior después de esto muchos en una fila.", + pause_secs: "La primera pausa después de tales fracasos. Cada otra pausa la duplica.", + max_pause_secs: "La pausa duplicada no excede esto.", + no_balance_pause_secs: "La pausa cuando las del proveedor reportan un equilibrio insuficiente.", + quota_pause_secs: "La pausa cuando la parte anterior informa que su cuota se ha agotado sin decir cuándo se reinicia. Cuando lo hace, la pausa dura hasta entonces.", + rate_limit_max_pause_secs: "Una tasa limitada del proveedor se pausa para la espera que pide, a lo sumo tanto tiempo.", + idle_timeout_secs: "Un upstream que no envía ningún contenido durante este tiempo se abandona: la petición se mueve al siguiente upupstreap si nada ha llegado al cliente todavía, y termina con un error de otro modo. 300 s por defecto.", + wait_secs: "El tiempo total que una solicitud pasa en cola para un total, tasa-limitada o uso-limitado arriba (o el límite de una clave por minuto o por hora) y reintentando del proveedor que fallaron temporalmente; después de que termina con un error. 120 s por defecto; 0 significa no cola o reintentar.", + }, + times: "veces", + badCount: "Un número entero de 1 a 100.", + badSecs: "Un número entero de 1 a 604800.", + badMax: "Un número entero, no menos que la pausa y como máximo 604800.", + badIdle: "Un número entero de 30 a 3600.", + badWait: "Un número entero de 0 a 600.", + saveFailed: "No guardado", + }, + }, ); diff --git a/src/settings/GeneralSection.i18n.ts b/src/settings/GeneralSection.i18n.ts index 092c852b..9eca740c 100644 --- a/src/settings/GeneralSection.i18n.ts +++ b/src/settings/GeneralSection.i18n.ts @@ -111,4 +111,166 @@ export const generalText = messages( noticeApp: "In app only", noticeOff: "Off", }, + { + "zh-Hant": { + language: "語言", + languageSystem: (name: string) => `依照系統(${name})`, + appearance: "外觀", + system: "跟隨系統", + light: "淺色", + systemNow: (name: string) => `系統當前為${name}。`, + zoom: "介面大小", + zoomKeys: (bigger: string, smaller: string, reset: string) => `按 ${bigger} 放大、${smaller} 縮小,${reset} 恢復為 100%。`, + hotkey: "全域快捷鍵", + hotkeyWhat: "在任意程式中按下即可開啟主介面,主介面在最前時再按一次收起。", + hotkeyUnsupported: "當前桌面環境不支援全域性快捷鍵。", + hotkeyTaken: "該組合鍵已被其他程式佔用,請換一個。", + hotkeyNone: "未設定", + hotkeyPress: "請按下組合鍵", + hotkeyOff: "關閉", + hotkeyRestore: "恢復預設", + hotkeyNeedModifier: `須包含 Ctrl、Alt 或 ${isWindows ? "Win" : isLinux ? "Super" : "⌘"} 中的至少一個。`, + hotkeyInApp: (combo: string) => `${combo} 已用於介面內的操作,請換一個。`, + menubar: "選單列", + menubarWhat: "數值為今日的 token 用量與費用。", + menubarFull: "圖示和數值", + menubarIcon: "僅圖示", + menubarNumbers: "僅數值", + menubarHidden: "不顯示", + menubarHiddenWhat: "從 Finder 或 Spotlight 再次開啟 ThinkWatch Lite,即可顯示主視窗。", + menubarHiddenWhatHotkey: (combo: string) => `按 ${combo},或從 Finder 或 Spotlight 再次開啟 ThinkWatch Lite,即可顯示主視窗。`, + autostart: "登入時啟動", + autostartWhat: isWindows + ? "登入後僅在通知區域顯示圖示,不開啟視窗。" + : isLinux + ? "登入後僅在系統匣顯示圖示,不開啟視窗。" + : "登入後僅在選單列顯示圖示,不開啟視窗。", + autostartHiddenWhat: "登入後在後臺執行,不開啟視窗。", + noticeSystem: "系統通知", + noticeApp: "僅在應用內", + noticeOff: "關閉", + }, + ja: { + title: "一般", + language: "言語", + languageSystem: (name: string) => `システムに従う(${name})`, + appearance: "外観", + system: "システムに従う", + light: "ライト", + dark: "ダーク", + systemNow: (name: string) => `現在のシステム設定は「${name}」です。`, + zoom: "表示サイズ", + zoomKeys: (bigger: string, smaller: string, reset: string) => `${bigger} で拡大、${smaller} で縮小、${reset} で 100% に戻します。`, + hotkey: "グローバルショートカット", + hotkeyWhat: "どのアプリからでもメインウィンドウを開けます。最前面でもう一度押すと閉じます。", + hotkeyUnsupported: "このデスクトップ環境はグローバルショートカットに対応していません。", + hotkeyTaken: "このショートカットは別のアプリで使用されています。別の組み合わせを選んでください。", + hotkeyNone: "未設定", + hotkeyPress: "キーの組み合わせを入力", + hotkeyOff: "オフにする", + hotkeyRestore: "初期設定に戻す", + hotkeyNeedModifier: `Ctrl、Alt、${isWindows ? "Win" : isLinux ? "Super" : "⌘"} のいずれかを含めてください。`, + hotkeyInApp: (combo: string) => `${combo} はアプリ内で使用されています。別の組み合わせを選んでください。`, + menubar: "メニューバー", + menubarWhat: "今日のトークン使用量と費用を表示します。", + menubarFull: "アイコンと数値", + menubarIcon: "アイコンのみ", + menubarNumbers: "数値のみ", + menubarHidden: "非表示", + menubarHiddenWhat: "Finder または Spotlight から ThinkWatch Lite を開くと、メインウィンドウを表示できます。", + menubarHiddenWhatHotkey: (combo: string) => `${combo} を押すか、Finder または Spotlight から ThinkWatch Lite を開くと、メインウィンドウを表示できます。`, + autostart: "ログイン時に起動", + autostartWhat: isWindows + ? "ログイン時に通知領域にアイコンを表示します。ウィンドウは開きません。" + : isLinux + ? "ログイン時にシステムトレイにアイコンを表示します。ウィンドウは開きません。" + : "ログイン時にメニューバーにアイコンを表示します。ウィンドウは開きません。", + autostartHiddenWhat: "ログイン時にバックグラウンドで起動します。", + notices: "通知", + noticeSystem: "システム通知", + noticeApp: "アプリ内のみ", + noticeOff: "オフ", + }, + ko: { + title: "일반", + language: "언어", + languageSystem: (name: string) => `시스템 설정 따르기(${name})`, + appearance: "모양", + system: "시스템 설정", + light: "라이트", + dark: "다크", + systemNow: (name: string) => `현재 시스템 설정: ${name.toLowerCase()}.`, + zoom: "화면 크기", + zoomKeys: (bigger: string, smaller: string, reset: string) => `${bigger}으로 확대하고 ${smaller}으로 축소합니다. ${reset}을(를) 누르면 100%로 돌아갑니다.`, + hotkey: "전역 단축키", + hotkeyWhat: "어느 앱에서든 기본 창을 엽니다. 창이 앞에 있을 때 한 번 더 누르면 닫힙니다.", + hotkeyUnsupported: "이 데스크톱 환경에서는 전역 단축키를 지원하지 않습니다.", + hotkeyTaken: "다른 앱에서 이 단축키를 사용 중입니다. 다른 조합을 선택하세요.", + hotkeyNone: "설정되지 않음", + hotkeyPress: "단축키를 누르세요", + hotkeyOff: "끄기", + hotkeyRestore: "기본값 복원", + hotkeyNeedModifier: `Ctrl, Alt, ${isWindows ? "Win" : isLinux ? "Super" : "⌘"} 중 하나 이상을 포함해야 합니다.`, + hotkeyInApp: (combo: string) => `앱에서 이미 ${combo}을(를) 사용 중입니다. 다른 조합을 선택하세요.`, + menubar: "메뉴 막대", + menubarWhat: "오늘의 토큰 사용량과 비용을 표시합니다.", + menubarFull: "아이콘 및 숫자", + menubarIcon: "아이콘만", + menubarNumbers: "숫자만", + menubarHidden: "숨김", + menubarHiddenWhat: "Finder 또는 Spotlight에서 ThinkWatch Lite를 다시 열면 기본 창을 표시합니다.", + menubarHiddenWhatHotkey: (combo: string) => `${combo}을(를) 누르거나 Finder 또는 Spotlight에서 ThinkWatch Lite를 다시 열면 기본 창을 표시합니다.`, + autostart: "로그인 시 실행", + autostartWhat: isWindows + ? "로그인하면 알림 영역에 아이콘만 표시합니다. 창은 열리지 않습니다." + : isLinux + ? "로그인하면 시스템 트레이에 아이콘만 표시합니다. 창은 열리지 않습니다." + : "로그인하면 메뉴 막대에 아이콘만 표시합니다. 창은 열리지 않습니다.", + autostartHiddenWhat: "로그인하면 백그라운드에서 실행됩니다.", + notices: "알림", + noticeSystem: "시스템 알림", + noticeApp: "앱 내에서만", + noticeOff: "끄기", + }, + es: { + language: "Idioma", + languageSystem: (name: string) => `Seguir al sistema (${name})`, + appearance: "Apariencia", + system: "Sistema", + light: "Claro", + dark: "Oscuro", + systemNow: (name: string) => `El sistema está en modo ${name.toLowerCase()}.`, + zoom: "Tamaño de la interfaz", + zoomKeys: (bigger: string, smaller: string, reset: string) => `Pulsa ${bigger} para ampliar, ${smaller} para reducir o ${reset} para volver al 100%.`, + hotkey: "Atajo global", + hotkeyWhat: "Abre la ventana principal desde cualquier aplicación. Púlsalo de nuevo cuando la ventana esté al frente para cerrarla.", + hotkeyUnsupported: "Este entorno de escritorio no admite atajos globales.", + hotkeyTaken: "Otra aplicación ya usa este atajo. Elige otro.", + hotkeyNone: "Sin configurar", + hotkeyPress: "Pulsa un atajo", + hotkeyOff: "Desactivar", + hotkeyRestore: "Restaurar valor predeterminado", + hotkeyNeedModifier: `El atajo debe incluir Ctrl, Alt o ${isWindows ? "Ganar" : isLinux ? "Super" : "⌘"}.`, + hotkeyInApp: (combo: string) => `La aplicación ya usa ${combo}. Elige otro atajo.`, + menubar: "Barra de menús", + menubarWhat: "Muestra el uso de tokens y el coste de hoy.", + menubarFull: "Icono y cifras", + menubarIcon: "Solo icono", + menubarNumbers: "Solo cifras", + menubarHidden: "Oculto", + menubarHiddenWhat: "Para mostrar la ventana principal, vuelve a abrir ThinkWatch Lite desde Finder o Spotlight.", + menubarHiddenWhatHotkey: (combo: string) => `Para mostrar la ventana principal, pulsa ${combo} o vuelve a abrir ThinkWatch Lite desde Finder o Spotlight.`, + autostart: "Abrir al iniciar sesión", + autostartWhat: isWindows + ? "Al iniciar sesión, solo aparece el icono en el área de notificación." + : isLinux + ? "Al iniciar sesión, solo aparece el icono en la bandeja del sistema." + : "Al iniciar sesión, solo aparece el icono en la barra de menús.", + autostartHiddenWhat: "La aplicación se ejecuta en segundo plano al iniciar sesión.", + notices: "Avisos", + noticeSystem: "Notificaciones del sistema", + noticeApp: "Solo en la aplicación", + noticeOff: "Desactivado", + }, + }, ); diff --git a/src/settings/GeneralSection.tsx b/src/settings/GeneralSection.tsx index 35ec21e2..b9fc8c22 100644 --- a/src/settings/GeneralSection.tsx +++ b/src/settings/GeneralSection.tsx @@ -10,7 +10,7 @@ import { resetHints, useAnyDismissed } from "@/guide/hints"; import { resetIgnored, useAnyIgnored } from "@/ignore"; import { invalidate, useResource } from "@/lib/resource"; import { useTauriEvent } from "@/lib/tauriEvent"; -import { LANG_NAMES, setLang, useText, type Lang } from "@/i18n"; +import { LANG_NAMES, LANGUAGES, isLang, setLang, useText, type Lang } from "@/i18n"; import { isMac } from "@/platform"; import { errorText } from "@/i18n/core.i18n"; import { COMBOS, comboText, hotkeyCombo, isInAppCombo, Keys } from "@/palette/keys"; @@ -62,8 +62,7 @@ export function GeneralSection() { } /** - * 语言。**跟随系统是一个选项,不是一个开关**:只有两种语言,三个选项放进一个 - * 下拉就说完了;括号里写出系统现在是哪种,选之前就知道会得到什么。 + * 选择界面语言,或跟随括号里显示的系统语言。 */ function LanguageRow() { const t = useText(generalText); @@ -80,24 +79,22 @@ function LanguageRow() { + {(v) => ( { - const x = nextValue; - const setting: Lang | null = x === "zh" || x === "en" ? x : null; + const setting = isLang(nextValue) ? nextValue : null; void set({ ...v, setting, current: setting ?? v.system }); }} > {t.languageSystem(LANG_NAMES[v.system])} - {LANG_NAMES.zh} - {LANG_NAMES.en} + {LANGUAGES.map((lang) => {LANG_NAMES[lang]})} )} diff --git a/src/settings/ListenSection.i18n.ts b/src/settings/ListenSection.i18n.ts index f129bd3f..5aa3cd67 100644 --- a/src/settings/ListenSection.i18n.ts +++ b/src/settings/ListenSection.i18n.ts @@ -75,4 +75,126 @@ export const listenText = messages( staleTitle: "The listen settings have not taken effect", staleBody: (why: string, addr: string) => `${why} The gateway is still listening on ${addr}.`, }, + { + "zh-Hant": { + title: "閘道器監聽", + additional: "其他監聽地址", + additionalHint: "與主網絡卡共用埠和放行網段;切換為僅本機會一併關閉。", + wslImpactTitle: "部分 WSL 用戶端將無法連線", + wslImpactBody: (names: string) => `此更改會影響 ${names}。接管記錄和用戶端配置會保留,應用不會自動恢復監聽。`, + saveAnyway: "確認更改", + current: "當前地址", + notListening: "未在監聽", + reachable: (addrs: string) => `其他裝置使用 ${addrs} 連線。`, + scope: "訪問範圍", + local: "僅本機", + localWhat: "只有本機上的程式可以連線。", + lan: "區域網", + lanWhat: "本機和所選網絡卡所在網路中的裝置可以連線。", + all: "所有網絡卡", + allWhat: "所有網絡卡所在網路中的裝置均可連線,包括公網和 VPN。", + firewall: "本機防火牆(如 firewalld、ufw)可能攔截這個埠的入站連線。", + nic: "網絡卡", + nicMissing: (name: string) => `${name}(當前未找到)`, + noNic: "未找到可用的網絡卡,請檢查網線或 Wi-Fi 連線。", + port: "埠", + badPort: "埠須為 1 到 65535 之間的整數。", + allowlist: "放行網段", + saveFailed: "未能儲存", + staleTitle: "監聽設定未生效", + staleBody: (why: string, addr: string) => `${why}閘道器仍在 ${addr} 上監聽。`, + }, + ja: { + title: "ゲートウェイのリッスン設定", + additional: "追加のリッスンアドレス", + additionalHint: "ポートと許可するアドレス範囲を共有します。「この端末のみ」を選ぶと追加のリッスンも停止します。", + remove: "削除", + wslImpactTitle: "一部の WSL クライアントが接続できなくなります", + wslImpactBody: (names: string) => `${names} に影響します。接続履歴とクライアント設定は保持されます。アプリはリッスンを自動で再開しません。`, + cancel: "キャンセル", + saveAnyway: "変更を適用", + current: "現在のアドレス", + notListening: "リッスンしていません", + reachable: (addrs: string) => `ほかの端末からは ${addrs} に接続します。`, + sep: "、", + scope: "接続を許可する範囲", + local: "この端末のみ", + localWhat: "この端末のプログラムだけが接続できます。", + lan: "ローカルネットワーク", + lanWhat: "この端末と、選択したインターフェイスと同じネットワークの端末が接続できます。", + all: "すべてのインターフェイス", + allWhat: "インターネットや VPN を含む、すべてのインターフェイスのネットワークから接続できます。", + firewall: "この端末のファイアウォール(firewalld、ufw など)が、このポートへの着信接続をブロックする場合があります。", + nic: "インターフェイス", + nicOption: (name: string, addr: string) => `${name} ${addr}`, + nicMissing: (name: string) => `${name}(現在見つかりません)`, + noNic: "利用できるインターフェイスがありません。ケーブルまたは Wi-Fi を確認してください。", + port: "ポート", + badPort: "ポートは 1〜65535 の整数で指定してください。", + allowlist: "許可するアドレス範囲", + saveFailed: "保存できませんでした", + staleTitle: "リッスン設定が適用されていません", + staleBody: (why: string, addr: string) => `${why} ゲートウェイは引き続き ${addr} でリッスンしています。`, + }, + ko: { + remove: "제거", + cancel: "취소", + current: "주소", + notListening: "수신 대기 중 아님", + lan: "로컬 네트워크", + all: "모든 네트워크 인터페이스", + port: "포트", + title: "게이트웨이 수신 설정", + additional: "추가 수신 주소", + additionalHint: "포트와 허용 범위를 공유합니다. 이 컴퓨터만 허용하면 추가 주소의 수신도 중지합니다.", + wslImpactTitle: "일부 WSL 클라이언트의 연결이 끊깁니다", + wslImpactBody: (names: string) => `${names}에 영향을 줍니다. 연결 기록과 클라이언트 설정은 유지됩니다. 앱은 수신을 자동으로 다시 시작하지 않습니다.`, + saveAnyway: "변경 사항 적용", + reachable: (addrs: string) => `다른 장치에서는 ${addrs}에 연결하세요.`, + scope: "연결 허용 범위", + local: "이 컴퓨터만", + localWhat: "이 컴퓨터의 프로그램만 연결할 수 있습니다.", + lanWhat: "이 컴퓨터와 선택한 네트워크 인터페이스의 네트워크에 있는 장치에서 연결할 수 있습니다.", + allWhat: "인터넷과 VPN을 포함한 모든 네트워크 인터페이스에서 연결할 수 있습니다.", + firewall: " firewalld, ufw 등 이 컴퓨터의 방화벽이 이 포트로 들어오는 연결을 차단할 수 있습니다.", + nic: "네트워크 인터페이스", + nicMissing: (name: string) => `${name}(현재 찾을 수 없음)`, + noNic: "사용 가능한 네트워크 인터페이스가 없습니다. 케이블 또는 Wi-Fi 연결을 확인하세요.", + badPort: "포트는 1~65535 사이의 정수여야 합니다.", + allowlist: "허용 주소 범위", + saveFailed: "저장하지 못했습니다", + staleTitle: "수신 설정이 적용되지 않았습니다", + staleBody: (why: string, addr: string) => `${why} 게이트웨이는 계속 ${addr}에서 연결을 기다립니다.`, + }, + es: { + title: "Escuchar", + additional: "Direcciones adicionales de escucha", + additionalHint: "Utiliza el mismo puerto y rangos permitidos. Seleccionar Esta máquina también cierra a estos oyentes.", + remove: "Quitar", + wslImpactTitle: "Algunos clientes de WSL perderán conectividad", + wslImpactBody: (names: string) => `Este cambio afecta a ${names}. Se conservarán los registros de adopción y la configuración del cliente. La aplicación no reabrirá los oyentes automáticamente.`, + cancel: "Cancelar", + saveAnyway: "Aplicar cambio", + current: "Dirección", + notListening: "Sin escucha", + reachable: (addrs: string) => `Otros dispositivos se conectan a ${addrs}.`, + scope: "Alcanzado desde", + local: "Esta máquina", + localWhat: "Sólo los programas en esta computadora pueden conectarse.", + lan: "Red local", + lanWhat: "Esta computadora y dispositivos en la red de la interfaz seleccionada pueden conectarse.", + all: "Todas las interfaces", + allWhat: "Los dispositivos de la red de cualquier interfaz pueden conectarse, incluyendo Internet y una VPN.", + firewall: " Un firewall en esta computadora, como cortafuegos o ufw, puede bloquear las conexiones entrantes a este puerto.", + nic: "Interfaz", + nicMissing: (name: string) => `${name} (no se encuentra ahora mismo)`, + noNic: "No hay interfaz disponible. Compruebe el cable o la conexión Wi-Fi.", + port: "Puerto", + badPort: "El puerto es un número entero de 1 a 65535.", + allowlist: "Gamas permitidas", + saveFailed: "No guardado", + staleTitle: "La configuración de escucha no ha tenido efecto", + staleBody: (why: string, addr: string) => `${why} La puerta sigue escuchando ${addr}.`, + }, + }, ); diff --git a/src/settings/RangeList.i18n.ts b/src/settings/RangeList.i18n.ts index 33c585e4..af0cd1a9 100644 --- a/src/settings/RangeList.i18n.ts +++ b/src/settings/RangeList.i18n.ts @@ -24,4 +24,40 @@ export const rangeListText = messages( restore: "Restore defaults", bad: (v: string) => `“${v}” is not a range or an address; it is written as 192.168.1.0/24 or 192.168.1.5.`, }, + { + "zh-Hant": { + enterToAdd: "回車新增", + single: "單個地址", + remove: (c: string) => `刪除 ${c}`, + removeShort: "刪除", + what: "可新增多個網段或單個地址。只有這些來源的裝置可以連線,本機始終可以連線。", + empty: "未放行任何網段,除本機外的裝置都無法連線。", + restore: "恢復預設", + bad: (v: string) => `「${v}」不是有效的網段或地址,寫法如 192.168.1.0/24 或 192.168.1.5。`, + }, + ja: { + placeholder: "例:192.168.1.0/24", + enterToAdd: "Enter で追加", + single: "単一アドレス", + remove: (c: string) => `${c} を削除`, + removeShort: "削除", + what: "接続を許可するネットワーク範囲またはアドレスを追加できます。この端末からは常に接続できます。", + empty: "許可された範囲がないため、この端末からのみ接続できます。", + restore: "初期設定に戻す", + bad: (v: string) => `「${v}」は無効です。192.168.1.0/24 や 192.168.1.5 の形式で入力してください。`, + }, + ko: { + removeShort: "제거", + }, + es: { + enterToAdd: "Introduzca para añadir", + single: "dirección única", + remove: (c: string) => `Eliminar ${c}`, + removeShort: "Quitar", + what: "Añadir tantos rangos o direcciones individuales como sea necesario. Sólo los dispositivos de estos pueden conectarse; este equipo siempre puede.", + empty: "No se permite ningún rango, por lo que sólo este equipo puede conectarse.", + restore: "Restaurar valores predeterminados", + bad: (v: string) => `“${v}” no es un rango ni una dirección; está escrito como 192.168.1.0/24 o 192.168.1.5.`, + }, + }, ); diff --git a/src/settings/RetentionSection.i18n.ts b/src/settings/RetentionSection.i18n.ts index 897fccd3..795d024f 100644 --- a/src/settings/RetentionSection.i18n.ts +++ b/src/settings/RetentionSection.i18n.ts @@ -32,4 +32,65 @@ export const retentionText = messages( badGb: "A positive number with at most one decimal place.", saveFailed: "Not saved", }, + { + "zh-Hant": { + title: "日誌保留", + intro: "封包和請求記錄分別設定保留期限。封包佔用空間最多,記錄很小,可以保留更久。", + bodyDays: "封包", + bodyDaysWhat: "超過期限的封包被刪除,請求詳情中的「內容」隨之為空。", + rowDays: "記錄", + rowDaysWhat: "請求的時刻、模型、用量和費用,用於統計較長時間段的費用。", + bodyMax: "封包上限", + bodyMaxWhat: "超出後從最早的一天開始刪除。", + usage: "封包當前佔用", + bad: "須為正整數。", + badGb: "須為正數,最多一位小數。", + saveFailed: "未能儲存", + }, + ja: { + title: "ログの保持", + intro: "リクエストの本文と記録には個別の保持期間を設定できます。本文は容量が大きく、記録は容量が小さいため長く保持できます。", + bodyDays: "本文", + bodyDaysWhat: "保持期間を過ぎた本文は削除され、リクエストの詳細の「内容」タブには表示されなくなります。", + rowDays: "記録", + rowDaysWhat: "リクエストの時刻、モデル、使用量、費用を保持し、長期間の集計に使用します。", + bodyMax: "本文の容量上限", + bodyMaxWhat: "上限を超えると古い日付から削除されます。", + usage: "本文の使用容量", + days: "日", + bad: "正の整数を入力してください。", + badGb: "小数第 1 位までの正の数を入力してください。", + saveFailed: "保存できませんでした", + }, + es: { + title: "Retención de troncos", + intro: "Las cargas útiles y los registros de solicitud expiran por separado.Las cargas útiles toman la mayor parte del espacio; los registros son pequeños y se pueden guardar más tiempo.", + bodyDays: "Cargas útiles", + bodyDaysWhat: "Las cargas útiles pasadas esta edad se eliminan, y la pestaña Contenido de una solicitud está vacía.", + rowDays: "Actas", + rowDaysWhat: "El tiempo, el modelo, el uso y el costo de cada solicitud, para totales durante períodos más largos.", + bodyMax: "Límite de carga útil", + bodyMaxWhat: "Sobre ella, los días más viejos van primero.", + usage: "Almacenamiento de carga útil en uso", + days: "días", + bad: "Un número entero positivo.", + badGb: "Un número positivo con como máximo un decimal.", + saveFailed: "No guardado", + }, + ko: { + title: "로그 보존", + intro: "본문과 요청 기록의 보존 기간을 각각 설정합니다. 본문은 공간을 많이 차지하며, 용량이 작은 기록은 더 오래 보관할 수 있습니다.", + bodyDays: "본문", + bodyDaysWhat: "보존 기간이 지난 본문은 삭제되어 요청 세부 정보의 내용 탭에 표시되지 않습니다.", + rowDays: "기록", + rowDaysWhat: "각 요청의 시각, 모델, 사용량, 비용을 보관하여 장기간 통계에 사용합니다.", + bodyMax: "본문 용량 한도", + bodyMaxWhat: "한도를 넘으면 가장 오래된 날짜부터 삭제합니다.", + usage: "본문 저장 공간 사용량", + days: "일", + bad: "양의 정수를 입력하세요.", + badGb: "소수점 첫째 자리까지의 양수를 입력하세요.", + saveFailed: "저장하지 못했습니다", + }, + }, ); diff --git a/src/settings/SettingsPage.i18n.tsx b/src/settings/SettingsPage.i18n.tsx index 79ad2209..1689fb04 100644 --- a/src/settings/SettingsPage.i18n.tsx +++ b/src/settings/SettingsPage.i18n.tsx @@ -218,5 +218,241 @@ export const settingsText = messages( uninstallFailed: "The uninstall did not finish", uninstalledRow: "The uninstall is complete.", }, + { + "zh-Hant": { + notListening: "未在監聽", + scopeLocal: "僅本機", + scopeLan: "區域網", + scopeAll: "所有網絡卡", + here: (isMac ? "這臺 Mac" : "這臺電腦"), + about: "關於", + checking: "正在檢查更新", + checkFailed: "檢查更新失敗", + checkNow: "檢查更新", + devBuild: "開發構建", + autoCheck: "自動檢查新版本", + dataDir: "資料目錄", + coreBin: "core 二進位制", + diagnostics: "診斷包", + diagnosticsBody: (tip: Wrap) => (<> + 包含版本、上游、熔斷狀態、近期失敗記錄與脫敏後的配置檔案。{tip("不含請求與回應正文")}。 + ), + diagnosticsTip: "不包含請求本文與回應本文,其中可能含有使用者貼上的內容。", + diagnosticsOffline: "連線到 core 後可生成診斷包。", + review: (em: Wrap) => <>其中的金鑰與地址已脫敏,{em("提交前請自行核對")}。, + uninstall: "解除安裝", + uninstallTitle: "完全解除安裝", + uninstallIntro: (em: Wrap, portable: boolean) => { + const skipped = ((portable: boolean) => isMac + ? "直接將應用移到廢紙簍不會執行這些操作" + : portable + ? "直接刪除資料夾不會執行這些操作" + : isWindows + ? null + : "直接刪除應用不會執行這些操作")(portable); + return skipped ? (<> + 還原所有已接管的用戶端,並取消開機啟動。 + {em(skipped)},已接管的用戶端將指向一個無人監聽的埠。 + ) : (<>還原所有已接管的用戶端,並取消開機啟動。透過系統解除安裝 ThinkWatch Lite 時也會執行這些操作。); + }, + uninstallAction: "解除安裝…", + willDo: (portable: boolean) => `將執行以下操作。${((portable: boolean) => isMac + ? "完成後即可將應用移到廢紙簍。" + : portable + ? "完成後即可刪除整個資料夾。" + : isWindows + ? "完成後即可解除安裝或刪除應用。" + : "完成後即可刪除應用。")(portable)}`, + restoreClients: "還原已接管的用戶端", + restoreNone: "當前無已接管的用戶端", + stopAutostart: "取消開機啟動", + wslconfigKept: "WSL 的網路模式不會改回", + wslconfigCreated: (path: string) => `${path} 是改為 mirrored 網路模式時新建的,解除安裝後保留。`, + wslconfigBackup: (path: string, backup: string) => `${path} 保持 mirrored 網路模式;修改前的備份保留在 ${backup}。`, + wslconfigBackupDropped: (path: string) => `${path} 保持 mirrored 網路模式;修改前的備份隨資料目錄一併刪除。`, + dropData: "同時刪除資料目錄", + dropDataWhat: "包括請求歷史、費用記錄與配置備份,刪除後無法恢復。", + confirmUninstall: "解除安裝", + uninstalled: "解除安裝完成", + uninstalledWithFailures: (n: number) => `解除安裝已結束,${n} 項未成功`, + uninstallFailed: "未能完成解除安裝", + uninstalledRow: "已完成解除安裝。", + }, + ja: { + notListening: "リッスンしていません", + scopeLocal: "この端末のみ", + scopeLan: "ローカルネットワーク", + scopeAll: "すべてのインターフェイス", + versionIs: (v: string) => `バージョン ${v}`, + available: "利用可能", + here: isMac ? "この Mac" : "この端末", + about: "アプリについて", + updates: "更新", + appName: "ThinkWatch Lite", + latest: "最新バージョンです", + newer: (v: string) => `バージョン ${v} を利用できます`, + checking: "更新を確認しています", + checkFailed: "更新の確認に失敗しました", + checkNow: "更新を確認", + updateTo: (v: string) => `${v} に更新…`, + homebrew: "Homebrew", + devBuild: "開発ビルド", + autoCheck: "更新を自動で確認", + dataDir: "データディレクトリ", + coreBin: "core バイナリ", + diagnostics: "診断情報", + diagnosticsBody: (tip: Wrap) => <> + バージョン、アップストリーム、サーキットブレーカーの状態、最近の失敗、機密情報を伏せた設定ファイルを含みます。{tip("リクエストとレスポンスの本文は含みません")}。 + , + diagnosticsTip: "リクエストとレスポンスの本文には、ユーザーが貼り付けた内容が含まれる可能性があるため、収集対象から除外しています。", + generate: "作成", + generated: "作成しました", + diagnosticsOffline: "core に接続すると診断情報を作成できます。", + review: (em: Wrap) => <>キーとアドレスは伏せています。{em("共有前に内容を確認してください")}。, + uninstall: "アンインストール", + uninstallTitle: "完全にアンインストール", + uninstallIntro: (em: Wrap, portable: boolean) => { + const skipped = isMac ? "アプリを直接ゴミ箱に移動する" : portable ? "フォルダーを直接削除する" : !isWindows ? "アプリを直接削除する" : null; + return skipped ? <> + 接続済みクライアントの設定を復元し、ログイン時の起動を無効にします。 + {em(skipped)}だけではクライアントの設定が復元されず、接続できなくなります。 + : <>接続済みクライアントの設定を復元し、ログイン時の起動を無効にします。システムから ThinkWatch Lite をアンインストールしても同じ処理が行われます。; + }, + uninstallAction: "アンインストール…", + willDo: (portable: boolean) => `以下の操作を行います。完了後は${isMac ? "アプリをゴミ箱に移動" : portable ? "フォルダーごと削除" : isWindows ? "アプリをアンインストールまたは削除" : "アプリを削除"}できます。`, + restoreClients: "接続済みクライアントの設定を復元", + restoreNone: "接続済みのクライアントはありません", + sep: "、", + wslClient: (client: string, distro: string) => `${client} (WSL · ${distro})`, + stopAutostart: "ログイン時の起動を無効にする", + wslconfigKept: "WSL のネットワークモードを維持", + wslconfigCreated: (path: string) => `ミラーモードへの切り替え時に作成した ${path} は保持されます。`, + wslconfigBackup: (path: string, backup: string) => `${path} はミラーモードのままです。変更前のバックアップは ${backup} に保存されます。`, + wslconfigBackupDropped: (path: string) => `${path} はミラーモードのままです。変更前のバックアップはデータディレクトリとともに削除されます。`, + dropData: "データディレクトリも削除", + dropDataWhat: "リクエスト履歴、費用の記録、設定のバックアップが削除されます。この操作は元に戻せません。", + confirmUninstall: "アンインストール", + uninstalled: "アンインストール完了", + uninstalledWithFailures: (n: number) => `アンインストール処理が終了しました(失敗 ${n} 件)`, + stepFailed: "失敗", + uninstallFailed: "アンインストールを完了できませんでした", + uninstalledRow: "アンインストールが完了しました。", + }, + ko: { + notListening: "수신 대기 중 아님", + scopeLocal: "이 컴퓨터만", + scopeLan: "로컬 네트워크", + scopeAll: "모든 네트워크 인터페이스", + versionIs: (v: string) => `버전 ${v}`, + here: (isMac ? "이 Mac" : "이 컴퓨터"), + about: "정보", + updates: "업데이트", + latest: "최신 버전", + newer: (v: string) => `버전 ${v}을(를) 사용할 수 있습니다`, + checking: "업데이트 확인 중", + checkFailed: "업데이트 확인 실패", + checkNow: "업데이트 확인", + updateTo: (v: string) => `${v}(으)로 업데이트…`, + devBuild: "개발 빌드", + autoCheck: "업데이트 자동 확인", + dataDir: "데이터 디렉터리", + coreBin: "core 실행 파일", + diagnostics: "진단 패키지", + diagnosticsBody: (tip: Wrap) => (<> + Contains the version, upstreams, circuit breaker states, recent failures and the redacted config file.{" "} + {tip("요청 및 응답 본문 제외")}. + ), + diagnosticsTip: "사용자가 붙여넣은 내용이 들어 있을 수 있어 요청 및 응답 본문은 포함되지 않습니다.", + generate: "생성", + generated: "생성됨", + diagnosticsOffline: "core에 연결하면 진단 패키지를 만들 수 있습니다.", + review: (em: Wrap) => <>Keys and addresses in it are redacted; {em("공유하기 전에 내용을 확인하세요")}., + uninstall: "제거", + uninstallTitle: "완전히 제거", + uninstallAction: "제거…", + restoreClients: "연결된 클라이언트 복원", + restoreNone: "현재 연결된 클라이언트가 없습니다.", + stopAutostart: "로그인 시 실행 끄기", + dropData: "데이터 디렉터리도 삭제", + dropDataWhat: "요청 기록, 비용 기록, 설정 백업을 삭제합니다. 이 작업은 되돌릴 수 없습니다.", + confirmUninstall: "제거", + uninstalled: "제거 완료", + stepFailed: "실패", + uninstallFailed: "제거를 완료하지 못했습니다.", + uninstalledRow: "제거가 완료되었습니다.", + }, + es: { + notListening: "Sin escucha", + scopeLocal: "Solo este equipo", + scopeLan: "Red local", + scopeAll: "Todas las interfaces", + versionIs: (v: string) => `Versión ${v}`, + available: "disponible", + here: (isMac ? "Este Mac" : "Este equipo"), + about: "Acerca de", + updates: "Actualizaciones", + latest: "Al día", + newer: (v: string) => `Hay una nueva versión disponible (${v})`, + checking: "Buscando actualizaciones", + checkFailed: "Error al buscar actualizaciones", + checkNow: "Buscar actualizaciones", + updateTo: (v: string) => `Actualizar a ${v}…`, + devBuild: "Compilación de desarrollo", + autoCheck: "Buscar actualizaciones automáticamente", + dataDir: "Directorio de datos", + coreBin: "Ejecutable de core", + diagnostics: "Paquete de diagnóstico", + diagnosticsBody: (tip: Wrap) => (<> + Contiene la versión, del proveedor, estados de disyuntor, fallos recientes y el archivo de configuraciónuración redactado.{" "} + {tip("Sin cuerpos de solicitudes ni respuestas")}. + ), + diagnosticsTip: "Se excluyen los cuerpos de las solicitudes y respuestas porque pueden incluir contenido pegado por el usuario.", + generate: "Generar", + generated: "Generado", + diagnosticsOffline: "Conéctate a un core para generar un paquete de diagnóstico.", + review: (em: Wrap) => <>Se redactan las claves y direcciones; {em("revísalo antes de compartirlo")}., + uninstall: "Desinstalar", + uninstallTitle: "Desinstalación completa", + uninstallIntro: (em: Wrap, portable: boolean) => { + const skipped = ((portable: boolean) => isMac + ? "Mover la aplicación directamente a la papelera no hace ninguna de las dos cosas" + : portable + ? "Eliminar la carpeta directamente no hace ninguna de las dos cosas" + : isWindows + ? null + : "Eliminar la aplicación directamente no hace ninguno de los dos")(portable); + return skipped ? (<> + Restaura cada cliente conectado y desactiva el lanzamiento en el inicio de sesión. {em(skipped)}, leaving connected clients + pointed at a port where nothing is listening. + ) : (<> + Restores every connected client and turns off launch at login. Uninstalling ThinkWatch Lite through the system + does the same. + ); + }, + uninstallAction: "Desinstalar…", + willDo: (portable: boolean) => `Lo siguiente está hecho. ${((portable: boolean) => isMac + ? "Una vez que termina, la aplicación se puede mover a la Papelera." + : portable + ? "Una vez que termina, se puede eliminar toda la carpeta." + : isWindows + ? "Una vez que termina, la aplicación puede ser desinstalada o eliminada." + : "Una vez que termina, la aplicación se puede eliminar.")(portable)}`, + restoreClients: "Restaurar los clientes conectados", + restoreNone: "No hay clientes conectados.", + stopAutostart: "Desactivar la apertura al iniciar sesión", + wslconfigKept: "La red WSL no se cambia de nuevo", + wslconfigCreated: (path: string) => `${path} fue creado al cambiar a redes reflejadas y se mantiene.`, + wslconfigBackup: (path: string, backup: string) => `${path} se mantiene en red reflejada; la copia de seguridad de antes de que el cambio se mantenga en ${backup}.`, + wslconfigBackupDropped: (path: string) => `${path} se mantiene en la red reflejada; la copia de seguridad de antes de que el cambio se elimina con el directorio de datos.`, + dropData: "Eliminar también el directorio de datos", + dropDataWhat: "Se eliminarán el historial de solicitudes, los registros de costes y las copias de configuración. Esta acción es irreversible.", + confirmUninstall: "Desinstalar", + uninstalled: "Desinstalación completa", + uninstalledWithFailures: (n: number) => (n === 1 ? "Desinstalar terminado; 1 paso ha fallado" : `Desinstalar terminado; ${n} los pasos fallaron`), + stepFailed: "Error", + uninstallFailed: "No se completó la desinstalación.", + uninstalledRow: "La desinstalación ha terminado.", + }, + }, ); diff --git a/src/settings/SyncBackupSection.i18n.ts b/src/settings/SyncBackupSection.i18n.ts index f7b72f39..a5b765c5 100644 --- a/src/settings/SyncBackupSection.i18n.ts +++ b/src/settings/SyncBackupSection.i18n.ts @@ -7,4 +7,15 @@ export const syncBackupText = messages( { title: "Sync and backup", }, + { + "zh-Hant": { + title: "同步與備份", + }, + ja: { + title: "同期とバックアップ", + }, + es: { + title: "Sincronización y respaldo", + }, + }, ); diff --git a/src/settings/kit.i18n.ts b/src/settings/kit.i18n.ts index 2dd598ab..9f93ef3d 100644 --- a/src/settings/kit.i18n.ts +++ b/src/settings/kit.i18n.ts @@ -21,4 +21,42 @@ export const kitText = messages( loadFailed: "Could not load", configFailed: "The gateway configuration could not be read", }, + { + "zh-Hant": { + index: "設定目錄", + unsaved: "有未儲存的更改", + saved: "已儲存", + discard: "放棄更改", + offline: "連線到 core 後可修改此項。", + loadFailed: "無法讀取", + configFailed: "無法讀取閘道器配置", + }, + ja: { + index: "設定項目", + unsaved: "未保存の変更があります", + saved: "保存しました", + discard: "変更を破棄", + offline: "core に接続すると設定できます。", + loadFailed: "読み込めませんでした", + configFailed: "ゲートウェイの設定を読み込めませんでした", + }, + ko: { + index: "설정 항목", + unsaved: "저장하지 않은 변경 사항", + saved: "저장됨", + discard: "변경 사항 취소", + offline: "core에 연결하면 사용할 수 있습니다.", + loadFailed: "불러올 수 없음", + configFailed: "게이트웨이 설정을 읽을 수 없습니다.", + }, + es: { + index: "Secciones de configuración", + unsaved: "Cambios sin guardar", + saved: "Guardado", + discard: "Descartar cambios", + offline: "Disponible al conectarse a un core.", + loadFailed: "No se pudo cargar", + configFailed: "No se pudo leer la configuración de la puerta de enlace.", + }, + }, ); diff --git a/src/sync/ConflictDialog.i18n.ts b/src/sync/ConflictDialog.i18n.ts index 015fe4d5..ab0cc787 100644 --- a/src/sync/ConflictDialog.i18n.ts +++ b/src/sync/ConflictDialog.i18n.ts @@ -53,4 +53,60 @@ export const conflictText = messages( loadFailed: "The conflicts could not be read", failed: "The conflicts could not be resolved", }, + { + "zh-Hant": { + title: "同步衝突", + desc: "以下物件在本機與其他裝置上被修改為不同內容。未處理前,本機保留當前內容。點選物件名稱檢視差異。", + showDiff: "檢視差異", + hideDiff: "收起差異", + deleted: "已刪除", + object: "物件", + here: "本機", + other: "其他裝置", + take: "採用", + deletedAt: (when: string) => `${when} 刪除`, + both: "兩者都保留", + keyInUse: "本機用戶端正在使用該閘道器金鑰,未刪除。", + invalid: "合併後的配置未透過校驗。", + bothName: (name: string) => `另一方內容的名稱(原名「${name}」)`, + bothNameHint: "本機內容保留原名稱,另一方的內容以此名稱新增。", + bothEmpty: "填寫名稱。", + bothSame: "名稱須與原名稱不同。", + later: "稍後處理", + apply: "應用", + left: (n: number) => `尚有 ${n} 項未選擇。`, + none: "沒有待處理的衝突。", + loadFailed: "未能讀取衝突", + failed: "未能處理衝突", + }, + ko: { + later: "나중에", + }, + es: { + title: "Conflictos de sincronización", + desc: "Estos elementos se cambiaron de manera diferente en este dispositivo y en otro. Hasta que se resuelva, este dispositivo mantiene su propia versión. Haga clic en un elemento para ver las diferencias.", + showDiff: "Mostrar diferencias", + hideDiff: "Ocultar diferencias", + deleted: "Suprimido", + object: "Tema", + here: "Este dispositivo", + other: "Otro dispositivo", + take: "Uso", + changedAt: (when: string) => `Cambiado ${when}`, + deletedAt: (when: string) => `Suprimido ${when}`, + both: "Conserve ambos", + keyInUse: "Un cliente en este dispositivo utiliza esta clave de puerta de enlace; no se ha eliminado.", + invalid: "La configuración fusionada no pasó la validación.", + bothName: (name: string) => `Nombre de la otra versión (era “${name}”)`, + bothNameHint: "La versión de este dispositivo mantiene el nombre; el otro se añade bajo este nombre.", + bothEmpty: "Introduzca un nombre.", + bothSame: "El nombre debe diferir del original.", + later: "Más tarde", + apply: "Aplicar", + left: (n: number) => (n === 1 ? "1 elemento no tiene opción todavía." : `${n} Los artículos no tienen opción todavía.`), + none: "Ningún conflicto está esperando.", + loadFailed: "Los conflictos no pueden leerse", + failed: "Los conflictos no pudieron resolverse", + }, + }, ); diff --git a/src/sync/JoinWizard.i18n.ts b/src/sync/JoinWizard.i18n.ts index 522c4362..2865a960 100644 --- a/src/sync/JoinWizard.i18n.ts +++ b/src/sync/JoinWizard.i18n.ts @@ -81,4 +81,68 @@ export const joinWizardText = messages( unresolved: (n: number) => (n === 1 ? "1 conflict has no choice yet." : `${n} conflicts have no choice yet.`), failed: "Sync could not be turned on", }, + { + "zh-Hant": { + title: "開啟同步", + steps: { location: "同步位置", encryption: "加密", merge: "合併" }, + locationDesc: "多臺裝置共用一份配置,並在同步位置儲存最新與上一個版本。", + test: "測試連線", + testing: "正在連線同步位置", + emptyOk: "可以讀寫。同步位置為空,將以本機配置開始同步。", + existingOk: (n: number, encrypted: boolean) => `可以讀寫。同步位置已有同步資料(${n > 0 ? `${n} 臺裝置,` : ""}${encrypted ? "已加密" : "未加密"})。`, + notWritable: "同步位置不可寫入", + testFailed: "無法連線同步位置", + encryptDesc: "選擇是否加密同步內容。同一同步位置上的所有裝置採用同一設定。", + encryptHint: "其他裝置加入時輸入同一口令。口令遺失且沒有裝置仍在同步時,同步資料無法解密。", + plainTitle: "同步內容不加密", + plainBody: "同步位置的服務商可讀取配置與金鑰,對同步位置有寫入許可權的任何人也可以改動配置。經同步新增或指令碼有變化的外掛在本裝置為停用狀態,須在本裝置啟用。", + joinDesc: "同步位置已有同步資料,以同步口令加密。輸入其他裝置上設定的同步口令。", + wrongPassphrase: "同步口令不正確。", + devices: (list: string) => `已在同步的裝置:${list}`, + enterPassphrase: "輸入同步口令。", + mergeDesc: "本機已有配置。以匯入的規則合併同步資料,衝突項逐項選擇處理方式。", + mode: { merge: "合併", use_remote: "使用同步資料替換本機配置" }, + replaceNote: "本機當前配置保留在備份中。本機用戶端正在使用的閘道器金鑰併入同步資料。", + noDifferences: "同步資料與本機配置一致。", + enable: "開啟同步", + unresolved: (n: number) => `尚有 ${n} 項衝突未選擇處理方式。`, + failed: "未能開啟同步", + }, + ko: { + steps: { location: "위치", encryption: "Encryption", merge: "Merge" }, + test: "연결 테스트", + }, + es: { + title: "Activar sincronización", + steps: { location: "Ubicación", encryption: "Cifrado", merge: "Fusionar" }, + skipped: "No cifrado", + locationDesc: "Los dispositivos comparten una configuración; la ubicación de sincronización mantiene la última y la versión anterior.", + test: "Probar conexión", + testing: "Conexión a la ubicación de sincronización", + emptyOk: "Se puede leer y escribir. La ubicación de sincronización está vacía; la sincronización comienza desde la configuración de este dispositivo.", + existingOk: (n: number, encrypted: boolean) => `La ubicación de sincronización ya contiene datos de sincronización (${n > 0 ? `${n === 1 ? "1 dispositivo" : `${n} dispositivos`}, ` : ""}${encrypted ? "cifrada" : "no cifrado"}).`, + notWritable: "La ubicación de sincronización no se puede escribir", + testFailed: "No se puede localizar la ubicación de sincronización", + encrypt: "Cifrar con una frase", + noEncrypt: "No cifrar", + encryptDesc: "Elija si el contenido sincronizado está cifrado. Todos los dispositivos en una ubicación de sincronización utilizan la misma configuración.", + encryptHint: "Otros dispositivos introducen la misma contraseña cuando se unen. Si la contraseña se pierde y ningún dispositivo sigue sincronizando, los datos de sincronización no pueden ser descifrados.", + plainTitle: "El contenido sincronizado no está cifrado", + plainBody: "El proveedor de almacenamiento puede leer la configuración y sus claves, y cualquier persona que pueda escribir en la ubicación de sincronización puede cambiar la configuración. Plugins que llegan o cambian su script a través de sincronización permanecer fuera de este dispositivo hasta que se encienda aquí.", + joinDesc: "La ubicación de sincronización ya contiene datos de sincronización cifrados con una contraseña de sincronización. Introduzca la frase de contraseña establecida en los otros dispositivos.", + wrongPassphrase: "La frase de paso de sincronización no es correcta.", + devices: (list: string) => `Dispositivos que ya sincronizan: ${list}`, + enterPassphrase: "Introduzca la frase de paso de sincronización.", + mergeDesc: "Este dispositivo ya tiene una configuración. Los datos de sincronización se fusionan con las reglas de importación; elija qué hacer con cada conflicto.", + mode: { merge: "Fusionar", use_remote: "Reemplazar la configuración de este dispositivo con los datos de sincronización" }, + replaceNote: "La configuración actual permanece en las copias de seguridad. Las claves de pasarela utilizadas por los clientes en este dispositivo se añaden a los datos de sincronización.", + noDifferences: "Los datos de sincronización coinciden con la configuración de este dispositivo.", + back: "Atrás", + next: "Siguiente", + enable: "Activar sincronización", + join: "Sincronización de unión", + unresolved: (n: number) => (n === 1 ? "1 conflicto no tiene opción todavía." : `${n} Los conflictos no tienen opción todavía.`), + failed: "Sincronización no se pudo activar", + }, + }, ); diff --git a/src/sync/MergeRows.i18n.ts b/src/sync/MergeRows.i18n.ts index d16139a6..ceb190e9 100644 --- a/src/sync/MergeRows.i18n.ts +++ b/src/sync/MergeRows.i18n.ts @@ -48,4 +48,53 @@ export const mergeRowsText = messages( renameSame: "The new name is the same as the old one.", renameTaken: "That name is already used.", }, + { + "zh-Hant": { + counts: (n: number, c: number, s: number, e: number) => [n && `新增 ${n}`, c && `衝突 ${c}`, s && `相同 ${s}`, e && `錯誤 ${e}`].filter(Boolean).join(" · "), + all: { overwrite: "全部覆蓋", rename: "全部改名匯入", skip: "全部跳過" }, + name: "名稱", + status: "狀態", + action: "處理", + statusOf: { new: "新增", same: "相同", conflict: "衝突", error: "錯誤" }, + flag: { missing_key: "缺少金鑰", needs_login: "需要登入", plugin_disabled: "外掛停用" }, + choice: { overwrite: "覆蓋", rename: "改名匯入", skip: "跳過" }, + importIt: "匯入", + cannot: "不可匯入", + takeRemote: "採用同步資料", + defaultKey: "預設閘道器金鑰", + clientsFollow: "採用同步資料的值。本機已接管的用戶端將自動更新。", + newName: (name: string) => `「${name}」的新名稱`, + renameFlags: (flags: string) => `改名匯入後:${flags}`, + renameEmpty: "填寫新名稱。", + renameSame: "新名稱與原名稱相同。", + renameTaken: "已有同名項。", + }, + ko: { + name: "이름", + status: "상태", + }, + es: { + counts: (n: number, c: number, s: number, e: number) => [n && `${n} nuevo`, c && `${c} ${c === 1 ? "conflicto armado" : "conflictos armados"}`, s && `${s} Lo mismo`, e && `${e} ${e === 1 ? "error" : "errores"}`] + .filter(Boolean) + .join(" · "), + all: { overwrite: "Sobrescribir todo", rename: "Cambiar el nombre de todos", skip: "Omitir todo" }, + name: "Nombre", + status: "Estado", + action: "Medidas adoptadas", + statusOf: { new: "Nuevo", same: "Mismo", conflict: "Conflicto", error: "Error" }, + differs: (units: string) => `${units} Difieren`, + flag: { missing_key: "Falta la clave", needs_login: "Se requiere registro", plugin_disabled: "Complemento desactivado" }, + choice: { overwrite: "Sobrescribir", rename: "Cambiar nombre", skip: "Saltar" }, + importIt: "Importar", + cannot: "No se puede importar", + takeRemote: "Usar datos de sincronización", + defaultKey: "Tecla de puerta de enlace predeterminada", + clientsFollow: "Se utiliza el valor de los datos de sincronización. Los clientes conectados en este dispositivo se actualizan automáticamente.", + newName: (name: string) => `Nuevo nombre para “${name}”`, + renameFlags: (flags: string) => `Después de cambiar el nombre: ${flags}`, + renameEmpty: "Introduzca un nuevo nombre.", + renameSame: "El nuevo nombre es el mismo que el antiguo.", + renameTaken: "Ese nombre ya está usado.", + }, + }, ); diff --git a/src/sync/SyncPart.i18n.ts b/src/sync/SyncPart.i18n.ts index 508c4d22..8180adcc 100644 --- a/src/sync/SyncPart.i18n.ts +++ b/src/sync/SyncPart.i18n.ts @@ -96,6 +96,92 @@ export const syncPartText = messages( loadFailed: "The sync status could not be read", nowFailed: "Sync failed", }, + { + "zh-Hant": { + offDesc: "多臺裝置共用一份配置,並在同步位置儲存最新與上一個版本。", + turnOn: "開啟同步…", + status: "狀態", + state: { + idle: (when: string) => `已同步 · ${when}`, + never: "尚未同步", + syncing: "正在同步", + conflict: (n: number) => `有 ${n} 項衝突`, + unreachable: "無法連線同步位置", + auth_failed: "同步位置拒絕訪問", + locked: "同步口令已在其他裝置上更改", + too_new: "已暫停:需更新", + paused: "已暫停:安全模式", + keyring_missing: "同步金鑰不可用", + emptied: "同步位置為空", + misconfigured: "同步設定無法使用", + }, + skipped: (n: number) => `同步位置上有 ${n} 個檔案無法使用,已跳過。`, + resolve: "處理衝突…", + unlock: "輸入口令…", + plain: "不加密。同步位置的服務商可讀取配置與金鑰。", + excludedNone: "無", + pick: "選擇…", + cascade: (items: string) => `隨之不同步:${items}。`, + devices: "裝置", + lastSeen: "最後同步", + deviceState: "狀態", + thisDevice: (name: string) => `${name}(本裝置)`, + remoteCore: (name: string) => `${name}(遠端 core)`, + pausedUpdate: "已暫停:需更新", + saveFailed: "未能儲存", + loadFailed: "未能讀取同步狀態", + }, + ko: { + status: "상태", + excludedNone: "없음", + deviceState: "상태", + }, + es: { + title: "Sincronización", + offDesc: "Los dispositivos comparten una configuración; la ubicación de sincronización mantiene la última y la versión anterior.", + turnOn: "Enciende la sincronización…", + stop: "Deja de sincronizar…", + now: "Sincronizar ahora", + status: "Estado", + state: { + idle: (when: string) => `Sincronizado · ${when}`, + never: "No sincronizado todavía", + syncing: "Sincronización", + conflict: (n: number) => (n === 1 ? "1 conflicto" : `${n} conflictos`), + unreachable: "Sincronizar ubicación inalcanzable", + auth_failed: "Sincronización de la ubicación de acceso denegado", + locked: "Frase de paso cambiada en otro dispositivo", + too_new: "Pausa: actualización necesaria", + paused: "Pausa: modo seguro", + keyring_missing: "Sincronización de la tecla no disponible", + emptied: "Sincronizar la ubicación vacía", + misconfigured: "Sincronización de la configuración inutilizable", + }, + skipped: (n: number) => n === 1 + ? "1 archivo en la ubicación de sincronización no se pudo utilizar y se omitió." + : `${n} los archivos en la ubicación de sincronización no se pudieron usar y se saltaron.`, + resolve: "Resolver…", + unlock: "Introduzca la frase de paso…", + encryption: "Cifrado", + encrypted: "Cifrado con la frase de paso de sincronización", + plain: "No cifrado. El proveedor de almacenamiento puede leer la configuración y sus claves.", + changePassphrase: "Cambiar frase de paso…", + excluded: "Corrientes ascendentes no sincronizadas", + excludedNone: "Ninguno", + pick: "Elegir…", + cascade: (items: string) => `No sincronizado con ellos: ${items}.`, + devices: "Dispositivo", + lastSeen: "Última sincronización", + coreVersion: "Versión básica", + deviceState: "Estado", + thisDevice: (name: string) => `${name} (este dispositivo)`, + remoteCore: (name: string) => `${name} (núcleo remoto)`, + pausedUpdate: "Pausa: actualización necesaria", + saveFailed: "No se pudo guardar", + loadFailed: "El estado de sincronización no se pudo leer", + nowFailed: "Sincronización fallida", + }, + }, ); /** 需要处理的状态:黄色提示(都可忽略) */ @@ -152,4 +238,57 @@ export const syncNoticeText = messages( republish: "Upload this device's configuration", stop: "Stop syncing…", }, + { + "zh-Hant": { + conflictTitle: (n: number) => `同步有 ${n} 項衝突`, + conflictBody: "本機與其他裝置將同一物件修改為不同內容。處理之前,本機保留當前內容。", + resolve: "處理衝突…", + unreachableTitle: "無法連線同步位置", + unreachableBody: "恢復後自動繼續,本機的修改在恢復後上傳。", + authTitle: "同步位置拒絕訪問", + authBody: "修改同步位置的連線引數後繼續同步。", + lockedTitle: "同步口令已在其他裝置上更改", + lockedBody: "輸入新口令後繼續同步。", + unlock: "輸入口令…", + tooNewTitle: "同步已暫停", + tooNewBody: "其他裝置使用較新版本,更新 ThinkWatch Lite 後繼續同步。", + update: "檢查更新", + pausedBody: "配置恢復正常後自動繼續。", + keyringTitle: "同步位置上的同步金鑰不可用", + keyringBody: "同步金鑰缺失、被替換為較早的版本或無法讀取,同步已暫停。可重新上傳本機配置(同時恢復本裝置儲存的同步金鑰),或停止同步。", + emptiedTitle: "同步位置為空", + emptiedBody: "其他裝置可能刪除了同步資料,或同步位置已不是原來的位置,同步已暫停。可重新上傳本機配置,或停止同步。", + misconfiguredTitle: "同步設定無法使用", + misconfiguredBody: "修改同步位置的連線引數或出站代理後繼續同步。", + republish: "重新上傳本機配置", + }, + ko: { + update: "업데이트 확인", + }, + es: { + conflictTitle: (n: number) => (n === 1 ? "1 conflicto de sincronización" : `${n} conflictos de sincronización`), + conflictBody: "Este dispositivo y otro cambiaron el mismo elemento de diferentes maneras. Hasta que se resuelva, este dispositivo mantiene su propia versión.", + resolve: "Resolver…", + unreachableTitle: "Sincronizar ubicación inalcanzable", + unreachableBody: "La sincronización continúa una vez que es accesible de nuevo; los cambios realizados en este dispositivo se cargan entonces.", + authTitle: "Sincronización de la ubicación de acceso denegado", + authBody: "Cambie los detalles de la conexión de la ubicación de sincronización para continuar sincronizando.", + lockedTitle: "Sincronizar frase cambiada en otro dispositivo", + lockedBody: "Introduzca la nueva frase de paso para continuar sincronizando.", + unlock: "Introduzca la frase de paso…", + tooNewTitle: "Sincronización pausada", + tooNewBody: "Otro dispositivo utiliza una versión más reciente. Actualiza ThinkWatch Lite para continuar sincronizando.", + update: "Buscar actualizaciones", + pausedTitle: "Sin sincronización en modo seguro", + pausedBody: "La sincronización continúa una vez que la configuración se puede leer de nuevo.", + keyringTitle: "Sincronizar la tecla en la ubicación de sincronización no disponible", + keyringBody: "Falta la clave de sincronización, fue reemplazada por una anterior o no se puede leer, por lo que la sincronización se pausa. Suba la configuración de este dispositivo de nuevo (esto devuelve la tecla de sincronización guardada en este dispositivo), o deje de sincronizarse.", + emptiedTitle: "Sincronizar la ubicación vacía", + emptiedBody: "Otro dispositivo puede haber eliminado los datos de sincronización, o la ubicación de sincronización ya no es el mismo lugar, por lo que se pausa la sincronización.", + misconfiguredTitle: "Sincronización de la configuración inutilizable", + misconfiguredBody: "Cambie los detalles de la conexión de la ubicación de sincronización o el proxy saliente para continuar la sincronización.", + republish: "Cargar la configuración de este dispositivo", + stop: "Deja de sincronizar…", + }, + }, ); diff --git a/src/sync/UpstreamBadges.i18n.ts b/src/sync/UpstreamBadges.i18n.ts index 5209063a..b29fc565 100644 --- a/src/sync/UpstreamBadges.i18n.ts +++ b/src/sync/UpstreamBadges.i18n.ts @@ -24,4 +24,26 @@ export const upstreamBadgesText = messages( plainNote: "Synced content is not encrypted, so a URL change is pointed out here once.", markRead: "Mark as read", }, + { + "zh-Hant": { + notSyncedTip: "此上游不參與同步:不上傳,也不被其他裝置的同名上游覆蓋。在設定 › 同步與備份中修改。", + urlChanged: "地址經同步變更", + urlChangedTitle: "地址經同步變更", + urlChangedBody: (from: string, to: string) => `地址由 ${from} 變更為 ${to}。`, + plainNote: "同步內容未加密,地址的變更在這裡提示一次。", + markRead: "標為已讀", + }, + ko: { + markRead: "읽음으로 표시", + }, + es: { + notSynced: "Sin sincronizar", + notSyncedTip: "Este upstream se deja fuera de sincronización: no se carga y no se reemplaza por un upsteam del mismo nombre desde otro dispositivo. Cambie esto en Configuración › Sincronización y respaldo.", + urlChanged: "URL cambiada por sincronización", + urlChangedTitle: "URL cambiada por sincronización", + urlChangedBody: (from: string, to: string) => `La URL cambió de ${from} a ${to}.`, + plainNote: "El contenido sincronizado no está cifrado, por lo que un cambio de URL se señala aquí una vez.", + markRead: "Marcar como leído", + }, + }, ); diff --git a/src/sync/dialogs.i18n.ts b/src/sync/dialogs.i18n.ts index feebacc7..85e52b39 100644 --- a/src/sync/dialogs.i18n.ts +++ b/src/sync/dialogs.i18n.ts @@ -68,4 +68,58 @@ export const syncDialogsText = messages( noUpstreams: "No upstreams yet.", done: "Done", }, + { + "zh-Hant": { + enableTitle: "開啟加密", + enableDesc: "設定同步口令後,重新上傳最新版本並刪除未加密的版本。其他裝置在下次同步時須輸入口令。", + enable: "開啟加密", + disableTitle: "關閉加密", + disableDesc: "重新上傳未加密的版本,各裝置儲存的同步口令保留。之後同步位置的服務商可讀取配置與金鑰,對同步位置有寫入許可權的任何人也可以改動配置。", + disable: "關閉加密", + changeDesc: "只重新加密同步金鑰,已有版本不變。其他裝置在下次同步時須輸入新口令。", + current: "當前口令", + freshAgain: "再次輸入", + enterCurrent: "輸入當前口令。", + unlockTitle: "輸入同步口令", + unlockDesc: "同步口令已在其他裝置上更改。輸入新口令後繼續同步。", + unlock: "繼續同步", + stopDesc: "本機保留當前配置,刪除本機的同步設定,並從同步位置移除本裝置的裝置記錄。其他裝置不受影響。", + stopPurge: "停止同步並刪除同步資料…", + purgeTitle: "刪除同步資料", + purgeDesc: "刪除同步位置上的全部版本、裝置記錄與同步金鑰。其他裝置隨後提示同步位置為空,可重新上傳各自的配置或停止同步。此操作無法撤銷;本機配置與本機備份不受影響。", + purge: "刪除並停止同步", + excludeDesc: "所選上游不上傳,也不被其他裝置的同名上游覆蓋,適用於本機地址的 Ollama 等。引用它們的路由、別名、策略組隨之不同步。", + noUpstreams: "尚無上游。", + }, + es: { + enableTitle: "Activar el cifrado", + enableDesc: "Una vez que la frase de paso de sincronización se establece, la última versión se sube de nuevo y las versiones no cifradas se eliminan. Otros dispositivos piden la frase en su siguiente sincronización.", + enable: "Activar el cifrado", + disableTitle: "Desactivar el cifrado", + disableDesc: "Se vuelve a subir una versión sin cifrar; se guarda la frase de acceso de sincronización guardada en cada dispositivo. Desde entonces, el proveedor de almacenamiento puede leer la configuración y sus claves, y cualquier persona que pueda escribir a la ubicación de sincronización puede cambiar la configuración.", + disable: "Desactivar el cifrado", + changeTitle: "Cambiar frase de paso de sincronización", + changeDesc: "Sólo la clave de sincronización se encripta de nuevo; las versiones existentes permanecen como están. Otros dispositivos piden la nueva frase de paso en su siguiente sincronización.", + change: "Cambiar frase de paso", + current: "Frase de paso actual", + fresh: "Nueva frase de paso", + freshAgain: "Repetir", + enterCurrent: "Introduzca la frase de paso actual.", + failed: "Esto no pudo completarse.", + unlockTitle: "Introduzca la frase de paso de sincronización", + unlockDesc: "La frase de paso de sincronización se cambió en otro dispositivo. Introduzca la nueva frase de acceso para continuar sincronizando.", + unlock: "Continuar la sincronización", + stopTitle: "Detener la sincronización", + stopDesc: "Este dispositivo mantiene su configuración actual; sus ajustes de sincronización se eliminan y su registro de dispositivo se elimina de la ubicación de sincronización. Otros dispositivos no se ven afectados.", + stop: "Detener la sincronización", + stopPurge: "Detener y eliminar datos de sincronización…", + purgeTitle: "Eliminar datos de sincronización", + purgeDesc: "Cada versión, registro de dispositivo y la clave de sincronización se eliminan de la ubicación de sincronización. Los otros dispositivos informan de una ubicación de sincronización vacía, donde su configuración puede ser cargada de nuevo o se puede detener. Esto no se puede deshacer. La configuración de este dispositivo y las copias de seguridad locales no se ven afectadas.", + purge: "Eliminar y dejar de sincronizar", + excludeTitle: "Corrientes ascendentes no sincronizadas", + excludeDesc: "Las del proveedor elegidas no se cargan y no se sustituyen por del proveedor del mismo nombre de otros dispositivos, por ejemplo un Ollama local. Las rutas, alias y grupos que las utilizan tampoco se sincronizan.", + noUpstreams: "No hay del proveedor todavía.", + done: "Hecho", + }, + }, ); diff --git a/src/sync/fields.i18n.ts b/src/sync/fields.i18n.ts index 809219dd..84328818 100644 --- a/src/sync/fields.i18n.ts +++ b/src/sync/fields.i18n.ts @@ -83,4 +83,78 @@ export const syncFieldsText = messages( passphraseShort: (n: number) => `The sync passphrase needs at least ${n} characters.`, passphraseMismatch: "The two passphrases differ.", }, + { + "zh-Hant": { + kinds: { folder: "資料夾", webdav: "WebDAV", s3: "S3 相容儲存" }, + folder: "資料夾", + pick: "選擇…", + folderHint: "iCloud Drive、Dropbox、OneDrive、Syncthing 等同步的資料夾均可。同步資料直接存放在該資料夾中,建議使用專用資料夾。", + folderRemoteHint: "伺服器上的資料夾路徑。", + user: "使用者名稱", + pass: "密碼", + passHint: "堅果雲等服務使用應用密碼。", + endpoint: "端點", + region: "區域", + regionHint: "Cloudflare R2 填寫 auto。", + bucket: "儲存桶", + prefix: "字首", + prefixHint: "可選。多個用途共用一個儲存桶時用於區分。", + direct: "直連", + system: "系統代理", + problem: { + path: "填寫資料夾路徑。", + url: "填寫 WebDAV 地址。", + url_scheme: "地址須以 https:// 或 http:// 開頭。", + endpoint: "填寫端點。", + endpoint_scheme: "端點須以 https:// 或 http:// 開頭。", + bucket: "填寫儲存桶。", + access_key_id: "填寫 Access Key ID。", + secret_access_key: "填寫 Secret Access Key。", + }, + deviceName: "本裝置名稱", + deviceNameHint: "在其他裝置的裝置列表中顯示。", + deviceNameMissing: "填寫本裝置名稱。", + passphraseAgain: "再次輸入", + passphraseShort: (n: number) => `同步口令至少 ${n} 個字元。`, + passphraseMismatch: "兩次輸入的口令不一致。", + }, + es: { + location: "Sincronizar ubicación", + kinds: { folder: "Carpeta", webdav: "WebDAV", s3: "Compatible con S3" }, + folder: "Carpeta", + pick: "Elegir…", + folderHint: "Cualquier carpeta sincronizada por iCloud Drive, Dropbox, OneDrive, Syncthing o similar. Sincronizar datos se almacena directamente en él, por lo que es mejor una carpeta dedicada.", + folderRemoteHint: "Una ruta de carpeta en el servidor.", + user: "Nombre de usuario", + pass: "Contraseña", + passHint: "Servicios como Jianguoyun utilizan una contraseña de aplicación.", + endpoint: "Punto final", + region: "Región", + regionHint: "Para Cloudflare R2, introduzca automáticamente.", + bucket: "Cuchara", + prefix: "Prefijo", + prefixHint: "Opcional. Mantiene estos datos separados cuando se comparte el cubo.", + accessKeyId: "Id. de clave de acceso", + secretAccessKey: "Clave de acceso secreta", + direct: "Directo", + system: "Proxy del sistema", + problem: { + path: "Introduzca una ruta de carpeta.", + url: "Introduzca la URL de WebDAV.", + url_scheme: "El URL debe comenzar con https:// o http://.", + endpoint: "Introduzca el punto final.", + endpoint_scheme: "El punto final debe comenzar con https:// o http://.", + bucket: "Entra en el cubo.", + access_key_id: "Introduzca la clave de acceso ID.", + secret_access_key: "Introduzca la llave de acceso secreta.", + }, + deviceName: "Nombre del dispositivo", + deviceNameHint: "Se muestra en la lista de dispositivos en los otros dispositivos.", + deviceNameMissing: "Introduzca un nombre de dispositivo.", + passphrase: "Sincronizar contraseña", + passphraseAgain: "Repetir", + passphraseShort: (n: number) => `La frase de paso de sincronización necesita al menos ${n} caracteres.`, + passphraseMismatch: "Las dos frases de paso difieren.", + }, + }, ); diff --git a/src/sync/labels.i18n.ts b/src/sync/labels.i18n.ts index dd6617a2..e63c5fd1 100644 --- a/src/sync/labels.i18n.ts +++ b/src/sync/labels.i18n.ts @@ -88,4 +88,99 @@ export const syncLabelsText = messages( minutesAgo: (n: number) => (n === 1 ? "1 minute ago" : `${n} minutes ago`), today: (hm: string) => `today ${hm}`, }, + { + "zh-Hant": { + kind: { + provider: "上游", + proxy: "代理", + key: "閘道器金鑰", + alias: "別名", + group: "策略組", + route: "路由", + price_sheet: "價目表", + security_rule: "安全規則", + plugin: "外掛", + provider_order: "上游順序", + route_order: "路由順序", + plugin_order: "外掛順序", + global: "全域性設定", + client_prefs: "通用偏好", + }, + global: { + failover: "故障轉移", + security: "安全防護", + default_route: "預設路由", + default_key: "預設金鑰", + client_probes: "輔助請求", + pricing: "價目表設定", + } as Record, + unit: { + conn: "連線", + models: "模型", + billing: "計費", + other: "其他", + script: "指令碼", + settings: "設定", + enabled: "啟用狀態", + } as Record, + justNow: "剛剛", + minutesAgo: (n: number) => `${n} 分鐘前`, + }, + ko: { + kind: { + provider: "업스트림", + proxy: "Proxy", + key: "Gateway key", + alias: "Alias", + group: "Group", + route: "Route", + price_sheet: "Price sheet", + security_rule: "Security rule", + plugin: "플러그인", + provider_order: "Upstream order", + route_order: "Route order", + plugin_order: "Plugin order", + global: "Global settings", + client_prefs: "General preferences", + }, + }, + es: { + kind: { + provider: "Proveedor", + proxy: "Proxy", + key: "Tecla de puerta de enlace", + alias: "Alias", + group: "Grupo", + route: "Ruta", + price_sheet: "Ficha de precios", + security_rule: "Regla de seguridad", + plugin: "Complemento", + provider_order: "Orden ascendente", + route_order: "Orden de la ruta", + plugin_order: "Pedido del complemento", + global: "Ajustes mundiales", + client_prefs: "Preferencias generales", + }, + global: { + failover: "Fallo", + security: "Protección", + default_route: "Ruta predeterminada", + default_key: "Tecla predeterminada", + client_probes: "Solicitudes auxiliares", + pricing: "Ajustes de la hoja de precios", + } as Record, + unit: { + conn: "conexión", + models: "modelos", + billing: "facturación", + other: "otros", + script: "script", + settings: "ajustes", + enabled: "on/off", + } as Record, + justNow: "justo ahora", + minutesAgo: (n: number) => (n === 1 ? "Hace 1 minuto" : `${n} Hace minutos`), + today: (hm: string) => `hoy ${hm}`, + }, + }, ); diff --git a/src/traffic/Conversation.i18n.tsx b/src/traffic/Conversation.i18n.tsx index 41fcfd96..07717e7d 100644 --- a/src/traffic/Conversation.i18n.tsx +++ b/src/traffic/Conversation.i18n.tsx @@ -162,4 +162,112 @@ export const conversationText = messages( estimated: "Estimated", estimatedTip: "Each part is estimated from the stored request body; it differs from the input the upstream measured.", }, + { + "zh-Hant": { + loadFailed: "對話讀取失敗", + emptyTitle: "尚無已記錄的輪次", + emptyHint: "每輪結束後顯示在此處", + allExpiredTitle: "對話內容已超過保留期限", + allUnkeptTitle: "對話正文未保留", + allLostHint: "費用與用量仍可在概況中檢視", + showSummary: "檢視概況", + user: "使用者", + system: "系統", + turnNo: (n: number) => `第 ${n} 輪`, + openRequest: "請求詳情", + afterEnd: "請求結束後可檢視", + systemPrompt: "系統提示", + systemChanged: "系統提示已更改", + thinkingHidden: "上游未返回思考內容", + result: "工具結果", + resultOf: (name: ReactNode) => <>{name} 的結果, + error: "錯誤", + noOutput: "無輸出", + image: "圖片", + chars: (n: number) => `${n.toLocaleString()} 字元`, + showAll: "展開全部", + collapse: "摺疊", + restart: "對話歷史從此處重新開始", + earlier: (n: number) => `此前的對話 · ${n} 條訊息`, + expired: "此輪內容已超過保留期限", + unkept: "此輪正文未保留", + expiredRun: (from: number, to: number) => `第 ${from}–${to} 輪的內容已超過保留期限`, + unkeptRun: (from: number, to: number) => `第 ${from}–${to} 輪的正文未保留`, + requestExpired: "請求內容已超過保留期限", + requestUnkept: "請求正文未保留", + requestTruncated: "請求過大,未完整儲存", + responseExpired: "回應內容已超過保留期限", + responseUnkept: "回應正文未保留", + responseCancelled: "已取消:用戶端在回應結束前斷開連線", + responseTruncated: "回應過大,未完整儲存", + responseUnreadable: "回應格式無法識別,原文見請求詳情", + noContent: "無對話內容", + cached: (pct: number) => `快取 ${pct}%`, + contextBar: (used: string, window: string, cachedPct: number) => `上下文 ${used} / ${window},快取讀取佔 ${cachedPct}%`, + contextLoadFailed: "上下文讀取失敗", + partSystem: "系統提示", + partTools: "工具定義", + partHistory: "此前的對話", + partLastUser: "最後一條使用者訊息", + partTotal: "合計", + estimatedTip: "各部分按儲存的請求正文估算,與上游計量的輸入不同。", + }, + ko: { + system: "시스템 설정", + }, + es: { + loadFailed: "No se pudo cargar la conversación", + emptyTitle: "Aún no se han registrado giros", + emptyHint: "Cada turno aparece aquí cuando termina", + allExpiredTitle: "La conversación ha pasado el período de retención", + allUnkeptTitle: "El contenido de la conversación no se mantuvo", + allLostHint: "El costo y el uso están todavía en el resumen", + showSummary: "Mostrar resumen", + user: "Usuario", + assistant: "Asistente", + tool: "Herramienta", + system: "Sistema", + turnNo: (n: number) => `Girar ${n}`, + openRequest: "Detalles de la solicitud", + afterEnd: "Disponible cuando finalice la solicitud", + systemPrompt: "Indicación del sistema", + systemChanged: "Se ha cambiado el sistema prompt", + thinking: "Pensar", + thinkingHidden: "El curso anterior no devolvió ningún contenido de pensamiento", + result: "Resultado de la herramienta", + resultOf: (name: ReactNode) => <>{name} resultado, + noOutput: "Sin salida", + image: "Imagen", + chars: (n: number) => count(n, "carácter", "caracteres"), + showAll: "Mostrar todo", + collapse: "Colapso", + hasHit: "Contiene un golpe de seguridad", + restart: "La historia de la conversación comienza aquí.", + earlier: (n: number) => `Conversación anterior · ${count(n, "mensaje", "mensajes")}`, + expired: "Este giro ha pasado el período de retención", + unkept: "El contenido de este turno no se mantuvo", + expiredRun: (from: number, to: number) => `Las vueltas ${from}–${to} pasan el período de retención`, + unkeptRun: (from: number, to: number) => `El contenido de las vueltas ${from}–${to} no se mantuvo`, + requestExpired: "La solicitud ha pasado el período de retención", + requestUnkept: "No se mantuvo el organismo de solicitud", + requestTruncated: "La petición era demasiado grande para ahorrar en su totalidad", + responseExpired: "La respuesta ha pasado el período de retención", + responseUnkept: "El cuerpo de respuesta no se mantuvo", + failedWithStatus: (status: number, reason: string) => `En la fase anterior se respondió ${status}: ${reason}`, + responseCancelled: "Cancelado: el cliente se desconectó antes de que la respuesta terminara", + responseTruncated: "La respuesta fue demasiado grande para ahorrar en su totalidad", + responseUnreadable: "El formato de respuesta no se reconoce; el cuerpo en bruto está en los detalles de la solicitud", + noContent: "Sin contenido de conversación", + context: "Contexto", + cached: (pct: number) => `${pct}% en caché`, + contextBar: (used: string, window: string, cachedPct: number) => `Contexto ${used} de ${window}, ${cachedPct}% de la caché lee`, + contextLoadFailed: "No se pudo cargar el desglose de contexto", + partSystem: "Indicación del sistema", + partTools: "Definiciones de las herramientas", + partHistory: "Conversación anterior", + partLastUser: "Último mensaje de usuario", + estimated: "Estimación", + estimatedTip: "Cada parte se estima a partir del cuerpo de solicitud almacenado; difiere de la entrada de la medida del proveedor.", + }, + }, ); diff --git a/src/traffic/Markdown.tsx b/src/traffic/Markdown.tsx index 6d65fe8e..4a259c50 100644 --- a/src/traffic/Markdown.tsx +++ b/src/traffic/Markdown.tsx @@ -13,10 +13,10 @@ import { useMarker } from "@/security/Highlight"; * - 链接只显示文字、悬停看地址,不能点:点了会把应用的窗口导航走;图片只显示替代文字 * - 顶层每一块按原文 `memo`:回答在长时只有最后一块重画 */ -export function Markdown({ text, tail }: { text: string; tail?: ReactNode }) { +export function Markdown({ text, tail, className }: { text: string; tail?: ReactNode; className?: string }) { const blocks = useMemo(() => lexer(text, { gfm: true, breaks: true }).filter((b) => b.type !== "space"), [text]); return ( -
+
{blocks.map((b, i) => { const last = i === blocks.length - 1; return ; diff --git a/src/traffic/Sessions.i18n.ts b/src/traffic/Sessions.i18n.ts index dbbb43e2..652cf1f5 100644 --- a/src/traffic/Sessions.i18n.ts +++ b/src/traffic/Sessions.i18n.ts @@ -116,4 +116,83 @@ export const sessionsText = messages( turnCancelled: "Canceled", turnRunning: "In progress", }, + { + "zh-Hant": { + expandSession: "展開此會話", + collapseSession: "收起此會話", + turnCount: (n: number) => `${n} 輪`, + failedTip: (n: number) => `此會話中 ${n} 輪失敗`, + runningTip: (n: number) => `此會話中 ${n} 輪進行中`, + sessionActions: "此會話的操作", + openSession: "開啟會話", + copySessionId: "複製會話 ID", + estimatedTip: (amount: string) => `其中 ${amount} 為估算值:請求在回應結束前斷開或中斷,輸出用量計至斷開時;或模型的單價取自其他平臺。`, + unpriced: "無法計價", + noPricedTurnsTip: "此會話中沒有可計價的輪次", + unpricedTurnsTip: (n: number) => `${n} 輪所用的模型未定價,費用未計入合計`, + noUsageTurnsTip: (n: number) => `${n} 輪沒有用量資料:上游未報告,或連線在報告之前已結束。這些輪次的費用無法計算,未計入合計`, + title: "會話", + tabSummary: "概況", + tabConversation: "對話", + startedAt: (at: string) => `${at} 開始`, + turns: "輪次", + duration: "時長", + cost: "費用", + failedTurns: "失敗", + loadFailed: "會話讀取失敗", + usage: (input: string, output: string, cacheRead: string) => `輸入 ${input} / 輸出 ${output} · 快取讀取 ${cacheRead}`, + growthTitle: "每輪輸入 token", + cacheReads: "快取讀取", + uncachedInput: "新輸入", + growthBar: (turn: number, total: string, read: string, input: string) => `第 ${turn} 輪 · ${total} token(快取讀取 ${read} · 新輸入 ${input})`, + waterfallTitle: "每輪費用", + turnFailed: "失敗", + turnRunning: "進行中", + }, + ko: { + cost: "비용", + failedTurns: "실패", + turnFailed: "실패", + turnRunning: "진행 중", + }, + es: { + expandSession: "Ampliar este período de sesiones", + collapseSession: "Contraer esta sesión", + turnCount: (n: number) => (n === 1 ? "1 turno" : `${n} giros`), + peakContext: "Contexto de pico", + failedTip: (n: number) => n === 1 ? "1 turno en esta sesión falló." : `${n} los giros en esta sesión fallaron.`, + runningTip: (n: number) => n === 1 ? "1 turn in this session is in progress." : `${n} giros en esta sesión están en curso.`, + sessionActions: "Medidas para este período de sesiones", + openSession: "Sesión abierta", + copySessionId: "Copiar el ID de sesión", + estimatedTip: (amount: string) => `${amount} de esto se estima: solicitudes desconectadas o fueron interrumpidas antes de que la respuesta terminara, y el uso de salida se cuenta hasta la desconexión; o el precio del modelo fue tomado de otra plataforma.`, + unpriced: "Sin precio", + noPricedTurnsTip: "Ninguna vuelta en esta sesión podría tener precio.", + unpricedTurnsTip: (n: number) => n === 1 + ? "1 turno utilizado un modelo sin precio, por lo que su costo no está incluido en el total." + : `${n} gira modelos usados sin precio, por lo que su costo no está incluido en el total.`, + noUsageTurnsTip: (n: number) => n === 1 + ? "1 turn no tiene datos de uso: el upstream no lo reportó, o la conexión terminó antes de ser reportado. Su costo no puede ser calculado y no está incluido en el total." + : `${n} los giros no tienen datos de uso: el upstream no lo reportó, o la conexión terminó antes de ser reportado. Su costo no puede ser calculado y no está incluido en el total.`, + title: "Sesión", + tabSummary: "Resumen", + tabConversation: "Conversación", + startedAt: (at: string) => `Iniciada ${at}`, + turns: "Gira", + duration: "Duración", + cost: "Coste", + failedTurns: "Error", + loadFailed: "No se pudo cargar la sesión", + usage: (input: string, output: string, cacheRead: string) => `Entrada ${input} / Salida ${output} · Caché lee ${cacheRead}`, + growthTitle: "tokens de entrada por turno", + cacheReads: "Caché lee", + uncachedInput: "Entrada sin encallar", + peak: (v: string) => `Pico ${v}`, + growthBar: (turn: number, total: string, read: string, input: string) => `Gire ${turn} · ${total} tokens (la caché dice ${read} · entrada no caché ${input})`, + waterfallTitle: "Costo por turno", + turnFailed: "Error", + turnCancelled: "Cancelado", + turnRunning: "En curso", + }, + }, ); diff --git a/src/traffic/Traffic.i18n.tsx b/src/traffic/Traffic.i18n.tsx index 2eebf529..017c078b 100644 --- a/src/traffic/Traffic.i18n.tsx +++ b/src/traffic/Traffic.i18n.tsx @@ -361,4 +361,480 @@ export const trafficText = messages( estimatedBorrowed: "The price sheet has no price for this upstream; the amount is estimated from the same model's price on another platform.", }, + { + "zh-Hant": { + idle: "當前空閒", + inFlight: "個進行中", + requestsUnit: (_n: number) => "條請求", + failedUnit: (_n: number) => "條失敗", + recent: (n: ReactNode) => <>近 30 分鐘 {n} 條, + sparkLabel: (n: number, failed: number) => `近 30 分鐘 ${n} 條請求${failed > 0 ? `,其中 ${failed} 條失敗` : ""}`, + sparkBar: (at: string, n: number, failed: number) => n === 0 ? `${at} · 無請求` : `${at} · ${n} 條${failed > 0 ? `,${failed} 條失敗` : ""}`, + viewLabel: "檢視", + viewRequests: "請求", + viewSessions: "會話", + search: isMac ? "搜尋路徑、金鑰、上游、錯誤… ⌘F" : `搜尋路徑、金鑰、上游、錯誤 ${modKey}+F`, + failedOnly: "僅顯示失敗", + unpricedOnly: "僅顯示無法計價", + allClients: "全部金鑰", + shownOf: (shown: number, total: number) => `${shown} / ${total} 條`, + searchContent: "搜尋內容", + searchContentTip: "同時搜尋請求與回答的內容", + found: (n: number) => `找到 ${n} 條`, + searchingOlder: "正在搜尋更早的記錄…", + searchingContent: "正在搜尋內容…", + searchedTo: (at: string) => `已搜尋至 ${at}`, + searchedAll: "已搜尋全部記錄", + searchMore: "繼續搜尋", + searchFailed: (why: string) => `搜尋失敗:${why}`, + bodiesSince: (ms: number) => `封包保留自 ${new Date(ms).toLocaleDateString("zh-CN", { month: "long", day: "numeric", timeZone: "UTC" })},更早的請求不按內容匹配。`, + noBodies: "沒有保留的封包,請求不按內容匹配。", + hitRequest: "請求", + listening: (addr: ReactNode) => <>閘道器正在 {addr} 監聽。配置上游後,請求才能轉發。, + noMatchTitle: "沒有符合條件的請求", + noMatch: (n: number) => `共 ${n} 條記錄,當前篩選條件下沒有匹配項。`, + noMatchSearched: (at: string | null) => at === null ? "已搜尋全部記錄,當前篩選條件下沒有匹配項。" : `已搜尋至 ${at},當前篩選條件下沒有匹配項。`, + clearFilters: "清除篩選條件", + emptyTitle: "暫無請求記錄", + pointClients: (endpoint: ReactNode) => <>將用戶端的端點設為 {endpoint},並使用以 tw- 開頭的用戶端金鑰。, + appearHere: "收到請求後,請求記錄將顯示在此處。", + copyAddress: "複製地址", + goToClients: "前往用戶端", + addressCopied: "閘道器地址已複製", + probesAnswered: (n: number) => `已本地應答 ${n} 次用戶端探測。用戶端已連線閘道器,這些探測未產生費用。`, + probesElsewhere: (n: number) => `另有 ${n} 次用戶端探測由閘道器本地應答,未傳送到上游。`, + historyFailed: "請求記錄讀取失敗", + historyPartial: "請求記錄讀取失敗,以下僅為此後收到的請求。", + columns: "列設定", + compactColumns: "緊湊檢視", + resetColumns: "恢復預設", + pinColumnLeft: "固定左側", + pinColumnRight: "固定右側", + moveColumnUp: (name: string) => `將${name}列前移`, + moveColumnDown: (name: string) => `將${name}列後移`, + requestedModel: (name: string) => `請求:${name}`, + sentModel: (name: string) => `發往上游:${name}`, + status: "狀態", + time: "時間", + client: "金鑰", + latency: "延遲", + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `首 token ${ttft}`, + `總耗時 ${total}`, + `生成用時 ${gen}`, + ...(speed != null ? [`生成速度 ${speed} token/秒`] : []), + ], + liveSpeedTip: (n: string) => `當前生成速度 ${n} token/秒`, + cost: "費用", + keyTip: (key: string) => `金鑰 ${key}`, + appTip: (app: string) => `應用 ${app}(按請求頭推測)`, + fromPeer: (ip: string) => `來自 ${ip}`, + promptTip: (n: string) => `輸入合計 ${n}`, + promptParts: (input: string, read: string, write: string) => `新輸入 ${input} · 快取讀取 ${read} · 快取寫入 ${write}`, + outputTip: (n: string) => `輸出 ${n}`, + uploadTip: (shown: string) => `上傳 ${shown}`, + downloadTip: (shown: string) => `下載 ${shown}`, + rowActions: (id: number) => `第 ${id} 號請求的操作`, + openDetails: "開啟詳情", + onlyUpstream: (name: string) => `僅顯示上游 ${name}`, + onlyClient: (name: string) => `僅顯示金鑰 ${name}`, + copyId: "複製請求 ID", + copyRow: "複製此行", + failed: "失敗", + aborted: "手動中止", + queued: "排隊中", + retrying: "重試中", + queuedTip: (names: string[], at: string) => `排隊等待上游:${names.join("、")}。最晚等到 ${at}。`, + retryingTip: (names: string[], at: string) => `等待重試上游:${names.join("、")}。最晚等到 ${at}。`, + aliasTip: (model: string, upstream: string, sent: string) => `${model} 是別名,發往 ${upstream} 的模型名是 ${sent}。`, + pinnedTip: (rule: string, upstream: string, sent: string) => `規則「${rule}」指定了發往 ${upstream} 的模型:${sent}。`, + redactedTip: (items: string[]) => `傳送前已替換:${items.join("、")}`, + redacted: (n: number) => `已脫敏 ${n}`, + secretsTip: (items: string[]) => `請求中含有憑據,已原樣發出:${items.join("、")}`, + withSecrets: (n: number) => `含憑據 ${n}`, + stripped: "已刪除", + strippedTip: (rules: string[]) => `已刪除命中以下內容規則的文字:${rules.join("、")}`, + contentReplaced: "已替換", + contentReplacedTip: (rules: string[]) => `已替換命中以下內容規則的文字:${rules.join("、")}`, + sentConverted: (formats: string) => `請求已轉換格式後傳送:${formats}。`, + droppedFields: (fields: string[]) => `\n\n目標格式不支援、已丟棄的欄位:${fields.join("、")}`, + noneDropped: "\n未丟棄任何欄位。", + converted: "已轉換", + convertedDropped: (n: number) => `丟棄 ${n} 個欄位`, + pluginChanged: "外掛", + pluginChangedTip: "經外掛改寫。在請求詳情中可以對比改寫前後。", + blocked: "已攔截", + suspicious: "可疑呼叫", + estimatedCancelled: "用戶端在回應結束前斷開,輸出用量計至斷開時,實際費用可能更高。", + estimatedFailed: "回應在結束前中斷,輸出用量計至中斷時,實際費用可能更高。", + estimatedBorrowed: "價目表中沒有此上游的單價,該金額按同一模型在其他平臺的單價估算。", + }, + ja: { + idle: "処理中のリクエストなし", + inFlight: "件処理中", + latest: "直近", + requestsUnit: (_n: number) => "件のリクエスト", + failedUnit: (_n: number) => "件失敗", + recent: (n: ReactNode) => <>過去 30 分間に {n} 件, + sparkLabel: (n: number, failed: number) => `過去 30 分間のリクエスト ${n} 件${failed > 0 ? `(失敗 ${failed} 件)` : ""}`, + sparkBar: (at: string, n: number, failed: number) => n === 0 ? `${at} · リクエストなし` : `${at} · ${n} 件${failed > 0 ? `(失敗 ${failed} 件)` : ""}`, + viewLabel: "表示", + viewRequests: "リクエスト", + viewSessions: "セッション", + search: `パス、キー、エラーを検索 ${modKey}+F`, + failedOnly: "失敗のみ", + unpricedOnly: "料金不明のみ", + allClients: "すべてのキー", + allUpstreams: "すべてのアップストリーム", + allModels: "すべてのモデル", + shownOf: (shown: number, total: number) => `${shown} / ${total} 件`, + clear: "クリア", + searchContent: "内容を検索", + searchContentTip: "リクエストとレスポンスの内容も検索します", + found: (n: number) => `${n} 件見つかりました`, + searchingOlder: "以前の記録を検索しています…", + searchingContent: "内容を検索しています…", + searchedTo: (at: string) => `${at} まで検索済み`, + searchedAll: "すべての記録を検索済み", + searchMore: "さらに検索", + searchFailed: (why: string) => `検索に失敗しました:${why}`, + bodiesSince: (ms: number) => `本文は ${new Date(ms).toLocaleDateString("ja", { month: "long", day: "numeric", timeZone: "UTC" })} 以降の分を保持しています。それ以前の記録は本文の検索対象外です。`, + noBodies: "保持されている本文がないため、本文は検索対象外です。", + hitRequest: "リクエスト", + hitAnswer: "レスポンス", + noUpstreams: "アップストリームが設定されていません", + listening: (addr: ReactNode) => <>ゲートウェイは {addr} でリッスンしています。リクエストを転送するにはアップストリームを設定してください。, + goToUpstreams: "アップストリームを開く", + noMatchTitle: "条件に一致するリクエストがありません", + noMatch: (n: number) => `全 ${n} 件の記録に、現在の条件と一致するものがありません。`, + noMatchSearched: (at: string | null) => at === null ? "すべての記録を検索しましたが、条件に一致するものがありません。" : `${at} まで検索しましたが、条件に一致するものがありません。`, + clearFilters: "フィルターを解除", + emptyTitle: "リクエストの記録がありません", + pointClients: (endpoint: ReactNode) => <>クライアントの接続先を {endpoint} に設定し、tw- で始まるクライアントキーを使用してください。, + appearHere: "リクエストを受信すると、ここに記録が表示されます。", + copyAddress: "アドレスをコピー", + goToClients: "クライアントを開く", + addressCopied: "ゲートウェイアドレスをコピーしました", + probesAnswered: (n: number) => `クライアントの確認リクエスト ${n} 件にゲートウェイが応答しました。クライアントは接続済みで、これらの応答に費用は発生していません。`, + probesElsewhere: (n: number) => `ほかに ${n} 件の確認リクエストにゲートウェイが直接応答しました。アップストリームには送信されていません。`, + historyFailed: "リクエスト履歴を読み込めませんでした", + historyPartial: "リクエスト履歴を読み込めませんでした。それ以降に受信したリクエストを表示しています。", + columns: "列の設定", + compactColumns: "コンパクト表示", + resetColumns: "既定の設定に戻す", + pinColumn: (name: string) => `「${name}」列の固定位置`, + unpinnedColumn: "固定しない", + pinColumnLeft: "左に固定", + pinColumnRight: "右に固定", + moveColumnUp: (name: string) => `「${name}」列を前へ移動`, + moveColumnDown: (name: string) => `「${name}」列を後ろへ移動`, + requestedModel: (name: string) => `リクエスト:${name}`, + sentModel: (name: string) => `送信:${name}`, + status: "状態", + time: "時刻", + client: "キー", + model: "モデル", + upstream: "アップストリーム", + latency: "レイテンシ", + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `最初のトークンまで ${ttft}`, `全体 ${total}`, `生成 ${gen}`, + ...(speed != null ? [`生成速度 ${speed} トークン/秒`] : []), + ], + tokens: "トークン", + liveSpeed: (n: string) => `${n} t/s`, + liveSpeedTip: (n: string) => `現在の生成速度 ${n} トークン/秒`, + cost: "費用", + keyTip: (key: string) => `キー ${key}`, + appTip: (app: string) => `アプリ ${app}(リクエストヘッダーから推定)`, + fromPeer: (ip: string) => `送信元 ${ip}`, + promptTip: (n: string) => `入力合計 ${n}`, + promptParts: (input: string, read: string, write: string) => `未キャッシュの入力 ${input} · キャッシュ読み取り ${read} · キャッシュ書き込み ${write}`, + outputTip: (n: string) => `出力 ${n}`, + uploadTip: (shown: string) => `送信 ${shown}`, + downloadTip: (shown: string) => `受信 ${shown}`, + rowActions: (id: number) => `リクエスト #${id} の操作`, + openDetails: "詳細を開く", + onlyUpstream: (name: string) => `アップストリーム ${name} のみ表示`, + onlyClient: (name: string) => `キー ${name} のみ表示`, + copyId: "リクエスト ID をコピー", + copyRow: "行をコピー", + failed: "失敗", + cancelled: "キャンセル済み", + aborted: "手動で中止", + queued: "待機中", + retrying: "再試行中", + waitingFor: (names: string[]) => names.join("、"), + queuedTip: (names: string[], at: string) => `${names.join("、")} の空きを待っています。待機期限は ${at} です。`, + retryingTip: (names: string[], at: string) => `${names.join("、")} への再試行を待っています。待機期限は ${at} です。`, + aliasTip: (model: string, upstream: string, sent: string) => `${model} はエイリアスです。${upstream} には ${sent} として送信しました。`, + pinned: "固定", + pinnedTip: (rule: string, upstream: string, sent: string) => `ルール「${rule}」により、${upstream} に送るモデルを ${sent} に固定しました。`, + redactedTip: (items: string[]) => `送信前に置換:${items.join("、")}`, + redacted: (n: number) => `マスキング ${n} 件`, + secretsTip: (items: string[]) => `認証情報を含む状態で送信:${items.join("、")}`, + withSecrets: (n: number) => `認証情報 ${n} 件`, + stripped: "削除済み", + strippedTip: (rules: string[]) => `以下のルールに一致した内容を削除しました:${rules.join("、")}`, + contentReplaced: "置換済み", + contentReplacedTip: (rules: string[]) => `以下のルールに一致した内容を置換しました:${rules.join("、")}`, + sentConverted: (formats: string) => `形式を変換して送信しました:${formats}。`, + droppedFields: (fields: string[]) => `\n\n変換先の形式で対応していないため削除したフィールド:${fields.join("、")}`, + noneDropped: "\n削除されたフィールドはありません。", + converted: "変換済み", + convertedDropped: (n: number) => `${n} 個のフィールドを削除`, + flaggedTip: (tool: string, rule: string, excerpt: string) => `${tool} · ${rule}\n${excerpt}`, + pluginChanged: "プラグイン", + pluginChangedTip: "プラグインで変更されました。リクエストの詳細で変更前後を比較できます。", + blocked: "ブロック済み", + suspicious: "不審な呼び出し", + estimatedCancelled: "レスポンス完了前にクライアントが切断されました。切断までの出力を集計しているため、実際の費用は高くなる場合があります。", + estimatedFailed: "レスポンスが途中で中断されました。中断までの出力を集計しているため、実際の費用は高くなる場合があります。", + estimatedBorrowed: "このアップストリームの単価が料金表にないため、別のプラットフォームにおける同じモデルの単価で推定しました。", + }, + ko: { + viewRequests: "요청", + viewSessions: "세션", + allUpstreams: "모든 업스트림", + hitRequest: "요청", + status: "상태", + time: "시간", + client: "키", + model: "모델", + upstream: "업스트림", + latency: "지연 시간", + tokens: "토큰", + cost: "비용", + failed: "실패", + pluginChanged: "플러그인", + idle: "진행 중인 요청 없음", + inFlight: "건 진행 중", + latest: "최근", + requestsUnit: (_n: number) => "건의 요청", + failedUnit: (_n: number) => "건 실패", + recent: (n: ReactNode) => <>최근 30분간 {n}건, + sparkLabel: (n: number, failed: number) => `최근 30분간 요청 ${n}건${failed > 0 ? `, 실패 ${failed}건` : ""}`, + sparkBar: (at: string, n: number, failed: number) => n === 0 ? `${at} · 요청 없음` : `${at} · ${n}건${failed > 0 ? `, 실패 ${failed}건` : ""}`, + viewLabel: "보기", + search: `경로, 키, 업스트림, 오류 검색… ${modKey}${isMac ? "" : "+"}F`, + failedOnly: "실패만 표시", + unpricedOnly: "단가 없음만 표시", + allClients: "모든 키", + allModels: "모든 모델", + shownOf: (shown: number, total: number) => `${shown} / ${total}건`, + clear: "지우기", + searchContent: "본문 검색", + searchContentTip: "요청과 응답의 본문도 검색합니다", + found: (n: number) => `${n}건 찾음`, + searchingOlder: "이전 기록 검색 중…", + searchingContent: "본문 검색 중…", + searchedTo: (at: string) => `${at}까지 검색함`, + searchedAll: "모든 기록을 검색했습니다", + searchMore: "더 검색", + searchFailed: (why: string) => `검색 실패: ${why}`, + bodiesSince: (ms: number) => `${new Date(ms).toLocaleDateString("ko", { month: "long", day: "numeric", timeZone: "UTC" })}부터 본문을 보관합니다. 이전 요청은 본문으로 검색할 수 없습니다.`, + noBodies: "보관된 본문이 없어 본문을 검색할 수 없습니다.", + hitAnswer: "응답", + noUpstreams: "설정된 업스트림이 없습니다", + listening: (addr: ReactNode) => <>게이트웨이가 {addr}에서 연결을 기다립니다. 업스트림을 설정하면 요청을 전달할 수 있습니다., + goToUpstreams: "업스트림 열기", + noMatchTitle: "일치하는 요청 없음", + noMatch: (n: number) => `요청 ${n}건 중 현재 필터와 일치하는 항목이 없습니다.`, + noMatchSearched: (at: string | null) => at === null ? "모든 기록을 검색했지만 현재 필터와 일치하는 항목이 없습니다." : `${at}까지 검색했지만 현재 필터와 일치하는 항목이 없습니다.`, + clearFilters: "필터 지우기", + emptyTitle: "요청 기록 없음", + pointClients: (endpoint: ReactNode) => <>클라이언트의 엔드포인트를 {endpoint}로 설정하고 tw-로 시작하는 클라이언트 키를 사용하세요., + appearHere: "요청을 받으면 여기에 표시됩니다.", + copyAddress: "주소 복사", + goToClients: "클라이언트 열기", + addressCopied: "게이트웨이 주소를 복사했습니다", + probesAnswered: (n: number) => `게이트웨이가 클라이언트의 연결 확인 요청 ${n}건에 직접 응답했습니다. 클라이언트는 이미 연결되어 있으며 이 요청에 비용은 들지 않았습니다.`, + probesElsewhere: (n: number) => `게이트웨이가 연결 확인 요청 ${n}건에 직접 응답했습니다. 업스트림으로 보내지 않았습니다.`, + historyFailed: "요청 기록을 불러올 수 없습니다", + historyPartial: "요청 기록을 불러올 수 없어 이후에 받은 요청만 표시합니다.", + columns: "열 설정", + compactColumns: "간단히 보기", + resetColumns: "열 초기화", + pinColumn: (name: string) => `「${name}」 열 고정`, + unpinnedColumn: "고정하지 않음", + pinColumnLeft: "왼쪽에 고정", + pinColumnRight: "오른쪽에 고정", + moveColumnUp: (name: string) => `「${name}」 열을 앞으로 이동`, + moveColumnDown: (name: string) => `「${name}」 열을 뒤로 이동`, + requestedModel: (name: string) => `요청한 모델: ${name}`, + sentModel: (name: string) => `업스트림에 보낸 모델: ${name}`, + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `첫 토큰 ${ttft}`, `전체 ${total}`, `생성 ${gen}`, ...(speed != null ? [`생성 속도 ${speed}토큰/초`] : []), + ], + liveSpeedTip: (n: string) => `현재 생성 속도 ${n}토큰/초`, + keyTip: (key: string) => `키 ${key}`, + appTip: (app: string) => `앱 ${app}(요청 헤더 기반 추정)`, + fromPeer: (ip: string) => `보낸 주소: ${ip}`, + promptTip: (n: string) => `입력 합계 ${n}`, + promptParts: (input: string, read: string, write: string) => `캐시되지 않은 입력 ${input} · 캐시 읽기 ${read} · 캐시 쓰기 ${write}`, + outputTip: (n: string) => `출력 ${n}`, + uploadTip: (shown: string) => `전송 ${shown}`, + downloadTip: (shown: string) => `수신 ${shown}`, + rowActions: (id: number) => `요청 #${id} 작업`, + openDetails: "세부 정보 열기", + onlyUpstream: (name: string) => `업스트림 ${name}만 표시`, + onlyClient: (name: string) => `키 ${name}만 표시`, + copyId: "요청 ID 복사", + copyRow: "행 복사", + cancelled: "취소됨", + aborted: "중단됨", + queued: "대기 중", + retrying: "다시 시도 중", + queuedTip: (names: string[], at: string) => `${names.join(", ")}의 여유를 기다리는 중입니다. 최대 ${at}까지 대기합니다.`, + retryingTip: (names: string[], at: string) => `${names.join(", ")}에 다시 시도 중입니다. 최대 ${at}까지 대기합니다.`, + aliasTip: (model: string, upstream: string, sent: string) => `${model}은(는) 별칭입니다. ${upstream}에는 ${sent}(으)로 보냈습니다.`, + pinned: "고정", + pinnedTip: (rule: string, upstream: string, sent: string) => `규칙 「${rule}」에 따라 ${upstream}에 보낼 모델을 ${sent}(으)로 고정했습니다.`, + redactedTip: (items: string[]) => `전송 전에 대체함: ${items.join(", ")}`, + redacted: (n: number) => `가림 ${n}건`, + secretsTip: (items: string[]) => `인증 정보가 포함된 채로 전송함: ${items.join(", ")}`, + withSecrets: (n: number) => `인증 정보 ${n}건`, + stripped: "삭제됨", + strippedTip: (rules: string[]) => `다음 콘텐츠 규칙과 일치하는 텍스트를 삭제했습니다: ${rules.join(", ")}`, + contentReplaced: "대체됨", + contentReplacedTip: (rules: string[]) => `다음 콘텐츠 규칙과 일치하는 텍스트를 대체했습니다: ${rules.join(", ")}`, + sentConverted: (formats: string) => `형식을 변환하여 전송했습니다: ${formats}.`, + droppedFields: (fields: string[]) => `\n\n대상 형식에서 지원하지 않아 제외한 필드: ${fields.join(", ")}`, + noneDropped: "\n제외한 필드가 없습니다.", + converted: "변환됨", + convertedDropped: (n: number) => `필드 ${n}개 제외`, + pluginChangedTip: "플러그인이 수정했습니다. 요청 세부 정보에서 변경 전후를 비교할 수 있습니다.", + blocked: "차단됨", + suspicious: "의심스러운 호출", + estimatedCancelled: "응답이 끝나기 전에 클라이언트 연결이 끊겼습니다. 연결이 끊기기 전까지의 출력만 집계되어 실제 비용이 더 높을 수 있습니다.", + estimatedFailed: "응답이 완료되기 전에 중단되었습니다. 중단 전까지의 출력만 집계되어 실제 비용이 더 높을 수 있습니다.", + estimatedBorrowed: "가격표에 이 업스트림의 단가가 없어 다른 플랫폼의 동일한 모델 단가로 계산했습니다.", + }, + es: { + idle: "Inactivo", + inFlight: "en curso", + latest: "Última", + requestsUnit: (n: number) => (n === 1 ? "solicitud" : "solicitudes"), + failedUnit: (_n: number) => "Falló", + recent: (n: ReactNode) => <>{n} en los últimos 30 minutos, + sparkLabel: (n: number, failed: number) => `${count(n, "solicitud", "solicitudes")} en los últimos 30 minutos${failed > 0 ? `, ${failed} falló` : ""}`, + sparkBar: (at: string, n: number, failed: number) => n === 0 ? `${at} · Ninguna solicitud` : `${at} · ${count(n, "solicitud", "solicitudes")}${failed > 0 ? `, ${failed} falló` : ""}`, + viewLabel: "Ver", + viewRequests: "Solicitudes", + viewSessions: "Sesiones", + search: `Ruta, clave, del proveedor, error... ${modKey}${isMac ? "" : "+"}F`, + failedOnly: "Falló solamente", + unpricedOnly: "Únicamente sin precio", + allClients: "Todas las teclas", + allUpstreams: "Todos los proveedores", + allModels: "Todos los modelos", + shownOf: (shown: number, total: number) => `${shown} / ${count(total, "solicitud", "solicitudes")}`, + clear: "Limpiar", + searchContent: "Contenido de la búsqueda", + searchContentTip: "También buscar el contenido de las solicitudes y respuestas", + found: (n: number) => `${n} encontrado`, + searchingOlder: "Buscando registros anteriores…", + searchingContent: "Buscando contenido…", + searchedTo: (at: string) => `Buscar de nuevo a ${at}`, + searchedAll: "Búsqueda de todos los registros", + searchMore: "Buscar más", + searchFailed: (why: string) => `Falló la búsqueda: ${why}`, + bodiesSince: (ms: number) => `Las cargas útiles se guardan de ${new Date(ms).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" })}; las solicitudes anteriores no se corresponden con el contenido.`, + noBodies: "No se guardan cargas útiles; las solicitudes no se corresponden con el contenido.", + hitRequest: "Solicitud", + hitAnswer: "Respuesta", + noUpstreams: "No hay ninguna configuración anterior todavía", + listening: (addr: ReactNode) => (<>La puerta está escuchando. {addr}. Las peticiones pueden ser reenviadas una vez que se configura un curso previo.), + goToUpstreams: "Ir hacia arriba", + noMatchTitle: "No hay solicitudes coincidentes", + noMatch: (n: number) => n === 1 + ? "1 petición registrada; no coincide con los filtros actuales." + : `${n} solicitudes registradas; ninguna coincide con los filtros actuales.`, + noMatchSearched: (at: string | null) => at === null + ? "Todos los registros buscados; ninguno coincide con los filtros actuales." + : `Buscar de nuevo a ${at}; nada coincide con los filtros actuales.`, + clearFilters: "Limpiar filtros", + emptyTitle: "Todavía no hay solicitudes.", + pointClients: (endpoint: ReactNode) => (<>Establecer el punto final del cliente a {endpoint} y utilizar una clave de cliente que comienza con tw-.), + appearHere: "Las solicitudes aparecen aquí una vez recibidas.", + copyAddress: "Copiar dirección", + goToClients: "Ir a los clientes", + addressCopied: "Dirección de la pasarela copiada", + probesAnswered: (n: number) => n === 1 + ? "1 client probe was answered locally. A client is already connected to the gateway; the probe incurred no cost." + : `${n} las sondas del cliente fueron respondidas localmente. Un cliente ya está conectado a la puerta de entrada; estas sondas incurrieron en ningún costo.`, + probesElsewhere: (n: number) => n === 1 + ? "Además, 1 sonda cliente fue respondida localmente por la puerta de entrada y no enviada a un río." + : `Además, ${n} las sondas de clientes fueron contestadas localmente por la puerta de entrada y no enviadas a una corriente corriente.`, + historyFailed: "No se pudo cargar el registro de peticiones", + historyPartial: "El registro de peticiones no se pudo cargar. Sólo las solicitudes recibidas desde entonces se muestran a continuación.", + columns: "Columnas", + compactColumns: "Vista compacta", + resetColumns: "Reiniciar columnas", + pinColumn: (name: string) => `Pin ${name} columna`, + unpinnedColumn: "Sin fijar", + pinColumnLeft: "Pin izquierda", + pinColumnRight: "Pin derecha", + moveColumnUp: (name: string) => `Mover ${name} columna anterior`, + moveColumnDown: (name: string) => `Mover ${name} columna más adelante`, + requestedModel: (name: string) => `Solicitado: ${name}`, + sentModel: (name: string) => `Expedido del proveedor: ${name}`, + status: "Estado", + time: "Hora", + client: "Clave", + model: "Modelo", + upstream: "Proveedor", + latency: "Latencia", + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `Primer token ${ttft}`, + `Total ${total}`, + `Generación ${gen}`, + ...(speed != null ? [`Velocidad ${speed} tokens/s`] : []), + ], + liveSpeedTip: (n: string) => `Velocidad actual ${n} tokens/s`, + cost: "Coste", + keyTip: (key: string) => `Clave ${key}`, + appTip: (app: string) => `App ${app} (afirmado de las cabeceras de la solicitud)`, + fromPeer: (ip: string) => `de ${ip}`, + promptTip: (n: string) => `Total de entradas ${n}`, + promptParts: (input: string, read: string, write: string) => `Entrada sin caché ${input} · Caché lee ${read} · El caché escribe ${write}`, + outputTip: (n: string) => `Producto ${n}`, + uploadTip: (shown: string) => `Cargar ${shown}`, + downloadTip: (shown: string) => `Descargar ${shown}`, + rowActions: (id: number) => `Acciones para la solicitud #${id}`, + openDetails: "Abrir detalles", + onlyUpstream: (name: string) => `Mostrar solo del proveedor ${name}`, + onlyClient: (name: string) => `Mostrar solo la tecla ${name}`, + copyId: "Copiar el ID de solicitud", + copyRow: "Copiar fila", + failed: "Error", + cancelled: "Cancelado", + aborted: "Abortado", + queued: "En cola", + retrying: "Reintentar", + queuedTip: (names: string[], at: string) => `En fila para ${names.join(", ")}. Espera hasta ${at} como máximo.`, + retryingTip: (names: string[], at: string) => `Reintentar ${names.join(", ")}. Espera hasta ${at} como máximo.`, + aliasTip: (model: string, upstream: string, sent: string) => `${model} es un alias; el modelo enviado a ${upstream} es ${sent}.`, + pinnedTip: (rule: string, upstream: string, sent: string) => `La regla “${rule}” fija el modelo enviado a ${upstream}: ${sent}.`, + redactedTip: (items: string[]) => `Reemplazado antes de enviar: ${items.join(", ")}`, + redacted: (n: number) => `Redactado ${n}`, + secretsTip: (items: string[]) => `Enviado como está, con credenciales en él: ${items.join(", ")}`, + withSecrets: (n: number) => `Credenciales ${n}`, + stripped: "Suprimido", + strippedTip: (rules: string[]) => `Se suprimió el texto correspondiente a estas reglas de contenido: ${rules.join(", ")}`, + contentReplaced: "Reemplazado", + contentReplacedTip: (rules: string[]) => `El texto que coincide con estas reglas de contenido se sustituyó por el texto siguiente: ${rules.join(", ")}`, + sentConverted: (formats: string) => `Enviado después de la conversión de formato: ${formats}.`, + droppedFields: (fields: string[]) => `\n\nCampos caídos porque el formato de destino no los soporta: ${fields.join(", ")}`, + noneDropped: "\nNo se tiraron campos.", + converted: "Convertido", + convertedDropped: (n: number) => (n === 1 ? "1 campo caído" : `${n} Campos caídos`), + pluginChanged: "Complemento", + pluginChangedTip: "Cambiado por un plugin. Compare antes y después en los detalles de la solicitud.", + blocked: "Bloqueado", + suspicious: "Llamada sospechosa", + estimatedCancelled: "El cliente se desconectó antes de que la respuesta terminara. El uso de salida se cuenta hasta la desconexión, por lo que el costo real puede ser mayor.", + estimatedFailed: "La respuesta se interrumpió antes de terminar. El uso de la salida se cuenta hasta la interrupción, por lo que el costo real puede ser más alto.", + estimatedBorrowed: "La hoja de precios no tiene precio para este upstream; la cantidad se estima a partir del precio del mismo modelo en otra plataforma.", + }, + }, ); diff --git a/src/traffic/abort.i18n.ts b/src/traffic/abort.i18n.ts index 185b43c8..041775dc 100644 --- a/src/traffic/abort.i18n.ts +++ b/src/traffic/abort.i18n.ts @@ -20,4 +20,22 @@ export const abortText = messages( confirm: "Abort", failed: "Not aborted", }, + { + "zh-Hant": { + abortRequest: "中止請求", + abortSession: "中止會話", + title: "中止會話", + body: (n: number) => `此會話中正在進行的 ${n} 個請求將立即停止,用戶端會收到錯誤。已完成的請求不受影響。`, + }, + es: { + abortRequest: "Abortar solicitud", + abortSession: "Abortar sesión", + title: "Abortar sesión", + body: (n: number) => n === 1 + ? "La solicitud en curso en esta sesión se detiene inmediatamente, y su cliente recibe un error. Las solicitudes terminadas no se ven afectadas." + : `Las ${n} solicitudes en curso en esta sesión se detienen inmediatamente, y sus clientes reciben un error. Las solicitudes terminadas no se ven afectadas.`, + confirm: "Abortar", + failed: "Sin abortar", + }, + }, ); diff --git a/src/traffic/drawer/Content.i18n.ts b/src/traffic/drawer/Content.i18n.ts index 38b0e7c4..2a5af017 100644 --- a/src/traffic/drawer/Content.i18n.ts +++ b/src/traffic/drawer/Content.i18n.ts @@ -93,4 +93,68 @@ export const contentText = messages( noHead: "Not sent yet", liveFailed: (why: string) => `Live content is unavailable: ${why}`, }, + { + "zh-Hant": { + views: { parsed: "解析", raw: "封包記錄" }, + viewsLabel: "內容的顯示方式", + redactedRecord: "請求頭和正文在記錄時會再次脫敏,此處的佔位符不一定發給了上游。傳送前實際替換的位置見安全記錄。", + copyRecord: "複製記錄", + sides: { client: "用戶端一側", upstream: "上游一側" }, + sidesLabel: "封包的一側", + attemptsLabel: "嘗試", + follow: "跟隨最新", + live: "實時", + request: "請求", + waiting: "等待上游回應", + messages: (n: number) => `${n.toLocaleString()} 條訊息`, + tools: (n: number) => `${n.toLocaleString()} 個工具`, + events: (n: number) => `${n.toLocaleString()} 個事件`, + earlierEvents: (n: number) => `前 ${n.toLocaleString()} 個事件`, + showEarlierEvents: "顯示全部事件", + unknownFormat: "無法識別此請求的格式,內容見「封包記錄」", + requestCut: "請求過大,僅儲存了開頭部分,無法解析,內容見「封包記錄」", + requestUnreadable: "請求正文無法解析,內容見「封包記錄」", + responseUnreadable: "回答的格式無法識別,內容見「封包記錄」", + noAnswer: "回答中沒有可顯示的內容", + sameAsClient: "正文與用戶端一側相同", + afterPluginsLater: "正文為外掛改寫後的版本,請求結束後可檢視", + attemptNotKept: "失敗的嘗試不保留正文", + noHead: "尚未發出", + liveFailed: (why: string) => `無法顯示實時內容:${why}`, + }, + ko: { + request: "요청", + }, + es: { + views: { parsed: "Analizado", raw: "Grabado HTTP" }, + viewsLabel: "Cómo se muestra el contenido", + redactedRecord: "Los encabezados y los cuerpos se redactan de nuevo para que conste. Es posible que no se haya enviado un marcador de posición. Vea los registros de seguridad de lo que fue reemplazado antes de enviar.", + copyRecord: "Copiar registro", + sides: { client: "Lado cliente", upstream: "Lado ascendente" }, + sidesLabel: "Lado del intercambio", + attemptsLabel: "Intento", + follow: "Seguir la última", + live: "Vivo", + request: "Solicitud", + response: "Respuesta", + receiving: "Recepción", + waiting: "Esperando por el río arriba", + messages: (n: number) => count(n, "mensaje", "mensajes"), + tools: (n: number) => count(n, "herramienta", "herramientas"), + toolsLabel: "Herramientas", + events: (n: number) => count(n, "evento", "eventos"), + earlierEvents: (n: number) => (n === 1 ? "1 evento anterior" : `${n.toLocaleString()} Hechos anteriores`), + showEarlierEvents: "Mostrar todos los eventos", + unknownFormat: "No se reconoce el formato de esta solicitud; véase HTTP grabado", + requestCut: "La solicitud era demasiado grande para guardarla en su totalidad y no puede ser analizada; vea HTTP grabado para el comienzo", + requestUnreadable: "El cuerpo de solicitud no puede ser analizado; vea el HTTP grabado", + responseUnreadable: "No se reconoce el formato de respuesta; ver HTTP grabado", + noAnswer: "La respuesta no tiene nada que mostrar", + sameAsClient: "El cuerpo es el mismo que en el lado del cliente", + afterPluginsLater: "El cuerpo es la versión reescrita por plugins; se puede ver cuando termina la solicitud", + attemptNotKept: "No se conservan los cuerpos de intentos fallidos", + noHead: "No se ha enviado aún", + liveFailed: (why: string) => `El contenido en vivo no está disponible: ${why}`, + }, + }, ); diff --git a/src/traffic/drawer/RequestDrawer.i18n.tsx b/src/traffic/drawer/RequestDrawer.i18n.tsx index 0e88c7b6..29af2ec3 100644 --- a/src/traffic/drawer/RequestDrawer.i18n.tsx +++ b/src/traffic/drawer/RequestDrawer.i18n.tsx @@ -407,4 +407,294 @@ export const requestDrawerText = messages( duration: "Total time", replayPending: "Replay is available when the request ends", }, + { + "zh-Hant": { + title: "請求詳情", + requestNo: (id: number) => `第 ${id} 號請求`, + loadFailed: "請求詳情讀取失敗", + tabTimeline: "時間線", + tabPayload: "內容", + details: "說明", + ttfb: "首位元組", + totalTime: "總耗時", + generationTime: "生成用時", + answeredLocally: "本地應答", + client: "金鑰", + app: "應用", + guessed: "(按請求頭推測)", + peer: "來源", + path: "路徑", + conversion: "格式轉換", + dropped: "丟棄欄位", + plugins: "外掛", + droppedTip: "目標格式不支援這些欄位,傳送前已移除。", + sessionLog: "會話日誌", + sessionLogNote: "DeepSeek Harness 隨請求附帶的整段對話記錄。發往 DeepSeek 以外的上游之前,閘道器已將其去除。", + status: "狀態", + inProgress: "進行中", + failed: "失敗", + aborted: "手動中止", + idleTimeout: "無回應超時", + cancelled: "已取消:用戶端在回應結束前斷開連線", + upload: "上傳", + download: "下載", + viaProxy: (name: string) => `經 ${name}`, + notSentSuffix: "(未傳送)", + matchedRule: "命中規則", + denied: "拒絕", + viaGroup: "經過策略組", + alias: "別名", + aliasNote: "按上游換成對應的模型名", + pinnedBy: (rule: string) => `由規則「${rule}」指定,模型名原樣發出`, + rewrittenBy: "引數改寫", + continuity: "對話延續", + heldRoute: "沿用本輪開頭的路由決定", + stayedTurn: "同一輪內留在上次回答的上游", + stayedCache: "上次回答的快取仍有效,留在該上游", + stayedSealed: "對話帶有該上游加密的內容,只能送回該上游", + deniedBy: "拒絕規則", + attempts: "嘗試鏈", + queued: (s: string) => `排隊 ${s} 秒`, + retry: (n: number) => `第 ${n} 次重試`, + abandonedEstimate: (n: string) => `輸入約 ${n} token`, + mayBeBilled: "上游可能已計費", + mayBeBilledTip: "上游是否收取這部分費用無法得知,此請求的費用不含這部分。", + sentModel: (model: string) => `規則改寫了模型名:這一跳發給上游的是 ${model},費用按它計算`, + sentByAlias: (upstream: string, model: string) => `別名:這一跳發給 ${upstream} 的是 ${model},費用按它計算`, + sentPinned: (upstream: string, model: string) => `指定模型:這一跳發給 ${upstream} 的是 ${model},費用按它計算`, + sentByPlugin: (model: string) => `外掛改寫了模型名:這一跳發給上游的是 ${model},費用按它計算`, + sentOther: (model: string) => `這一跳發給上游的是 ${model},費用按它計算`, + failover: (failed: number) => `已發生故障轉移:前 ${failed} 個上游失敗,已自動切換至下一個上游。`, + failoverDenied: (failed: number, rule: string) => `已發生故障轉移:前 ${failed} 個上游失敗,切換至下一個上游後,規則「${rule}」拒絕了此請求,未向該上游傳送。`, + deniedAfterPick: (rule: string) => `選定上游後,規則「${rule}」拒絕了此請求,未發往任何上游。`, + deniedBeforePick: (rule: string) => `選定上游之前,規則「${rule}」已拒絕此請求,未發往任何上游。`, + unavailable: "規則選中的上游均無法服務此請求,未發往任何上游。", + model: "請求的模型無法使用,未發往任何上游。", + unrouted: "未能為此請求選出去向,未發往任何上游。", + switched: (n: number) => `已自動切換上游:前 ${n} 次嘗試未接下此請求。`, + waited: (n: number) => `前 ${n} 次嘗試未接下此請求,上游恢復後已發出。`, + retried: (n: number) => `前 ${n} 次嘗試未接下此請求,已自動重試。`, + limited: "閘道器金鑰已達到用量上限,此請求未發往任何上游。", + busy: "上游均已達到併發上限,等待期間沒有空出位置,此請求未發往任何上游。", + busyAfterTries: (n: number) => `發出的 ${n} 次嘗試未成功,其餘上游均已達到併發上限,等待期間沒有空出位置。`, + throttled: "上游均因返回 429 而暫停,等待期間沒有恢復,此請求未被接下。", + throttledAfterTries: (n: number) => `發出的 ${n} 次嘗試未成功,其餘上游均因返回 429 而暫停,等待期間沒有恢復。`, + full: "上游均已達到各自的用量上限,此請求未被接下。", + fullAfterTries: (n: number) => `發出的 ${n} 次嘗試未成功,其餘上游均已達到各自的用量上限。`, + timeout: "等待期間沒有上游恢復可用,此請求未被接下。", + timeoutAfterTries: (n: number) => `發出的 ${n} 次嘗試未成功,等待期間其餘上游均未恢復可用。`, + noRouting: "此請求由閘道器本地應答,未經過路由。", + noAttempts: "此請求沒有上游嘗試記錄。", + payloadViews: { compare: "對比", after: "外掛改寫後" }, + afterPluginsSentBy: (n: number, upstream: string) => `外掛改寫後的請求:第 ${n} 跳發往 ${upstream} 的那一份`, + notSaved: "未儲存", + afterEnd: "請求結束後可檢視", + pastRetentionTip: "此記錄已超過保留期限。", + requestNotKeptTip: "請求正文未保留。", + responseNotKeptTip: "回應正文未保留。", + truncated: "僅儲存開頭部分", + collapse: "摺疊", + showAll: "展開全部", + usagePending: "請求結束後可檢視用量和費用", + cancelledBeforeUsage: "用戶端在上游報告用量前斷開連線", + failedBeforeUsage: "請求在上游報告用量前失敗", + noUsage: "上游未報告用量", + noUsageTip: "部分上游的回應不含用量欄位。缺少用量時,無法得知此次呼叫的消耗,也無法計算費用。", + input: "新輸入", + output: "輸出", + cacheReads: "快取讀取", + cacheWrites: "快取寫入", + inputMix: (read: string, input: string, write: string) => `快取讀取 ${read},新輸入 ${input},快取寫入 ${write}`, + cost: "費用", + free: "不計費", + unpriced: "無法計價:該模型未定價", + estimatedCancelled: "估算值,輸出用量計至用戶端斷開", + estimatedInterrupted: "估算值,輸出用量計至回應中斷", + priceSource: "價格來源", + replayIntro: (em: (x: ReactNode) => ReactNode) => (<>將{em("記錄中的請求")}傳送至另一個上游,並排對比結果), + asIsTip: "使用儲存時已脫敏的請求本文,其中的佔位符和遮蔽後的值也會一併傳送。", + asIs: "記錄的內容", + upstreamsFailed: "上游列表讀取失敗", + estimateCost: "預估費用", + quote: (upstream: ReactNode, bytes: number, tokens: number) => (<>將向 {upstream} 傳送 {bytes} 位元組,約 {tokens} 個輸入 token。), + willRedact: "傳送前將按金鑰與隱私的規則替換憑據。", + pricingDate: (date: string) => `價目表日期 ${date}。`, + confirmSend: "確認傳送", + originalColumn: (upstream: string) => `${upstream}(原請求)`, + duration: "耗時", + replayPending: "請求結束後可重放", + }, + ko: { + tabRouting: "라우팅", + tabUsage: "사용량", + details: "세부 정보", + upstream: "업스트림", + client: "키", + peer: "출처", + security: "보안", + plugins: "플러그인", + attemptGroup: (n: number, upstream: string | null) => (upstream ? `Attempt ${n} · ${upstream}` : `${n}번째 시도`), + status: "상태", + inProgress: "진행 중", + failed: "실패", + tokens: "토큰", + reason: "원인", + output: "출력", + cost: "비용", + }, + es: { + title: "Detalles de la solicitud", + requestNo: (id: number) => `Solicitud #${id}`, + loadFailed: "No se pudo cargar la solicitud", + tabTimeline: "Calendario", + tabRouting: "Enrutamiento", + tabPayload: "Contenido", + tabUsage: "Uso", + tabReplay: "Repetir", + details: "Detalles", + ttft: "Primer token", + speed: "Velocidad", + totalTime: "Tiempo total", + generationTime: "Generación", + upstream: "Proveedor", + answeredLocally: "Respuestas locales", + client: "Clave", + guessed: " (afirmado en las cabeceras de la solicitud)", + peer: "Origen", + path: "Ruta", + conversion: "Conversión", + dropped: "Caída", + security: "Seguridad", + plugins: "Complementos", + attemptGroup: (n: number, upstream: string | null) => (upstream ? `Intento ${n} · ${upstream}` : `Intento ${n}`), + droppedTip: "El formato de destino no admite estos campos; fueron eliminados antes de enviarlos.", + sessionLog: "Registro de la sesión", + sessionLogNote: "Toda la conversación, unida por DeepSeek Harness. La puerta de entrada lo elimina antes de que una solicitud vaya a un río arriba distinto de Deepseek.", + status: "Estado", + inProgress: "En curso", + failed: "Error", + cancelledShort: "Cancelado", + aborted: "Abortado", + idleTimeout: "Sin respuesta", + cancelled: "Cancelado: el cliente se desconectó antes de que la respuesta terminara", + egress: "Egreso", + upload: "Subir", + download: "Descargar", + waiting: "Esperando el primer token", + generating: "Generando", + timingLabel: (ttft: string, gen: string) => `Esperando el primer token ${ttft}, generando ${gen}`, + notSentSuffix: " (no enviado)", + route: "Ruta", + matchedRule: "Regla armonizada", + denied: "Denegado", + viaGroup: "A través del grupo", + aliasNote: "Resuelto al nombre del modelo de cada uno de ellos", + pinnedModel: "Modelo de fijación", + pinnedBy: (rule: string) => `Establecer por regla “${rule}”; el nombre del modelo se envía como es`, + rewrittenBy: "Reescrito por", + continuity: "Conversación", + heldRoute: "Mantuvo la ruta decidida al inicio de este turno", + stayedTurn: "Se quedó con la corriente que respondió antes en este turno", + stayedCache: "Permaneció con el cursor que respondió por última vez, mientras que su caché es caliente", + stayedSealed: "Enviado de vuelta al contenido cifrado en esta conversación", + deniedBy: "Denegado por", + reason: "Motivo", + attempts: "Intentos", + queued: (s: string) => `Encolado ${s} s`, + retry: (n: number) => `Reintentar ${n}`, + backoff: (s: string) => `Esperado ${s} s`, + abandonedEstimate: (n: string) => `Acerca de ${n} tokens de entrada`, + mayBeBilled: "puede haber sido facturado por el", + mayBeBilledTip: "Se desconoce si la carga ascendente de estos tokens no está incluida en el coste de esta solicitud.", + sentModel: (model: string) => `Una regla reescribió el modelo: este intento enviado ${model}, y el costo es el precio por él`, + sentByAlias: (upstream: string, model: string) => `Alias: este intento enviado ${model} a ${upstream}, y el costo es calculado por él`, + sentPinned: (upstream: string, model: string) => `Modelo clavado: este intento enviado ${model} a ${upstream}, y el costo es valorado por él`, + sentByPlugin: (model: string) => `Un plugin reescribió el modelo: este intento enviado ${model}, y el costo es el precio por él`, + sentOther: (model: string) => `Este intento enviado ${model}, y el costo es calculado por él`, + failover: (failed: number) => failed === 1 + ? "Ocurrió un fallo: la primera versión anterior falló, y la solicitud se cambió a la siguiente versión anterior automáticamente." + : `Ocurrió un fallo: las primeras ${failed} del proveedor fallaron, y la solicitud fue cambiada automáticamente a la siguiente del proveedor.`, + failoverDenied: (failed: number, rule: string) => failed === 1 + ? `Ocurrió un fallo: el primer paso anterior falló, y después del cambio al siguiente paso, la regla “${rule}” denegó la solicitud antes de que se enviara allí.` + : `Ocurrió un fallo: los primeros ${failed} del proveedor fallaron, y después del cambio a la siguiente del proveedor, la regla “${rule}” denegó la solicitud antes de que fuera enviada allí.`, + deniedAfterPick: (rule: string) => `La regla “${rule}” denegó esta solicitud una vez que se eligió el curso anterior; no se envió a ningún curso anterior.`, + deniedBeforePick: (rule: string) => `La regla “${rule}” denegó esta solicitud antes de que se eligiera un curso anterior; no se envió a ningún curso anterior.`, + unavailable: "Ninguna regla seleccionada puede servir a esta solicitud; no fue enviada a ninguna instrucción.", + model: "No se puede utilizar el modelo solicitado; la solicitud no se envió a ninguna fuente.", + unrouted: "No se pudo elegir ningún destino para esta solicitud; no se envió a ninguna fuente.", + switched: (n: number) => n === 1 + ? "Conmutado de forma automática: el primer intento no aceptó esta petición." + : `Conmutado hacia arriba automáticamente: los primeros intentos ${n} no aceptaron esta petición.`, + waited: (n: number) => n === 1 + ? "En el primer intento no se aceptó esta solicitud; se envió una vez que el curso previo estaba disponible de nuevo." + : `Los primeros ${n} intentos no aceptaron esta petición; se envió una vez que el curso previo estaba disponible de nuevo.`, + retried: (n: number) => n === 1 + ? "El primer intento no tomó esta petición; fue juzgado automáticamente." + : `Los primeros ${n} intentos no tomaron esta petición; fue juzgado automáticamente.`, + limited: "La clave de entrada había alcanzado un límite de uso; esta solicitud no se envió a ninguna fuente.", + busy: "Todas las del proveedor estaban en su límite de concurrencia y ninguna fue liberada a tiempo; esta solicitud no fue enviada a ninguna del proveedor.", + busyAfterTries: (n: number) => n === 1 + ? "El intento enviado no tuvo éxito, y las otras del proveedor estaban en sus límites de concurrencia sin que nadie se liberara a tiempo." + : `Los ${n} intentos enviados no tuvieron éxito, y las otras del proveedor estaban en sus límites de concurrencia, sin que ninguno se liberara a tiempo.`, + throttled: "Cada del proveedor se detuvo después de responder 429 y ninguna se reanudó a tiempo; esta petición no fue tomada.", + throttledAfterTries: (n: number) => n === 1 + ? "El intento enviado no tuvo éxito, y las otras del proveedor se detuvieron después de responder 429 sin que se reanudara a tiempo." + : `Los ${n} intentos enviados no tuvieron éxito, y las otras del proveedor fueron pausadas después de responder a 429 sin que ninguna se reanudara a tiempo.`, + full: "Todas las del proveedor estaban en uno de sus límites de uso; esta petición no fue tomada.", + fullAfterTries: (n: number) => n === 1 + ? "El intento enviado no tuvo éxito, y las otras del proveedor estaban en sus límites de uso." + : `Los ${n} intentos enviados no tuvieron éxito, y las otras del proveedor estaban en sus límites de uso.`, + timeout: "No se pudo acceder a tiempo a ninguna fase anterior; esta solicitud no se hizo efectiva.", + timeoutAfterTries: (n: number) => n === 1 + ? "El intento enviado no tuvo éxito, y ninguna de las otras del proveedor estuvo disponible a tiempo." + : `Los ${n} intentos enviados no tuvieron éxito, y ninguna de las otras del proveedor llegó a estar disponible a tiempo.`, + noRouting: "La puerta de entrada respondió a esta petición localmente; no pasó por rutas.", + routingPending: "El enrutamiento no ha terminado todavía", + noAttempts: "No se registraron intentos previos para esta solicitud.", + payloadViews: { compare: "Comparar", after: "Después de los complementos" }, + afterPluginsSentBy: (n: number, upstream: string) => `Después de plugins: qué intento ${n} enviado a ${upstream}`, + notSaved: "No guardado", + afterEnd: "Disponible cuando finalice la solicitud", + pastRetentionTip: "Este registro ha pasado su período de retención.", + requestNotKeptTip: "El cuerpo de solicitud no se mantuvo.", + responseNotKeptTip: "El cuerpo de respuesta no se mantuvo.", + truncated: "sólo el principio se salvó", + collapse: "Colapso", + showAll: "Mostrar todo", + usagePending: "Uso y costo están disponibles cuando la solicitud termina", + cancelledBeforeUsage: "El cliente se desconectó antes del uso informado", + failedBeforeUsage: "La solicitud falló antes del uso informado", + noUsage: "En la fase anterior no se informó del uso", + noUsageTip: "Algunas respuestas anteriores no incluyen campos de uso. Sin uso, se desconoce el consumo de esta llamada y no se puede calcular su costo.", + input: "Entrada sin encallar", + output: "Salida", + cacheReads: "Caché lee", + cacheWrites: "Cache escribe", + inputMix: (read: string, input: string, write: string) => `Caché lee ${read}, entrada sin caché ${input}, caché escribe ${write}`, + cost: "Coste", + free: "Libre", + unpriced: "Sin precio: este modelo no tiene precio", + estimatedCancelled: "estimado; uso de salida contado hasta la desconexión del cliente", + estimatedInterrupted: "estimado; el uso de la salida se contabilizó hasta la interrupción", + estimated: "Estimación", + priceSource: "Fuente del precio", + replayIntro: (em: (x: ReactNode) => ReactNode) => (<> + Enviar {em("la solicitud registrada")} y comparar los resultados uno al lado del otro + ), + asIsTip: "Utiliza el cuerpo redactado para su almacenamiento, incluidos los marcadores de posición y los valores enmascarados.", + asIs: "Acerca de la solicitud almacenada", + upstreamsFailed: "No se pudo cargar las del proveedor", + estimateCost: "Costo estimado", + quote: (upstream: ReactNode, bytes: number, tokens: number) => (<> + {count(bytes, "byte", "bytes")} se enviará a {upstream}, sobre{" "} + {count(tokens, "token de entrada", "tokens de entrada")}. + ), + willRedact: "Las credenciales se sustituyen por los secretos y las reglas de privacidad antes de enviar.", + pricingDate: (date: string) => `Datos de la hoja de precios a partir de ${date}.`, + confirmSend: "Confirmar y enviar", + replayColumn: (upstream: string) => `${upstream} (reproducir)`, + duration: "Tiempo total", + replayPending: "La repetición está disponible cuando finaliza la solicitud", + }, + }, ); diff --git a/src/ui/calendar.tsx b/src/ui/calendar.tsx index 280720b6..ce49bc77 100644 --- a/src/ui/calendar.tsx +++ b/src/ui/calendar.tsx @@ -1,5 +1,10 @@ import * as React from "react" import { cn } from "@/lib/utils" +import { useLang } from "@/i18n" +import { ja } from "react-day-picker/locale/ja" +import { ko } from "react-day-picker/locale/ko" +import { es } from "react-day-picker/locale/es" +import { zhTW } from "react-day-picker/locale/zh-TW" import { DayPicker, getDefaultClassNames, @@ -16,7 +21,7 @@ function Calendar({ showOutsideDays = true, captionLayout = "label", buttonVariant = "ghost", - locale, + locale: localeProp, formatters, components, ...props @@ -24,6 +29,8 @@ function Calendar({ buttonVariant?: React.ComponentProps["variant"] }) { const defaultClassNames = getDefaultClassNames() + const lang = useLang() + const locale = localeProp ?? { ja, ko, es, "zh-Hant": zhTW, zh: undefined, en: undefined }[lang] return ( `Since ${date}`, sameLength: "period", }, + { + "zh-Hant": { + label: "時間範圍", + live: "實時", + preset: { "1d": "24 小時", "7d": "7 天", "30d": "30 天" }, + custom: "自定義", + sameLength: "等長區間", + }, + ja: { + label: "期間", + live: "リアルタイム", + preset: { "1d": "24 時間", "7d": "7 日間", "30d": "30 日間" }, + custom: "カスタム", + since: (date: string) => `${date} から`, + sameLength: "同じ長さの期間", + }, + es: { + label: "Rango temporal", + live: "Vivo", + preset: { "1d": "24 horas", "7d": "7 días", "30d": "30 días" }, + custom: "Personalizado", + since: (date: string) => `Desde ${date}`, + sameLength: "plazo", + }, + ko: { + label: "기간", + live: "실시간", + preset: { "1d": "24시간", "7d": "7일", "30d": "30일" }, + custom: "사용자 설정", + since: (date: string) => `${date} 이후`, + sameLength: "같은 길이의 기간", + }, + }, ); diff --git a/src/ui/range.tsx b/src/ui/range.tsx index a87eff67..3acf2b6f 100644 --- a/src/ui/range.tsx +++ b/src/ui/range.tsx @@ -5,7 +5,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover"; import { Segmented } from "@/ui/segmented"; import { StatusDot } from "@/ui/status-dot"; import { bucketStart } from "@/format"; -import { textOf, useText } from "@/i18n"; +import { getLang, localeTag, textOf, useText } from "@/i18n"; import { rangeText } from "./range.i18n"; const HOUR = 3_600_000; @@ -132,7 +132,7 @@ export function customRange(d: Date): Range { ms: Math.max(60_000, Date.now() - d.getTime()), from: d.getTime(), get label() { - return textOf(rangeText).since(d.toLocaleDateString()); + return textOf(rangeText).since(d.toLocaleDateString(localeTag(getLang()))); }, get compare() { return textOf(rangeText).sameLength; @@ -156,7 +156,7 @@ export function dayRange(d: Date): Range { from, to, get label() { - return new Date(from).toLocaleDateString(); + return new Date(from).toLocaleDateString(localeTag(getLang())); }, get compare() { return textOf(rangeText).preset["1d"]; diff --git a/src/ui/ui.i18n.ts b/src/ui/ui.i18n.ts index 18ed8d4e..d04c44c8 100644 --- a/src/ui/ui.i18n.ts +++ b/src/ui/ui.i18n.ts @@ -27,4 +27,28 @@ export const uiText = messages( hide: "Hide", ignore: "Ignore", }, + { + "zh-Hant": { + loading: "讀取中…", + loadFailed: "讀取失敗", + retry: "重試", + undo: "撤銷", + undone: "已撤銷", + show: "顯示", + hide: "隱藏", + }, + ko: { + loadFailed: "불러올 수 없음", + retry: "다시 시도", + }, + es: { + loading: "Cargando…", + loadFailed: "No se pudo cargar", + retry: "Reintentar", + undo: "Deshacer", + show: "Mostrar", + hide: "Ocultar", + ignore: "Ignorar", + }, + }, ); diff --git a/src/updateFlow.test.ts b/src/updateFlow.test.ts index 761e46aa..ac1c9a27 100644 --- a/src/updateFlow.test.ts +++ b/src/updateFlow.test.ts @@ -1,6 +1,26 @@ import { describe, expect, it } from "vitest"; import { setLang } from "./i18n"; -import { canInstall, describeStep } from "./updateFlow"; +import { canInstall, describeStep, releaseNotesFor } from "./updateFlow"; + +describe("更新说明按界面语言选取", () => { + it("分别展示中文和英文,并保留 Markdown 的换行", () => { + const notes = { zh: " - 修复路由\n- 改进更新\n", en: " - Fixed routing\n- Improved updates\n" }; + expect(releaseNotesFor(notes, "zh")).toBe("- 修复路由\n- 改进更新"); + expect(releaseNotesFor(notes, "zh-Hant")).toBe("- 修复路由\n- 改进更新"); + expect(releaseNotesFor(notes, "en")).toBe("- Fixed routing\n- Improved updates"); + expect(releaseNotesFor(notes, "ja")).toBe("- Fixed routing\n- Improved updates"); + expect(releaseNotesFor(notes, "ko")).toBe("- Fixed routing\n- Improved updates"); + expect(releaseNotesFor(notes, "es")).toBe("- Fixed routing\n- Improved updates"); + }); + + it("旧清单只有中文时英文界面隐藏说明", () => { + const notes = { zh: "修复路由", en: null }; + expect(releaseNotesFor(notes, "zh")).toBe("修复路由"); + expect(releaseNotesFor(notes, "en")).toBeUndefined(); + expect(releaseNotesFor(notes, "ja")).toBeUndefined(); + expect(releaseNotesFor({ zh: " ", en: "Fixed routing" }, "zh")).toBeUndefined(); + }); +}); describe("谁能在窗口里直接装", () => { /** diff --git a/src/updateFlow.ts b/src/updateFlow.ts index 896624b1..6b7f035b 100644 --- a/src/updateFlow.ts +++ b/src/updateFlow.ts @@ -4,7 +4,7 @@ * 更新窗口和设置页都用它们。**判断在 Rust 里**(这一份怎么装上来的、 * 能不能自己装、该不该弹窗),这里只负责把 Rust 给的状态说成一句话。 */ -import { textOf } from "@/i18n"; +import { textOf, type Lang } from "@/i18n"; import { updateText } from "./Update.i18n"; /** @@ -29,14 +29,24 @@ export interface UpdateView { } /** 更新窗口要画的东西。 */ -export interface Offer { - version: string; +export interface Offer extends Found { current: string; install: Install; + notes: ReleaseNotes; /** Homebrew 那一档要执行的命令。由 Rust 给出,界面上不再写一遍 */ command?: string | null; } +export interface ReleaseNotes { + zh: string | null; + en: string | null; +} + +/** 中文界面读中文,其余读英文。旧清单可能缺一份。 */ +export function releaseNotesFor(notes: ReleaseNotes, lang: Lang): string | undefined { + return (lang === "zh" || lang === "zh-Hant" ? notes.zh : notes.en)?.trim() || undefined; +} + /** 按下安装之后走到了哪一步。 */ export type Step = | { step: "downloading" } diff --git a/src/upstreams/AccountPanel.i18n.tsx b/src/upstreams/AccountPanel.i18n.tsx index cdff5a01..3f6ffe87 100644 --- a/src/upstreams/AccountPanel.i18n.tsx +++ b/src/upstreams/AccountPanel.i18n.tsx @@ -121,4 +121,107 @@ export const accountPanelText = messages( "Signing in replaces the current key with a key from the account. Model scope, billing and other settings stay unchanged.", signIn: "Sign in", }, + { + "zh-Hant": { + expired: "授權未在有效期內完成", + cancelled: "登入已取消", + chatgptTitle: "使用 ChatGPT 帳號", + chatgptDesc: "登入 OpenAI 帳號,把 ChatGPT 訂閱額度作為一個上游使用。", + noticeOfficial: "ChatGPT 訂閱的用途是在 OpenAI 的官方用戶端中對話。用於其他用戶端不受 OpenAI 支援,帳號可能因此受限。", + noticeCredential: (where: string) => `登入得到的憑據儲存在${where}的配置檔案中,刪除該上游時一併吊銷。`, + zaiTitle: (site: string) => `使用 ${site} 帳號`, + zaiDesc: (site: string, other: string) => `登入帳號,把它的程式設計套餐額度作為一個上游使用。${site} 與 ${other} 是同一服務的兩個站點,帳號不通用。`, + noticeTheirPage: "授權頁由對方提供,頁面上顯示的是他們自己的用戶端名稱。", + noticeKey: "登入會在帳號中建立一把名為 thinkwatch 的 API 金鑰(已存在則直接使用),額度按該金鑰計入套餐。", + noticeKeyStorage: (where: string) => `得到的金鑰儲存在${where}的配置檔案中,與其他上游一同管理。`, + here: "本機", + understood: "已閱讀上述說明", + signInBrowser: "在瀏覽器中登入", + browserDesc: "在這臺電腦的瀏覽器中授權,完成後自動繼續。", + openPage: "開啟授權頁", + copyLink: "複製連結", + linkCopied: "已複製連結", + linkHint: "預設瀏覽器不是常用的那個時,複製到常用的瀏覽器中開啟", + signInDevice: "用裝置碼登入", + deviceDesc: "在任意裝置上開啟驗證網址,輸入裝置碼。", + getCode: "獲取裝置碼", + deviceInstead: "瀏覽器打不開或不方便時,改用裝置碼。", + useDevice: "改用裝置碼", + waiting: (min: number) => `等待瀏覽器中的授權 · ${min} 分鐘內有效`, + reopen: "重新開啟", + useBrowser: "改用瀏覽器登入", + zaiAfter: "授權完成後瀏覽器會停在對方的頁面上,可直接關閉。", + deviceTitle: "用裝置碼登入", + deviceDescLocal: "在任意瀏覽器開啟驗證網址並輸入裝置碼,完成後此處自動繼續。", + deviceDescRemote: (name: string) => `core 執行在 ${name} 上,瀏覽器登入無法回到這臺電腦。在任意瀏覽器開啟驗證網址並輸入裝置碼,完成後此處自動繼續。`, + verifyUrl: "驗證網址", + code: "裝置碼", + open: "開啟", + deviceWaiting: (min: number) => `等待輸入 · ${min} 分鐘內有效`, + newCode: "重新獲取", + deviceWarning: "只輸入這裡顯示的裝置碼;他人提供的裝置碼請勿輸入。", + doneTitle: "已登入", + reloginDone: (name: ReactNode) => <>已重新登入,上游 {name} 的憑據已更新。, + signedIn: "已登入", + siteAccount: (site: string) => `${site} 帳號`, + signedInTitle: (site: string) => `已登入 ${site} 帳號`, + signedInDesc: "金鑰由帳號登入取得,額度計入該帳號的程式設計套餐。", + relogin: "重新登入", + replaceTitle: (site: string) => `登入 ${site} 帳號`, + replaceDesc: "登入後,帳號中取得的金鑰替換當前的金鑰。模型範圍、計費方式等設定保持不變。", + signIn: "登入帳號", + }, + es: { + expired: "La autorización no se completó dentro del plazo", + cancelled: "Se canceló la inscripción", + chatgptTitle: "Usar una cuenta ChatGPT", + chatgptDesc: "Inicia sesión en una cuenta de OpenAI y utiliza su cuota de suscripción de ChatGPT como upstream.", + noticeOfficial: "Una suscripción de ChatGPT está destinada a chatear en los clientes oficiales de OpenAI. El uso en otros clientes no es compatible con OpenAI, y la cuenta puede ser restringida como resultado.", + noticeCredential: (where: string) => `La credencial obtenida al iniciar sesión se almacena en el archivo de configuraciónuración ${where}, y se revoca cuando se elimina el upstream.`, + zaiTitle: (site: string) => `Usar una cuenta ${site}`, + zaiDesc: (site: string, other: string) => `Inicia sesión en una cuenta y utiliza su cuota del plan de codificación como un principio. ${site} y ${other} son dos sitios de un servicio, y una cuenta funciona en uno de ellos solamente.`, + noticeTheirPage: "La página de autorización es de ellos, y nombra a su propio cliente.", + noticeKey: "Iniciar sesión crea una clave de API llamada thinkwatch en la cuenta, o utiliza la existente. La cuota se cuenta contra esa clave.", + noticeKeyStorage: (where: string) => `La clave obtenida al iniciar sesión se almacena en el archivo de configuraciónuración ${where} y se gestiona junto con las otras del proveedor.`, + here: "en este ordenador", + server: (name: string) => `el ${name}`, + understood: "Reconozca las notas anteriores", + signInBrowser: "Iniciar sesión con el navegador", + browserDesc: "Autorizar en un navegador en este equipo; el inicio de sesión continúa aquí una vez hecho.", + openPage: "Abrir la página de autorización", + copyLink: "Copiar enlace", + linkCopied: "Enlace copiado", + linkHint: "Si el navegador predeterminado no es el que se utiliza normalmente, copiar el enlace en ese navegador", + signInDevice: "Iniciar sesión con un código de dispositivo", + deviceDesc: "Abra la dirección de verificación en cualquier dispositivo e introduzca el código.", + getCode: "Obtener un código de dispositivo", + deviceInstead: "Cuando el navegador no se puede utilizar, inicie sesión con un código de dispositivo en su lugar.", + useDevice: "Usar un código de dispositivo en su lugar", + waiting: (min: number) => `Esperando autorización en el navegador · válida para ${min} min`, + reopen: "Reabrir", + useBrowser: "Usar el navegador en su lugar", + zaiAfter: "Después de la autorización, el navegador se queda en su página y simplemente puede ser cerrado.", + deviceTitle: "Iniciar sesión con un código de dispositivo", + deviceDescLocal: "Abra la dirección de verificación en cualquier navegador e introduzca el código del dispositivo. El inicio de sesión continúa aquí una vez que se haya hecho.", + deviceDescRemote: (name: string) => `Core se ejecuta en ${name}, y un inicio de sesión del navegador no puede volver a este equipo. Abra la dirección de verificación en cualquier navegador e introduzca el código del dispositivo.`, + verifyUrl: "Dirección de verificación", + code: "Código del dispositivo", + open: "Abrir", + deviceWaiting: (min: number) => `Esperando el código · válido para ${min} min`, + newCode: "Obtener un nuevo código", + deviceWarning: "Ingrese sólo el código del dispositivo que se muestra aquí; nunca introduzca un código de dispositivo proporcionado por otra persona.", + doneTitle: "Firmado en", + reloginDone: (name: ReactNode) => <>Firmado de nuevo. La credencial de la corriente {name} ha sido reemplazado., + signedIn: "Firmado en", + siteAccount: (site: string) => `${site} cuenta`, + quotaUsed: (window: string, percent: number) => `${window}: ${percent}% utilizado`, + resets: (when: string) => `reinicia ${when}`, + signedInTitle: (site: string) => `Firmado en una cuenta ${site}`, + signedInDesc: "La clave se obtuvo al iniciar sesión, y el uso cuenta con el plan de codificación de la cuenta.", + relogin: "Inicie sesión de nuevo", + replaceTitle: (site: string) => `Inicia sesión en ${site}`, + replaceDesc: "Iniciar sesión reemplaza la clave actual con una clave de la cuenta. El alcance del modelo, la facturación y otros ajustes permanecen sin cambios.", + signIn: "Iniciar sesión", + }, + }, ); diff --git a/src/upstreams/BillingSection.i18n.ts b/src/upstreams/BillingSection.i18n.ts index 75073647..d0d8e787 100644 --- a/src/upstreams/BillingSection.i18n.ts +++ b/src/upstreams/BillingSection.i18n.ts @@ -47,4 +47,48 @@ export const billingSectionText = messages( linkSheetDetail: (multiplier: number, overrides: number) => `Created with the upstream · multiplier ×${multiplier} · ${overrides === 1 ? "1 model" : `${overrides} models`} priced separately`, }, + { + "zh-Hant": { + billing: "計費方式", + sheet: "價目表", + defaultSheet: "預設價目表", + newSheet: "新建價目表…", + usedBy: "使用此價目表的上游", + editSheet: "編輯價目表", + effective: "生效價格", + unit: "美元 / 百萬 tokens", + empty: "模型列表為空。獲取模型列表後顯示各模型的生效價格。", + source: "來源", + unpriced: (n: number) => `${n} 個模型無法計價,這些模型的請求無法計算費用。`, + setPrices: "設定價格…", + linkSheet: (name: string) => `新價目表「${name}」`, + linkSheetDetail: (multiplier: number, overrides: number) => `隨上游一起建立 · 倍率 ×${multiplier} · ${overrides} 個模型單獨定價`, + }, + ko: { + model: "모델", + source: "출처", + }, + es: { + newUpstream: "(nuevas del proveedor)", + billing: "Facturas", + sheet: "Ficha de precios", + defaultSheet: "Ficha de precios por defecto", + newSheet: "Nueva hoja de precios…", + usedBy: "Upstreams usando esta hoja de precios", + editSheet: "Editar hoja de precios", + effective: "Precios efectivos", + unit: "USD / millones de fichas", + empty: "La lista de modelos está vacía. Los precios efectivos aparecen una vez que se obtiene la lista de modelo.", + model: "Modelo", + source: "Origen", + estimated: " (estimado)", + unpriced: (n: number) => n === 1 + ? "1 modelo no tiene precio; el costo de sus solicitudes no puede calcularse." + : `${n} los modelos no tienen precio; el costo de sus solicitudes no puede calcularse.`, + setPrices: "Fijar precios…", + linkSheet: (name: string) => `Nueva hoja de precios “${name}”`, + unnamed: "sin título", + linkSheetDetail: (multiplier: number, overrides: number) => `Creado con el multiplicador · del proveedor ×${multiplier} · ${overrides === 1 ? "1 modelo" : `${overrides} modelos`} precio por separado`, + }, + }, ); diff --git a/src/upstreams/ChatgptAccountSection.i18n.ts b/src/upstreams/ChatgptAccountSection.i18n.ts index 98b635c4..34d2244b 100644 --- a/src/upstreams/ChatgptAccountSection.i18n.ts +++ b/src/upstreams/ChatgptAccountSection.i18n.ts @@ -83,4 +83,85 @@ export const chatgptAccountText = messages( needsLogin: "Signing in again is required to keep using this upstream.", relogin: "Sign in again", }, + { + "zh-Hant": { + status: { + available: "可用", + redeemed: "已使用", + expired: "已過期", + revoked: "已作廢", + }, + codes: { + reset: "額度已重置", + nothing_to_reset: "額度尚未用完,未使用重置卡", + no_credit: "沒有可用的重置卡", + already_redeemed: "這次操作此前已經完成,額度已在那一次重置", + }, + name: "名稱", + egressDesc: "登入與後續請求都經此發出", + direct: "直連", + systemProxy: "系統代理", + quota: "訂閱額度", + reload: "重新讀取", + window: (label: string) => `${label}視窗`, + noQuota: "上游未報告額度。", + credits: "額度重置卡", + available: (n: number) => `可用 ${n} 張`, + creditsNote: "一張重置卡把已用完的額度視窗重置一次。使用之後無法撤回,閘道器不會自動使用。", + noCredits: "帳號上沒有重置卡。", + credit: "額度重置卡", + confirmTitle: "使用一張額度重置卡", + confirmDesc: "這張卡將被立即使用,用於重置已經用完的額度視窗。使用之後無法撤回。", + notConsumedTitle: "額度尚未用完時不會消耗", + notConsumedDesc: "上游在沒有需要重置的視窗時直接返回,不扣除這張卡。", + loginInvalid: "登入已失效", + signedIn: "已登入", + needsLogin: "需要重新登入才能繼續使用這個上游。", + relogin: "重新登入", + }, + ko: { + name: "이름", + }, + es: { + status: { + available: "Disponible", + redeemed: "Utilizado", + expired: "Expirado", + revoked: "Revocado", + }, + codes: { + reset: "El límite de uso ha sido restablecido", + nothing_to_reset: "El límite de uso no se ha agotado; no se utilizó crédito de reinicio", + no_credit: "No se dispone de créditos de reinicio", + already_redeemed: "Esta operación ya estaba terminada; el límite de uso se restableció en ese momento.", + }, + name: "Nombre", + egress: "Conexión de salida", + egressDesc: "Utilizado para iniciar sesión y todas las solicitudes posteriores", + direct: "Directo", + systemProxy: "Proxy del sistema", + quota: "Límites de uso", + reload: "Recargar", + window: (label: string) => `${label} ventana`, + used: (percent: number) => `${percent}% utilizado`, + resets: (when: string) => `reinicia ${when}`, + noQuota: "Las del proveedor no comunicaron ningún límite de uso.", + credits: "Reiniciar créditos", + available: (n: number) => `${n} disponibles`, + creditsNote: "Un crédito de reinicio restablece una ventana de límite de uso usado una vez. Usar uno no se puede deshacer, y la puerta de enlace nunca los utiliza automáticamente.", + noCredits: "La cuenta no tiene créditos de reinicio.", + credit: "Reiniciar crédito", + expires: (date: string) => `expira ${date}`, + useEllipsis: "Usa…", + confirmTitle: "Usar un crédito de reinicio", + confirmDesc: "Este crédito se utilizará inmediatamente para restablecer las ventanas de límite de uso que se han agotado. Esto no se puede deshacer.", + notConsumedTitle: "No se consume si el límite de uso no se ha agotado", + notConsumedDesc: "Cuando no es necesario restablecer ninguna ventana, los rendimientos ascendentes sin deducir este crédito.", + use: "Uso", + loginInvalid: "El registro ya no es válido", + signedIn: "Firmado en", + needsLogin: "Es necesario volver a iniciar sesión para seguir usando este curso previo.", + relogin: "Inicie sesión de nuevo", + }, + }, ); diff --git a/src/upstreams/ConnectionSection.i18n.ts b/src/upstreams/ConnectionSection.i18n.ts index 89803888..fbd0da19 100644 --- a/src/upstreams/ConnectionSection.i18n.ts +++ b/src/upstreams/ConnectionSection.i18n.ts @@ -155,4 +155,141 @@ export const connectionSectionText = messages( clientIdentityDesc: "Sends this upstream the client's own User-Agent and identity; when off, requests appear as ThinkWatch. Turn on only for upstreams that accept specific clients, such as Kimi For Coding or Bailian Coding Plan.", }, + { + "zh-Hant": { + auto: "自動識別", + autoDetected: (protocol: string) => `自動識別(${protocol})`, + autoUndetected: "自動識別(未識別,按原格式轉發)", + protocol: "介面協議", + name: "名稱", + baseUrl: "介面地址", + baseUrlDesc: "服務商提供的 Base URL,不含 /chat/completions、/messages 等介面路徑。", + auth: "認證方式", + site: "站點", + siteZai: "Z.ai(國際)", + siteBigmodel: "BigModel(中國大陸)", + advanced: "高階設定", + headers: "請求頭", + headersHint: "隨每個請求傳送。值中的 ${變數名} 讀取系統環境變數。", + authUnknown: "鑑權頭(按介面協議)", + renewedToken: "‹自動換髮的 Access Token›", + signedPerRequest: "‹每個請求單獨簽名›", + region: "區域", + pickRegion: "選擇區域", + signingRegionDesc: "介面地址不是標準的 Bedrock 地址,簽名按這裡選的區域。", + accessKeyId: "訪問金鑰 ID", + secretAccessKey: "私有訪問金鑰", + sessionToken: "會話令牌(可選)", + sessionTokenDesc: "臨時憑證才有。", + profileDesc: "讀取本機 AWS 憑證檔案(~/.aws/credentials、~/.aws/config)中的這個 profile,只支援寫有訪問金鑰的 profile。", + onProxyFail: "代理不可用時", + failWithError: "返回錯誤", + fallBackDirect: "改為直連", + concurrency: "併發上限", + balanceSource: "餘額來源", + balanceAuto: "自動識別", + balanceOff: "不讀取", + concurrencyDesc: "同時發往此上游的請求數上限,用於限制併發的中轉站或帳號。", + badConcurrency: "須為 1 到 1000 之間的整數。", + minSpeedBefore: "生成速度低於", + minSpeedMiddle: "token/秒持續", + minSpeedAfter: "秒時中斷", + minSpeedWindow: "判定時長(秒)", + minSpeedOff: "關閉", + minSpeedDesc: "中斷後由用戶端重試。", + badMinSpeed: "生成速度須為 1 到 1000 之間的整數。", + badMinSpeedWindow: "判定時長鬚為 5 到 120 之間的整數。", + check: "檢測連線", + checking: "檢測中", + checkNote: "驗證地址與憑據,並獲取模型列表。不產生費用。", + keyPlaceholder: "sk-…,或 ${變數名}", + apiKey: "API 金鑰", + tokenEndpoint: "Token 端點", + clientId: "Client ID(可選)", + clientSecret: "Client Secret(可選)", + accessToken: "Access Token(檢測用,可選)", + accessTokenDesc: "僅用於儲存前檢測連線。", + failed: "連線失敗", + authenticated: "認證透過", + responded: (ms: string) => `回應 ${ms}`, + via: (proxy: string) => `經由 ${proxy}`, + ok: "連線正常", + clientIdentity: "轉發用戶端身份", + clientIdentityDesc: "向此上游傳送用戶端自己的 User-Agent 和身份資訊;關閉時顯示為 ThinkWatch。僅在上游只接受特定用戶端時開啟,例如 Kimi For Coding、百鍊 Coding Plan。", + }, + ko: { + name: "이름", + minSpeedOff: "끄기", + }, + es: { + auto: "Autodetectar", + autoDetected: (protocol: string) => `Detección automática (${protocol})`, + autoUndetected: "Detectar automáticamente (pasaje)", + protocol: "Protocolo", + name: "Nombre", + namePlaceholder: "Por ejemplo, relé-hk", + namePlaceholderGateway: "Por ejemplo, corp-gateway", + baseUrl: "URL de la base", + baseUrlDesc: "URL base del proveedor, sin una ruta de endpoint como /chat/completions o /messages.", + auth: "Autenticación", + site: "Sitio", + siteZai: "Z.ai (internacional)", + siteBigmodel: "BigModel (China continental)", + advanced: "Configuración avanzada", + headers: "Cabeceras", + headersHint: "Enviado con cada petición. ${NAME} En un valor se lee una variable de entorno del sistema.", + authUnknown: "Encabezado Auth (por protocolo)", + renewedToken: "‹renovado token de acceso›", + signedPerRequest: "‹firmado por solicitud›", + region: "Región", + pickRegion: "Seleccionar una región", + signingRegionDesc: "La URL base no es una URL estándar de Bedrock, por lo que las solicitudes están firmadas para esta región.", + accessKeyId: "Id. de clave de acceso", + secretAccessKey: "Clave de acceso secreta", + sessionToken: "Token de sesión (opcional)", + sessionTokenDesc: "Sólo las credenciales temporales tienen una.", + awsProfile: "Perfil AWS", + profileDesc: "Lee este perfil de los archivos de credencial AWS en este equipo (~/.aws/credentials, ~/.aws/config). Sólo se admiten perfiles que contengan claves de acceso.", + proxy: "Proxy saliente", + newProxy: "Nuevo proxy…", + onProxyFail: "Cuando el proxy no está disponible", + failWithError: "Devuelve un error", + fallBackDirect: "Conectar directamente", + concurrency: "Límite de concurrencia", + limits: "Límites de uso", + balanceSource: "Fuente de balance", + balanceAuto: "Autodetectar", + balanceOff: "No leer", + noLimit: "Sin límite", + concurrencyDesc: "La mayoría de las solicitudes enviadas a este río a la vez, para relés y cuentas que limitan la concurrencia.", + badConcurrency: "Un número entero de 1 a 1000.", + minSpeed: "Velocidad mínima de generación", + minSpeedBefore: "Parar cuando la generación es más lenta que", + minSpeedMiddle: "tokens/s", + minSpeedAfter: "segundos", + minSpeedRate: "Velocidad mínima de generación (tokens/s)", + minSpeedWindow: "Período de medición (segundos)", + minSpeedOff: "Desactivado", + minSpeedDesc: "El cliente repite una petición detenida.", + badMinSpeed: "La velocidad debe ser un número entero de 1 a 1000.", + badMinSpeedWindow: "El período de medición debe ser de un número entero de 5 a 120.", + check: "Comprobar la conexión", + checking: "Comprobación", + checkNote: "Verifica la URL y las credenciales y obtiene la lista de modelos. No se incurre en ningún costo.", + keyPlaceholder: "sk..., o ${NAME}", + apiKey: "Clave API", + tokenEndpoint: "Punto final de token", + refreshToken: "Actualizar el token", + clientId: "Identificación del cliente (opcional)", + clientSecret: "Secreto del cliente (opcional)", + accessToken: "Token de acceso (para comprobar, opcional)", + accessTokenDesc: "Sólo se utiliza para comprobar la conexión antes de guardar.", + failed: "Ha fallado la conexión", + authenticated: "Autenticado", + responded: (ms: string) => `respondió en ${ms}`, + ok: "Conexión OK", + clientIdentity: "Reenviar la identidad del cliente", + clientIdentityDesc: "Envía este curso previo al usuario del propio agente de usuario y la identidad; cuando está fuera, las solicitudes aparecen como ThinkWatch. Enciende sólo para los cursos previos que aceptan clientes específicos, como Kimi For Coding o Bailian Coding Plan.", + }, + }, ); diff --git a/src/upstreams/DeleteDialog.i18n.ts b/src/upstreams/DeleteDialog.i18n.ts index 0ae8f34f..2d19cabb 100644 --- a/src/upstreams/DeleteDialog.i18n.ts +++ b/src/upstreams/DeleteDialog.i18n.ts @@ -26,4 +26,25 @@ export const deleteDialogText = messages( condition: (route: string, rule: string) => `Route “${route}” · condition of rule “${rule}”`, group: (group: string) => `Group “${group}”`, }, + { + "zh-Hant": { + title: (what: string, name: string) => `刪除${what}「${name}」`, + blockedTitle: (what: string, name: string) => `無法刪除${what}「${name}」`, + blocked: (what: string) => `以下配置引用了此${what},解除引用後才能刪除。`, + show: "檢視", + rule: (route: string, rule: string) => `路由「${route}」· 規則「${rule}」`, + condition: (route: string, rule: string) => `路由「${route}」· 規則「${rule}」的條件`, + group: (group: string) => `策略組「${group}」`, + }, + es: { + title: (what: string, name: string) => `Suprímase ${what} “${name}”`, + blockedTitle: (what: string, name: string) => `No se puede borrar ${what} «${name}»`, + blocked: (what: string) => `Esto ${what} se refiere a la configuración de abajo y se puede eliminar una vez que se eliminan esas referencias.`, + show: "Mostrar", + upstream: (name: string) => `Corriente ascendente “${name}”`, + rule: (route: string, rule: string) => `Ruta “${route}” · regla “${rule}”`, + condition: (route: string, rule: string) => `Ruta “${route}” · condición de la regla “${rule}”`, + group: (group: string) => `Grupo “${group}”`, + }, + }, ); diff --git a/src/upstreams/HeaderEditor.i18n.ts b/src/upstreams/HeaderEditor.i18n.ts index 5caccb87..44c0d18f 100644 --- a/src/upstreams/HeaderEditor.i18n.ts +++ b/src/upstreams/HeaderEditor.i18n.ts @@ -25,4 +25,42 @@ export const headerEditorText = messages( fromOauth: "Set by the OAuth credentials", fromSignature: "Set by signing with the access keys", }, + { + "zh-Hant": { + name: "請求頭名稱", + namePlaceholder: "名稱", + valueOf: (name: string) => `請求頭「${name}」的值`, + value: "請求頭的值", + valuePlaceholder: "值,或 ${變數名}", + remove: "刪除此請求頭", + add: "新增請求頭", + fromKey: "由 API 金鑰生成", + fromOauth: "由 OAuth 憑據生成", + fromSignature: "由訪問金鑰簽名生成", + }, + ko: { + namePlaceholder: "이름", + name: "요청 헤더 이름", + valueOf: (name: string) => `요청 헤더 「${name}」의 값`, + value: "헤더 값", + valuePlaceholder: "값 또는 ${NAME}", + remove: "요청 헤더 제거", + add: "요청 헤더 추가", + fromKey: "API 키로 설정", + fromOauth: "OAuth 인증 정보로 설정", + fromSignature: "요청 서명으로 설정", + }, + es: { + name: "Nombre del encabezado", + namePlaceholder: "Nombre", + valueOf: (name: string) => `Valor de la cabecera “${name}”`, + value: "Valor de cabecera", + valuePlaceholder: "Valor, o ${NAME}", + remove: "Borrar esta cabecera", + add: "Añadir cabecera", + fromKey: "Establecer por la clave de la API", + fromOauth: "Establecer por las credenciales de OAuth", + fromSignature: "Establecer firmando con las teclas de acceso", + }, + }, ); diff --git a/src/upstreams/LimitsField.i18n.ts b/src/upstreams/LimitsField.i18n.ts index 3455cb80..52411000 100644 --- a/src/upstreams/LimitsField.i18n.ts +++ b/src/upstreams/LimitsField.i18n.ts @@ -9,4 +9,14 @@ export const limitsFieldText = messages( hint: "Once any limit is used up, this upstream takes no new requests for a while", free: "This upstream is free: its cost counts as $0, so a cost limit is never used up.", }, + { + "zh-Hant": { + hint: "任一上限用滿後,此上游暫不接收新請求", + free: "此上游不計費,費用按 0 計入,費用上限不會用滿。", + }, + es: { + hint: "Una vez que se ha agotado cualquier límite, este curso no toma nuevas solicitudes durante un tiempo", + free: "Este curso previo es gratuito: su costo cuenta como $0, por lo que un límite de costo nunca se consume.", + }, + }, ); diff --git a/src/upstreams/ManualModelInput.i18n.ts b/src/upstreams/ManualModelInput.i18n.ts index baa41adf..316b49e5 100644 --- a/src/upstreams/ManualModelInput.i18n.ts +++ b/src/upstreams/ManualModelInput.i18n.ts @@ -34,4 +34,35 @@ export const manualModelInputText = messages( manualOnlyTitle: "Added by hand; not in the upstream's model list", manualListedTitle: "Added by hand; also in the upstream's model list", }, + { + "zh-Hant": { + about: "新增上游能服務、但未列在其模型列表中的模型。", + enterToAdd: "回車新增", + hint: "可新增多個,每項為一個確切的模型 ID。", + blank: "模型 ID 不能為空。", + wildcard: (id: string) => `「${id}」含有 * 或 ?。手動新增的模型須為確切的模型 ID,不支援通配。`, + tooLong: (max: number) => `模型 ID 最多 ${max} 個字元。`, + duplicate: (id: string) => `「${id}」已在待新增的模型中。`, + added: (id: string) => `「${id}」已經手動新增過。`, + listed: (id: string) => `上游的模型列表中已有「${id}」,無需新增。`, + manualTag: "手動", + manualOnlyTitle: "手動新增的模型,上游的模型列表中沒有", + manualListedTitle: "手動新增的模型,上游的模型列表中也有", + }, + es: { + about: "Agregue los modelos que sirve la corriente ascendente, pero deja fuera de su lista de modelos.", + models: "ID de modelos", + placeholder: "Por ejemplo, gpt-6-luna", + enterToAdd: "Introduzca para añadir", + hint: "Añadir tantos como sea necesario, cada uno un modelo exacto ID.", + blank: "Un ID de modelo no puede estar vacío.", + wildcard: (id: string) => `“${id}” contiene * o ?. Un modelo añadido a mano es un ID de modelo exacto; los comodines no son compatibles.`, + tooLong: (max: number) => `Un ID de modelo es como máximo ${max} caracteres.`, + duplicate: (id: string) => `“${id}” ya está en la lista para añadir.`, + added: (id: string) => `“${id}” ya se ha añadido a mano.`, + listed: (id: string) => `La lista de modelos de del proveedor ya tiene “${id}”; no hay necesidad de añadirla.`, + manualOnlyTitle: "Añadido a mano; no en la lista de modelos de del proveedor", + manualListedTitle: "Añadido a mano; también en la lista de modelos de del proveedor", + }, + }, ); diff --git a/src/upstreams/ManualModelsDialog.i18n.ts b/src/upstreams/ManualModelsDialog.i18n.ts index 52022ab2..565d36c4 100644 --- a/src/upstreams/ManualModelsDialog.i18n.ts +++ b/src/upstreams/ManualModelsDialog.i18n.ts @@ -14,4 +14,19 @@ export const manualModelsDialogText = messages( removeShort: "Remove", outOfScope: "Not enabled", }, + { + "zh-Hant": { + title: "新增模型", + outOfScope: "不在啟用範圍內", + }, + ko: { + removeShort: "제거", + }, + es: { + title: "Añadir modelos", + remove: (id: string) => `Eliminar ${id}`, + removeShort: "Quitar", + outOfScope: "No activado", + }, + }, ); diff --git a/src/upstreams/ModelSpecDialog.i18n.ts b/src/upstreams/ModelSpecDialog.i18n.ts index 8c9a0043..de27968a 100644 --- a/src/upstreams/ModelSpecDialog.i18n.ts +++ b/src/upstreams/ModelSpecDialog.i18n.ts @@ -69,4 +69,71 @@ export const modelSpecDialogText = messages( filtered: (levels: string) => `The current protocol conversion cannot represent ${levels}; these choices are not offered to clients.`, resetEffort: "Restore automatic effort", }, + { + "zh-Hant": { + title: "模型規格", + desc: "預設自動獲取模型能力;上游缺少資訊或結果有誤時,可按需填寫覆蓋值。留空或選「自動」恢復自動獲取。", + contextWindow: "上下文視窗", + maxOutput: "輸出上限", + imageInput: "圖片輸入", + table: "自動", + priceTable: "價目表", + yes: "支援", + no: "不支援", + fromTable: (n: string) => `價目表:${n}`, + useTable: "使用自動獲取的值", + notInTable: "暫無已知值", + bad: "須為正整數,最大 4294967295。", + removing: "儲存後移除手動設定,恢復自動獲取。", + effort: "推理強度", + effortHelp: "自動使用上游宣告的檔位。支援推理不一定支援調節強度;手動檔位應與上游實際支援的能力一致。", + effortDisabled: "已選擇不支援推理,儲存後不提供推理檔位。", + noAdjustable: "不可調", + manual: "手動", + supportedLevels: "支援的檔位", + chooseLevel: "至少選擇一個檔位;沒有可調檔位請選「不可調」。", + defaultLevel: "預設檔位", + defaultHelp: "自動:在最終可用檔位裡優先 medium,否則最低檔。", + reported: "上游報告", + savedEffective: "該上游當前生效檔位", + aliasEffortHelp: "別名使用所有候選模型共有的檔位;任一候選能力未知時不提供檔位。Codex 也會優先使用與用戶端版本對應的上游目錄。", + filtered: (levels: string) => `當前協議轉換不支援 ${levels},這些檔位未向用戶端提供。`, + resetEffort: "恢復自動檔位", + }, + ko: { + upstream: "업스트림", + }, + es: { + title: "Especificaciones del modelo", + desc: "Las capacidades del modelo se descubren automáticamente. Anule aquí la información que falta o incorrecta; deje un campo en blanco o seleccione Automático para restaurar el descubrimiento.", + contextWindow: "Ventana contextual", + maxOutput: "Salida máxima", + reasoning: "Razonamiento", + imageInput: "Entrada de imagen", + table: "Automático", + priceTable: "Tabla de precios", + yes: "Sí", + fromTable: (n: string) => `Cuadro de precios: ${n}`, + useTable: "Usar valores automáticos", + fromUpstream: (n: string) => `Corriente ascendente: ${n}`, + notInTable: "Ningún valor conocido", + bad: "Un número entero por encima de 0, como máximo 4294967295.", + removing: "Guardar elimina las anulaciones manuales y restaura los valores automáticos.", + effort: "Motivación", + effortHelp: "Utilice los niveles declarados por el upstream automáticamente. El soporte de razonamiento no siempre incluye el esfuerzo ajustable; los niveles manuales deben coincidir con las capacidades reales del upsteam.", + effortDisabled: "El razonamiento está desactivado. Guardar elimina las opciones de razonamiento del catálogo.", + noAdjustable: "No ajustable", + upstream: "Proveedor", + unknown: "Desconocido", + supportedLevels: "Niveles apoyados", + chooseLevel: "Seleccione al menos un nivel, o elija No ajustable.", + defaultLevel: "Nivel predeterminado", + defaultHelp: "Automático prefiere el medio en el conjunto final disponible, de lo contrario su nivel más bajo.", + reported: "Informado por del proveedor", + savedEffective: "Niveles guardados para este curso previo", + aliasEffortHelp: "Los alias solo ofrecen niveles compartidos por todos los candidatos; un candidato desconocido no deja opciones confirmadas. Codex también prefiere el catálogo ascendente para su versión cliente.", + filtered: (levels: string) => `La conversión actual del protocolo no puede representar ${levels}; estas opciones no se ofrecen a los clientes.`, + resetEffort: "Restaurar el esfuerzo automático", + }, + }, ); diff --git a/src/upstreams/ModelsPanel.i18n.ts b/src/upstreams/ModelsPanel.i18n.ts index 7090eaf0..141936b4 100644 --- a/src/upstreams/ModelsPanel.i18n.ts +++ b/src/upstreams/ModelsPanel.i18n.ts @@ -95,4 +95,89 @@ export const modelsPanelText = messages( listSep: ", ", manualTitle: (what: string) => `Set by hand: ${what}`, }, + { + "zh-Hant": { + refetch: "重新獲取模型列表", + fetching: "正在獲取模型列表", + failed: "獲取失敗", + unreachable: "未能連線上游。", + editUpstream: "編輯上游…", + usingManual: (n: number) => `暫用手動新增的 ${n} 個模型。`, + noList: (reason: string) => `${reason.replace(/[。.]$/, "")}。可手動新增此上游提供的模型。`, + addModels: "新增模型…", + filter: "篩選模型", + notEnabled: (n: number) => `不在啟用範圍內 ${n} 個`, + noMatch: "無匹配的模型", + countAll: (total: number) => `${total} 個`, + countSome: (total: number, enabled: number) => `${total} 個,已啟用 ${enabled} 個`, + listedAt: (count: string, time: string) => `上游列出 ${count} · ${time} 獲取`, + listedAndAdded: (listed: number, added: number) => `上游列出 ${listed} 個,手動新增 ${added} 個`, + fetchedAt: (what: string, time: string) => `${what} · ${time} 獲取`, + manual: (count: string) => `手動新增 ${count}`, + lastTry: (time: string) => `最近一次嘗試 ${time}`, + notFetched: "尚未獲取", + priceTitle: "輸入 / 輸出,美元每百萬 tokens", + context: "上下文視窗", + aliasMark: (alias: string) => `別名 ${alias}`, + aliasTitle: (alias: string) => `別名 ${alias} 列著這個模型:用戶端用 ${alias} 請求時可以發往這個模型`, + makeAlias: "起別名…", + specs: "規格…", + setPrice: "設定價格…", + unpriced: "未定價", + manualSpecs: "手動規格", + removed: (id: string) => `已移除手動新增的模型 ${id}`, + manualContext: (n: string) => `上下文視窗 ${n}`, + manualOutput: (n: string) => `輸出上限 ${n}`, + manualReasoning: (on: boolean): string => (on ? "支援推理" : "不支援推理"), + manualImageInput: (on: boolean): string => (on ? "支援圖片輸入" : "不支援圖片輸入"), + manualEffort: (levels: string): string => levels ? `推理檔位 ${levels}` : "推理強度不可調", + manualTitle: (what: string) => `手動設定:${what}`, + }, + ko: { + title: "모델", + remove: "제거", + }, + es: { + title: "Modelos", + refetch: "Obtener la lista de modelos de nuevo", + fetching: "Obtener la lista de modelos", + failed: "Ha fallado la obtención", + unreachable: "No se pudo llegar a la del proveedor.", + editUpstream: "Editar ascendentemente…", + usingManual: (n: number) => n === 1 ? "Usando el modelo 1 agregado a mano por ahora." : `Usando los modelos ${n} añadidos a mano por ahora.`, + noList: (reason: string) => `${reason.replace(/[。.]$/, "")}. Los modelos a los que se sirve esta corriente pueden ser añadidos a mano.`, + noListReason: "El principio no proporciona una lista modelo", + addModels: "Añadir modelos…", + filter: "Modelos de filtro", + notEnabled: (n: number) => `${n} no activado`, + noMatch: "No hay modelos coincidentes", + editScope: "Administrar modelos…", + countAll: (total: number) => (total === 1 ? "1 modelo" : `${total} modelos`), + countSome: (total: number, enabled: number) => `${total === 1 ? "1 modelo" : `${total} modelos`}, ${enabled} activado`, + listed: (count: string) => `Listado por el río arriba: ${count}`, + listedAt: (count: string, time: string) => `Listado por el río arriba: ${count} · obtenido en ${time}`, + listedAndAdded: (listed: number, added: number) => `${listed} enumerado por la parte anterior, ${added} añadido a mano`, + fetchedAt: (what: string, time: string) => `${what} · obtenido en ${time}`, + manual: (count: string) => `Agregado a mano: ${count}`, + lastTry: (time: string) => `Último intento de ${time}`, + notFetched: "Aún no se ha recibido.", + priceTitle: "Entrada/salida, USD por millón de tokens", + context: "Ventana contextual", + aliasTitle: (alias: string) => `Alias ${alias} enumera este modelo: solicitudes para ${alias} pueden ir a él`, + makeAlias: "Añadir alias…", + setPrice: "Fijar el precio…", + unpriced: "Sin precio", + unknown: "Desconocido", + actionsOf: (id: string) => `Acciones en relación con ${id}`, + manualSpecs: "Especificaciones manuales", + remove: "Quitar", + removed: (id: string) => `Eliminado ${id}, añadido a mano`, + manualContext: (n: string) => `ventana de contexto ${n}`, + manualOutput: (n: string) => `Salida máxima ${n}`, + manualReasoning: (on: boolean): string => (on ? "razonamiento" : "sin razonamiento"), + manualImageInput: (on: boolean): string => (on ? "entrada de imagen" : "sin entrada de imagen"), + manualEffort: (levels: string): string => levels ? `Niveles de razonamiento ${levels}` : "esfuerzo de razonamiento no ajustable", + manualTitle: (what: string) => `Fijado a mano: ${what}`, + }, + }, ); diff --git a/src/upstreams/ModelsSection.i18n.ts b/src/upstreams/ModelsSection.i18n.ts index 60d3cd65..5c6e9fb9 100644 --- a/src/upstreams/ModelsSection.i18n.ts +++ b/src/upstreams/ModelsSection.i18n.ts @@ -103,4 +103,93 @@ export const modelsSectionText = messages( ? "1 enabled model has an unknown context window; clients that are taken over use their own default." : `${n} enabled models have an unknown context window; clients that are taken over use their own default.`, }, + { + "zh-Hant": { + count: (n: number) => `${n} 個`, + listedAndAdded: (listed: number, added: number) => `上游列出 ${listed} 個,手動新增 ${added} 個`, + fetchedAt: (time: string) => `獲取於 ${time}`, + refresh: "重新整理模型列表", + fetching: "正在獲取模型列表", + notFetched: "尚未獲取模型列表。", + noList: (reason: string) => `${reason.replace(/[。.]$/, "")}。可手動新增此上游提供的模型。`, + unreachable: "未能連線上游", + addLabel: "手動新增的模型 ID", + addPlaceholder: "新增模型,例如 gpt-6-luna", + scope: "啟用範圍", + patterns: (patterns: string[]) => `啟用範圍包含通配規則 ${patterns.join("、")}。勾選或取消勾選後,範圍改為所勾選的模型。`, + filter: "篩選模型", + enabled: (on: number, total: number) => `已啟用 ${on} / ${total}`, + selectAll: "全選", + context: "上下文視窗", + pricing: "定價", + specs: "規格…", + specsOf: (id: string) => `設定 ${id} 的規格`, + setPrice: "設定價格…", + setPriceShort: "設定價格", + priceOf: (id: string) => `設定 ${id} 的價格`, + makeAlias: "起別名…", + aliasMark: (alias: string) => `別名 ${alias}`, + aliasTitle: (alias: string) => `別名 ${alias} 列著這個模型:用戶端用 ${alias} 請求時可以發往這個模型`, + fill: "填寫", + manualContextTitle: "此上游手動填寫的值,優先於價目表", + noMatch: "無匹配的模型", + priced: "已定價", + pricedEstimated: "已定價(估算)", + unpriced: "未定價", + unpricedNote: (n: number, sheet: string) => `${n} 個已啟用的模型在${sheet}中未定價,這些模型的請求無法計算費用。`, + inBilling: "可在「計費」中為其設定價格。", + unknownNote: (n: number) => `${n} 個已啟用的模型上下文視窗未知,接管的用戶端按自身預設值處理。`, + }, + ko: { + actions: "작업", + remove: "제거", + }, + es: { + title: "Lista de modelos", + count: (n: number) => (n === 1 ? "1 modelo" : `${n} modelos`), + listedAndAdded: (listed: number, added: number) => `${listed} enumerado por la parte anterior, ${added} añadido a mano`, + fetchedAt: (time: string) => `obtenido a ${time}`, + refresh: "Actualizar la lista de modelos", + fetching: "Obtener la lista de modelos", + notFetched: "La lista de modelos no ha sido recogida.", + noList: (reason: string) => `${reason.replace(/[。.]$/, "")}. Los modelos a los que se sirve esta corriente pueden ser añadidos a mano.`, + noListReason: "El principio no proporciona una lista modelo", + unreachable: "No se pudo llegar a la del proveedor", + addLabel: "IDs de modelo para añadir a mano", + addPlaceholder: "Añadir un modelo, por ejemplo gpt-6-luna", + scope: "Modelos activados", + all: "Todos los modelos", + some: "Modelos seleccionados", + patterns: (patterns: string[]) => `Los modelos habilitados incluyen patrones de comodines ${patterns.join(", ")}. Comprobar o desmarcar un modelo los reemplaza con los modelos comprobados.`, + filter: "Modelos de filtro", + enabled: (on: number, total: number) => `${on} / ${total} activado`, + selectAll: "Seleccionar todo", + modelId: "ID del modelo", + context: "Ventana contextual", + pricing: "Precio", + actions: "Acciones", + actionsOf: (id: string) => `Acciones en relación con ${id}`, + remove: "Quitar", + specsOf: (id: string) => `Establecer especificaciones para ${id}`, + setPrice: "Fijar el precio…", + setPriceShort: "Fijar precio", + priceOf: (id: string) => `Fijar el precio de ${id}`, + makeAlias: "Añadir alias…", + aliasTitle: (alias: string) => `Alias ${alias} enumera este modelo: solicitudes para ${alias} pueden ir a él`, + unknown: "Desconocido", + fill: "Establecer", + manualContextTitle: "Fijar a mano para esta corriente; tiene precedencia sobre la tabla de precios", + noMatch: "No hay modelos coincidentes", + priced: "Precio", + pricedEstimated: "Precio (estimado)", + unpriced: "Sin precio", + unpricedNote: (n: number, sheet: string) => n === 1 + ? `1 modelo habilitado no tiene precio en ${sheet}, por lo que el costo de sus solicitudes no se puede calcular.` + : `${n} los modelos habilitados no tienen precio en ${sheet}, por lo que el costo de sus solicitudes no puede calcularse.`, + inBilling: " Los precios se pueden fijar en la facturación.", + unknownNote: (n: number) => n === 1 + ? "1 modelo habilitado tiene una ventana de contexto desconocida; los clientes que son tomados utilizan su propio valor predeterminado." + : `${n} los modelos habilitados tienen una ventana de contexto desconocida; los clientes que son tomados utilizan su propio valor predeterminado.`, + }, + }, ); diff --git a/src/upstreams/PriceSheetDialog.i18n.ts b/src/upstreams/PriceSheetDialog.i18n.ts index ab614fe4..4e4855de 100644 --- a/src/upstreams/PriceSheetDialog.i18n.ts +++ b/src/upstreams/PriceSheetDialog.i18n.ts @@ -118,4 +118,116 @@ export const priceSheetDialogText = messages( deleteTitle: (name: string) => `Delete price sheet “${name}”`, deleteDesc: "The price sheet's multiplier and model overrides will be removed from the config file. It can be restored from the backups.", }, + { + "zh-Hant": { + defaultSheet: "預設價目表", + editTitle: "編輯價目表", + duplicateTitle: "複製價目表", + createTitle: "新建價目表", + descDefault: "LiteLLM 公開價格。自定義價目表在此基礎上設定倍率與模型覆蓋。", + descCustom: "倍率作用於預設價目表中的全部單價,包括快取與長上下文單價;模型覆蓋不受倍率影響。", + multiplierPositive: "倍率須大於 0", + enterName: "填寫名稱", + name: "名稱", + basis: "定價依據", + modelPrices: "模型單價", + related: "相關模型", + overridden: "已覆蓋", + filterPlaceholder: "篩選模型", + addOverride: "新增覆蓋", + add: "新增", + source: "來源", + longContextPrices: "長上下文單價", + unpriced: "未定價", + sheetOverride: "價目表覆蓋", + removeOverride: (model: string) => `移除 ${model} 的覆蓋`, + overridePrice: (model: string) => `覆蓋 ${model} 的價格`, + longContextNote: "單次請求輸入超過 200K tokens 之後的單價", + setLongContext: "設定長上下文單價", + noTiers: "不分檔", + long: { + input_above_200k: "長上下文輸入", + output_above_200k: "長上下文輸出", + }, + emptyOverridden: "尚無模型覆蓋", + emptyRelated: "使用此價目表的上游尚無模型", + emptyAll: "沒有匹配的模型", + unit: "單位:美元 / 百萬 tokens", + truncated: (shown: number, matched: number) => `顯示前 ${shown} 個,共 ${matched.toLocaleString()} 個匹配。輸入模型名稱縮小範圍。`, + usedByTitle: "使用此價目表的上游", + noPerToken: "尚無按量計費的上游。", + switchHint: (sheet: string) => `當前使用價目表「${sheet}」,選中後改用此價目表`, + deleteSheet: "刪除價目表", + inUse: (n: number) => `正在被 ${n} 個上游使用`, + create: "建立", + draftTitle: "新價目表", + draftUsedBy: "隨正在新建的上游一起建立,由它使用。", + nameTaken: (name: string) => `價目表名稱「${name}」已被使用`, + deleteTitle: (name: string) => `刪除價目表「${name}」`, + deleteDesc: "刪除後此價目表的倍率與模型覆蓋將從配置檔案中移除,可從備份中恢復。", + }, + ko: { + enterName: "이름을 입력하세요.", + name: "이름", + model: "모델", + source: "출처", + removeOverrideShort: "제거", + }, + es: { + defaultSheet: "Ficha de precios por defecto", + editTitle: "Editar hoja de precios", + duplicateTitle: "Duplicar hoja de precios", + createTitle: "Nueva hoja de precios", + descDefault: "Los precios públicos de LiteLLM. Las hojas de precios personalizadas establecen un multiplicador y el modelo anula en la parte superior de ellos.", + descCustom: "El multiplicador se aplica a cada precio unitario en la hoja de precio por defecto, incluyendo los precios de caché y de contexto largo. Las anulaciones de modelos no se ven afectadas por ella.", + draftName: "Proyecto", + multiplierPositive: "El multiplicador deberá ser superior a 0", + enterName: "Introduce un nombre.", + name: "Nombre", + basis: "Basado en", + multiplier: "Multiplicador", + modelPrices: "Precios modelo", + related: "Modelos relacionados", + overridden: "Revocado", + all: "Todos", + filterPlaceholder: "Modelos de filtro", + addOverride: "Añadir anulación", + modelIdPlaceholder: "ID del modelo", + add: "Añadir", + model: "Modelo", + source: "Origen", + longContextPrices: "Precios a largo plazo", + unpriced: "Sin precio", + sheetOverride: "Superación de la hoja de precios", + estimated: " (estimado)", + removeOverride: (model: string) => `Eliminar la anulación de ${model}`, + removeOverrideShort: "Quitar", + overridePrice: (model: string) => `Anular el precio de ${model}`, + longContextNote: "Precios una vez que la entrada de una sola solicitud excede los tokens de 200K", + setLongContext: "Establecer precios de contexto largo", + noTiers: "Eliminar nivel", + long: { + input_above_200k: "Entrada de contexto largo", + output_above_200k: "Salida de contexto largo", + }, + emptyOverridden: "Todavía no hay sobreescritura del modelo", + emptyRelated: "Las del proveedor que utilizan esta hoja de precios no tienen modelos todavía", + emptyAll: "No hay modelos coincidentes", + unit: "Unidad: USD / 1M tokens", + truncated: (shown: number, matched: number) => `Mostrando el primer ${shown} de ${matched.toLocaleString()} ${matched === 1 ? "igualar" : "coincidencias"}. Escriba un nombre de modelo para estrechar la lista.`, + usedByTitle: "Upstreams usando esta hoja de precios", + notUsed: "No está en uso", + noPerToken: "Todavía no se facturan del proveedor por token.", + switchHint: (sheet: string) => `Actualmente se utiliza la hoja de precios “${sheet}”. Seleccionarlo lo cambia a esta hoja de precio.`, + deleteSheet: "Borrar la hoja de precios", + inUse: (n: number) => (n === 1 ? "En uso por 1 del proveedor" : `En uso por ${n} del proveedor`), + create: "Crear", + draftTitle: "Nueva hoja de precios", + draftUsedBy: "Creado junto con el nuevo río río arriba, que lo utiliza.", + nameTaken: (name: string) => `El nombre de la hoja de precios “${name}” ya está en uso`, + done: "Hecho", + deleteTitle: (name: string) => `Suprímase la hoja de precios “${name}”`, + deleteDesc: "El multiplicador de la hoja de precios y las anulaciones de modelos se eliminarán del archivo de configuraciónuración. Se puede restaurar desde las copias de seguridad.", + }, + }, ); diff --git a/src/upstreams/PriceSheetTable.i18n.ts b/src/upstreams/PriceSheetTable.i18n.ts index a2238565..b1f280c6 100644 --- a/src/upstreams/PriceSheetTable.i18n.ts +++ b/src/upstreams/PriceSheetTable.i18n.ts @@ -44,4 +44,47 @@ export const priceSheetTableText = messages( delete: "Delete…", overrideCount: (n: number) => (n === 1 ? "1 model" : `${n} models`), }, + { + "zh-Hant": { + viewPrices: "檢視價格…", + name: "名稱", + basis: "定價依據", + overrides: "模型覆蓋", + defaultSheet: "預設價目表", + litellm: "LiteLLM 公開價格", + notLoaded: "未載入", + dataInfo: (date: string, models: number) => `資料日期 ${date} · ${models.toLocaleString()} 個模型`, + lastChecked: (at: string) => `最近檢查 ${at}`, + defaultActions: "預設價目表的操作", + edit: "編輯…", + duplicate: "複製…", + delete: "刪除…", + overrideCount: (n: number) => `${n} 項`, + }, + ko: { + name: "이름", + actionsColumn: "작업", + }, + es: { + viewPrices: "Ver precios…", + name: "Nombre", + basis: "Basado en", + multiplier: "Multiplicador", + overrides: "Anular", + usedBy: "Utilizado por", + actionsColumn: "Acciones", + defaultSheet: "Ficha de precios por defecto", + litellm: "LiteLLM precios públicos", + notLoaded: "Descargado", + dataInfo: (date: string, models: number) => `Datos a partir de ${date} · ${models.toLocaleString()} ${models === 1 ? "modelo" : "modelos"}`, + lastChecked: (at: string) => `última comprobación ${at}`, + notUsed: "No está en uso", + defaultActions: "Acciones para la hoja de precios por defecto", + actions: (name: string) => `Acciones en relación con ${name}`, + edit: "Editar…", + duplicate: "Duplicar…", + delete: "Eliminar…", + overrideCount: (n: number) => (n === 1 ? "1 modelo" : `${n} modelos`), + }, + }, ); diff --git a/src/upstreams/ProxyDialog.i18n.tsx b/src/upstreams/ProxyDialog.i18n.tsx index 8ed66ec8..701f8d75 100644 --- a/src/upstreams/ProxyDialog.i18n.tsx +++ b/src/upstreams/ProxyDialog.i18n.tsx @@ -48,4 +48,52 @@ export const proxyDialogText = messages( checkHint: "Completes the proxy handshake and authentication. Incurs no cost.", create: "Create", }, + { + "zh-Hant": { + enterName: "填寫名稱", + enterAddress: "填寫地址與埠", + enterUser: "填寫使用者名稱", + editTitle: "編輯代理", + desc: "上游透過代理連線時,檢測連線、鏈路測速與轉發經過同一代理。", + name: "名稱", + kind: "型別", + port: "埠", + needsAuth: "需要認證", + user: "使用者名稱", + pass: "密碼", + check: "檢測代理", + checking: "檢測中", + ok: (auth: boolean, ms: string) => `連線正常 · ${auth ? "認證透過 · " : ""}回應 ${ms}`, + checkHint: "完成代理握手與認證。不產生費用。", + create: "建立", + }, + ko: { + enterName: "이름을 입력하세요.", + name: "이름", + address: "주소", + port: "포트", + }, + es: { + enterName: "Introduce un nombre.", + enterAddress: "Introduzca una dirección y un puerto", + enterUser: "Introduzca un nombre de usuario", + editTitle: "Editar proxy", + createTitle: "Nuevo proxy", + usedBy: (names: ReactNode) => <>Utilizado por {names}, + desc: "Cuando un upstream se conecta a través de un proxy, las comprobaciones de conexión, pruebas de conexión y peticiones reenviadas pasan por ese proxy.", + name: "Nombre", + namePlaceholder: "Por ejemplo, cc-socks", + kind: "Tipo", + address: "Dirección", + port: "Puerto", + needsAuth: "Requiere autenticación", + user: "Nombre de usuario", + pass: "Contraseña", + check: "Comprobar proxy", + checking: "Comprobación", + ok: (auth: boolean, ms: string) => `Conectado · ${auth ? "autenticado · " : ""}correspondiente a ${ms}`, + checkHint: "Completa el apretón de manos proxy y la autenticación.", + create: "Crear", + }, + }, ); diff --git a/src/upstreams/ProxyTable.i18n.ts b/src/upstreams/ProxyTable.i18n.ts index 80be670b..285eaf77 100644 --- a/src/upstreams/ProxyTable.i18n.ts +++ b/src/upstreams/ProxyTable.i18n.ts @@ -43,4 +43,42 @@ export const proxyTableText = messages( checking: "Checking", unreachable: "Unreachable", }, + { + "zh-Hant": { + traffic: "流量 · 24 小時", + trafficSplit: (up: string, down: string) => `上傳 ${up} · 下載 ${down}`, + trafficNote: "經過這個代理的上傳與下載之和", + trafficUnavailable: "流量暫時取不到", + connectivity: "連通性", + edit: "編輯…", + check: "檢測代理", + delete: "刪除…", + withAuth: "需要認證", + notChecked: "未檢測", + checking: "檢測中", + unreachable: "無法連線", + }, + ko: { + actionsColumn: "작업", + }, + es: { + usedBy: "Utilizado por", + traffic: "Tráfico · 24 h", + trafficSplit: (up: string, down: string) => `Arriba ${up} · Abajo ${down}`, + trafficNote: "Cargar y descargar a través de este proxy", + trafficUnavailable: "El tráfico no está disponible ahora.", + unavailableShort: "No disponible", + connectivity: "Conectividad", + actionsColumn: "Acciones", + edit: "Editar…", + check: "Comprobar proxy", + delete: "Eliminar…", + withAuth: "requiere autenticación", + notUsed: "No está en uso", + actions: (name: string) => `Acciones en relación con ${name}`, + notChecked: "No marcado", + checking: "Comprobación", + unreachable: "Inalcanzable", + }, + }, ); diff --git a/src/upstreams/ReloginDialog.i18n.tsx b/src/upstreams/ReloginDialog.i18n.tsx index 3a36e53f..1c70bc0b 100644 --- a/src/upstreams/ReloginDialog.i18n.tsx +++ b/src/upstreams/ReloginDialog.i18n.tsx @@ -30,4 +30,32 @@ export const reloginText = messages( cancelSignIn: "Cancel sign-in", finish: "Done", }, + { + "zh-Hant": { + chatgptTitle: "重新登入 ChatGPT 帳號", + chatgptDesc: (name: ReactNode) => <>為上游 {name} 換一次登入憑據。模型範圍、計費方式等設定保持不變。, + zaiTitle: (site: string) => `登入 ${site} 帳號`, + zaiDesc: (name: ReactNode) => <>登入帳號,為上游 {name} 換一把新金鑰。模型範圍、計費方式等設定保持不變。, + name: "名稱", + cancelSignIn: "取消登入", + }, + ko: { + name: "이름", + }, + es: { + chatgptTitle: "Inicie sesión en ChatGPT de nuevo", + chatgptDesc: (name: ReactNode) => (<> + Reemplaza la credencial de inicio de sesión para el curso previo {name}. Model scope, billing and other settings stay + unchanged. + ), + zaiTitle: (site: string) => `Inicia sesión en ${site}`, + zaiDesc: (name: ReactNode) => (<> + Inicia sesión en la cuenta y reemplaza la clave del cursor {name}. Model scope, billing and other + settings stay unchanged. + ), + name: "Nombre", + cancelSignIn: "Cancelar el inicio de sesión", + finish: "Hecho", + }, + }, ); diff --git a/src/upstreams/ServiceSection.i18n.ts b/src/upstreams/ServiceSection.i18n.ts index c2c4530e..a3ef6374 100644 --- a/src/upstreams/ServiceSection.i18n.ts +++ b/src/upstreams/ServiceSection.i18n.ts @@ -19,4 +19,24 @@ export const serviceSectionText = messages( }, none: "No matching service", }, + { + "zh-Hant": { + search: "搜尋服務", + groups: { + vendor: "模型廠商", + platform: "平臺與中轉", + local: "本機與自定義", + }, + none: "沒有匹配的服務", + }, + es: { + search: "Servicios de búsqueda", + groups: { + vendor: "Proveedores de modelos", + platform: "Plataformas y enlaces", + local: "Local y costumbre", + }, + none: "Sin servicio de correspondencia", + }, + }, ); diff --git a/src/upstreams/ShareDialog.i18n.ts b/src/upstreams/ShareDialog.i18n.ts index 938f4733..db109be5 100644 --- a/src/upstreams/ShareDialog.i18n.ts +++ b/src/upstreams/ShareDialog.i18n.ts @@ -135,4 +135,126 @@ export const shareDialogText = messages( other: "some settings", }, }, + { + "zh-Hant": { + secrets: "包含金鑰", + secretsWhat: "上游金鑰", + secretsNote: "連結包含金鑰。持有連結即可使用該金鑰,請僅透過可信渠道傳送。", + link: "連結", + copyWeb: "複製網頁連結", + copyApp: "複製 thinkwatch:// 連結", + webHint: "網頁連結在未安裝 Lite 的裝置上顯示安裝說明;# 之後的內容不傳送至網站伺服器。", + tooLong: (n: number) => `連結長 ${n} 個字元,超過 8192 個字元的上限,無法以連結形式分享。可改用配置包。`, + invalid: "此上游無法寫成匯入連結。可改用配置包。", + failed: "無法生成連結", + exportPack: "匯出為配置包…", + carried: { + address: "地址", + protocol: "協議", + key: "金鑰", + headers: (n: number) => `${n} 個請求頭`, + oauth: "OAuth 憑據", + aws: "AWS 訪問金鑰", + models: (n: number) => `${n} 個模型`, + scope: "只用這些模型", + specs: (n: number) => `${n} 個模型的規格`, + prices: (n: number) => `${n} 個模型的價格`, + multiplier: "價格倍率", + billing: "計費方式", + balance: "餘額來源", + concurrency: "併發上限", + minSpeed: "最低生成速度", + limits: (n: number) => `${n} 條用量上限`, + identity: "轉發用戶端身份", + login: "登入方式(接收方須登入)", + }, + left: { + secrets: "金鑰", + env: "以 ${變數名} 書寫的值(連結不接受該寫法)", + login: "登入憑據", + awsProfile: "AWS profile", + proxy: "出站代理", + routes: "路由", + disabled: "停用狀態", + tiers: "200K 以上的分檔價格", + reasoningEffort: "手動推理檔位(請使用配置包分享)", + rejected: (what: string) => `${what}(連結不接受其中的字元)`, + }, + params: { + name: "名稱", + key: "金鑰", + headers: "請求頭", + models: "模型列表", + models_only: "只用這些模型", + specs: "模型規格", + prices: "價目", + price_multiplier: "價格倍率", + oauth: "OAuth 憑據", + aws: "AWS 訪問金鑰", + other: "部分設定", + }, + }, + es: { + title: (name: string) => `Compartir “${name}”`, + secrets: "Incluir teclas", + secretsWhat: "Tecla ascendente", + secretsNote: "El enlace contiene la clave. Cualquiera que tenga el enlace puede utilizar la clave; envíelo sólo a través de canales de confianza.", + link: "Enlace", + copyWeb: "Copiar enlace web", + copyApp: "Copiar el enlace thinkwatch://", + webHint: "En un dispositivo sin Lite, el enlace web muestra cómo instalarlo. La parte después de # no se envía al servidor del sitio web.", + tooLong: (n: number) => `El enlace es ${n} caracteres de largo, sobre el límite de 8192 caracteres, por lo que no se puede compartir como un enlace. Utilice un paquete de configuración en su lugar.`, + invalid: "Este upstream no se puede escribir como un enlace de importación. Utilice un paquete de configuración en su lugar.", + failed: "No se pudo crear el enlace", + exportPack: "Exportar como paquete de configuración…", + done: "Hecho", + includes: (items: string) => `Incluye: ${items}.`, + excludes: (items: string) => `Deja fuera: ${items}.`, + carried: { + address: "dirección", + protocol: "protocolo", + key: "tecla", + headers: (n: number) => s(n, "encabezado", "encabezados"), + oauth: "Credenciales de OAuth", + aws: "Claves de acceso AWS", + models: (n: number) => s(n, "modelo", "modelos"), + scope: "sólo estos modelos", + specs: (n: number) => `Especificaciones de ${s(n, "modelo", "modelos")}`, + prices: (n: number) => `precios de ${s(n, "modelo", "modelos")}`, + multiplier: "multiplicador de precios", + billing: "facturación", + balance: "fuente de balance", + concurrency: "límite de condition", + minSpeed: "velocidad mínima de generación", + limits: (n: number) => s(n, "límite de uso", "límites de uso"), + identity: "identidad del cliente reenviada", + login: "Método de inicio de sesión (los signos del receptor en)", + }, + left: { + secrets: "teclas", + env: "valores escritos como ${NAME} (los enlaces no los aceptan)", + login: "Credenciales de inicio de sesión", + awsProfile: "Perfil AWS", + proxy: "proxy saliente", + routes: "rutas", + disabled: "Estado de discapacidad", + tiers: "precios por encima de 200K", + reasoningEffort: "niveles de razonamiento manual (usar un paquete de configuración para compartirlos)", + rejected: (what: string) => `${what} (los enlaces de caracteres no aceptan)`, + }, + params: { + name: "nombre", + key: "tecla", + headers: "encabezados", + models: "lista de modelos", + models_only: "sólo estos modelos", + specs: "Especificaciones del modelo", + prices: "precios", + price_multiplier: "multiplicador de precios", + oauth: "Credenciales de OAuth", + aws: "Claves de acceso AWS", + other: "algunos ajustes", + }, + }, + }, ); diff --git a/src/upstreams/TestDialogs.i18n.ts b/src/upstreams/TestDialogs.i18n.ts index d071daa2..6ef78a52 100644 --- a/src/upstreams/TestDialogs.i18n.ts +++ b/src/upstreams/TestDialogs.i18n.ts @@ -89,4 +89,130 @@ export const testDialogsText = messages( start: "Start test", }, }, + { + "zh-Hant": { + total: "合計", + connection: { + title: "檢測連線", + desc: "驗證地址與憑據,並獲取模型列表。不產生費用。", + checking: "正在檢測", + }, + link: { + title: "鏈路測速", + allUpstreams: "全部上游", + desc: "測量 DNS 解析、TCP 握手、TLS 握手各階段耗時;經代理時包含代理握手。不產生費用。", + empty: "尚無上游。", + via: "經由", + stages: "各階段", + direct: "直連", + again: "重新測速", + }, + speed: { + title: "推理測速", + desc: "向所選上游各傳送一次推理請求,測量首 token 時間。此操作按量計費。", + model: "模型", + loadingModels: "正在讀取模型列表", + noModels: "尚無可用模型。先為上游獲取模型列表或手動新增模型。", + upstreams: "上游", + estimate: "費用預估", + quoting: "計算中", + pricingDate: (date: string) => `價格資料 ${date}`, + inputTokens: "輸入 tokens", + maxOutput: "輸出上限", + estimatedCost: "預估費用", + uncalculable: "無法計算", + noLimit: "不限", + byUsage: "按實際用量", + totalUncalculable: "無法計算:部分上游沒有金額", + noneSelected: "未選擇上游", + results: "測速結果", + firstToken: "首 token", + totalTime: "總耗時", + tokens: "輸入 → 輸出 tokens", + again: "再次測速", + start: "開始測速", + }, + }, + ko: { + upstream: "업스트림", + link: { + title: "Connection test", + allUpstreams: "모든 업스트림", + desc: "Measures how long DNS resolution, the TCP handshake and the TLS handshake take, including the proxy handshake when a proxy is used. Incurs no cost.", + empty: "No upstreams yet.", + via: "Via", + stages: "Stages", + direct: "Direct", + again: "Test again", + }, + speed: { + title: "Inference test", + desc: "Sends one inference request to each selected upstream and measures the time to first token. This test is billed per token.", + model: "모델", + loadingModels: "Loading model list", + noModels: "No models available yet. Fetch an upstream's model list or add models by hand first.", + upstreams: "업스트림", + estimate: "Cost estimate", + quoting: "Calculating", + pricingDate: (date: string) => `Prices as of ${date}`, + inputTokens: "Input tokens", + maxOutput: "Max output", + estimatedCost: "Estimated cost", + uncalculable: "Unknown", + noLimit: "No limit", + byUsage: "By actual usage", + totalUncalculable: "Unknown for some upstreams", + noneSelected: "No upstreams selected", + results: "Results", + firstToken: "First token", + totalTime: "Total time", + tokens: "Input → output tokens", + again: "Test again", + start: "Start test", + }, + }, + es: { + upstream: "Proveedor", + connection: { + title: "Comprobar la conexión", + desc: "Verifica la dirección y las credenciales, y obtiene la lista de modelos.", + checking: "Comprobación", + }, + link: { + title: "Prueba de conexión", + allUpstreams: "Todos los proveedores", + desc: "Mide el tiempo de resolución DNS, el apretón de manos TCP y el aprieto de manos de TLS, incluyendo el aprestón de mano proxy cuando se utiliza un proxy.", + empty: "No hay del proveedor todavía.", + via: "Vía", + stages: "Etapas", + direct: "Directo", + again: "Prueba de nuevo", + }, + speed: { + title: "Ensayo de inferencia", + desc: "Envía una petición de inferencia a cada uno seleccionado del proveedor y mide el tiempo para el primer token. Esta prueba se factura por token", + model: "Modelo", + loadingModels: "Cargando lista de modelos", + noModels: "No hay modelos disponibles todavía. Obtener una lista de modelos de del proveedor o añadir modelos a mano primero.", + upstreams: "Proveedores", + estimate: "Estimación de gastos", + quoting: "Cálculo", + pricingDate: (date: string) => `Precios a partir de ${date}`, + inputTokens: "tokens de entrada", + maxOutput: "Salida máxima", + estimatedCost: "Costo estimado", + uncalculable: "Desconocido", + noLimit: "Sin límite", + byUsage: "Por uso real", + totalUncalculable: "Desconocido para algunas del proveedor", + noneSelected: "No se han seleccionado los niveles anteriores", + results: "Resultados", + firstToken: "Primer token", + totalTime: "Tiempo total", + tokens: "Input → tokens de salida", + again: "Prueba de nuevo", + start: "Ensayo de inicio", + }, + }, + }, ); diff --git a/src/upstreams/UpstreamDialog.i18n.ts b/src/upstreams/UpstreamDialog.i18n.ts index e73cce14..cd413fc8 100644 --- a/src/upstreams/UpstreamDialog.i18n.ts +++ b/src/upstreams/UpstreamDialog.i18n.ts @@ -96,4 +96,85 @@ export const upstreamDialogText = messages( : `${modelsEn(models)} are not on the model list; their specs are not saved.`, specsFailed: (models: string[]) => `The specs of ${modelsEn(models)} could not be saved`, }, + { + "zh-Hant": { + sections: { + service: "服務型別", + connection: "連線", + account: "帳號", + models: "模型", + billing: "計費", + }, + connectionFailed: (error: string) => `連線失敗:${error}`, + unknownError: "未知錯誤", + checkFailed: "連線失敗", + continueAnyway: "仍然繼續", + titleEdit: "編輯上游", + pickService: "選擇要接入的服務", + namedSheet: (name: string) => `價目表「${name}」`, + defaultSheet: "預設價目表", + create: "建立", + cancelSignIn: "取消登入", + signingIn: "正在讀取上游", + createdNote: "上游已建立,關閉對話方塊不會撤銷登入", + name: "名稱", + nameTaken: "這個名稱已被佔用", + nameReplaces: "將替換該上游的金鑰", + importFrom: "來自匯入連結。", + importSendsTo: "請求和金鑰將發往 ", + importPlain: "這個地址不加密,金鑰和請求內容以明文傳輸。", + specsKept: (n: number) => `${n} 個模型的規格來自匯入連結,隨上游一起儲存。`, + specsSkipped: (models: string[]) => `${modelsZh(models)} 不在模型列表中,其規格不儲存。`, + specsFailed: (models: string[]) => `${modelsZh(models)} 的規格未能儲存`, + }, + ko: { + sections: { + service: "Service", + connection: "연결", + account: "Account", + models: "모델", + billing: "Billing", + }, + name: "이름", + }, + es: { + sections: { + service: "Servicio", + connection: "Conexión", + account: "Cuenta", + models: "Modelos", + billing: "Facturas", + }, + connectionFailed: (error: string) => `Falló la conexión: ${error}`, + unknownError: "Error desconocido", + checkFailed: "Ha fallado la conexión", + continueAnyway: "Continúa de todos modos.", + titleEdit: "Editar en sentido ascendente", + titleNew: "Nueva fase anterior", + pickService: "Elija el servicio a conectar", + namedSheet: (name: string) => `hoja de precios “${name}”`, + defaultSheet: "la hoja de precios por defecto", + back: "Atrás", + next: "Siguiente", + create: "Crear", + finish: "Hecho", + cancelSignIn: "Cancelar el inicio de sesión", + signingIn: "Leyendo el curso previo", + createdNote: "Se ha creado el upstream; cerrar este diálogo no deshaga el inicio de sesión", + name: "Nombre", + nameTaken: "Este nombre ya está en uso", + nameReplaces: "Se sustituirá la clave de esa corriente.", + importFrom: "De un enlace de importación. ", + importSendsTo: "Solicitudes y claves serán enviadas a ", + importAnd: " y ", + importPlain: "Esta dirección no está cifrada; la clave y el contenido de la solicitud viajan en texto plano.", + specsKept: (n: number) => n === 1 + ? "Las especificaciones de 1 modelo provienen del enlace de importación y se guardan con el upstream." + : `Las especificaciones de los modelos ${n} provienen del enlace de importación y se guardan con el upstream.`, + specsSkipped: (models: string[]) => models.length === 1 + ? `${modelsEn(models)} no está en la lista de modelos; sus especificaciones no se guardan.` + : `${modelsEn(models)} no están en la lista de modelos; sus especificaciones no se guardan.`, + specsFailed: (models: string[]) => `Las especificaciones de ${modelsEn(models)} no pudieron ser salvadas`, + }, + }, ); diff --git a/src/upstreams/UpstreamTable.i18n.ts b/src/upstreams/UpstreamTable.i18n.ts index 5ed556c1..808d842b 100644 --- a/src/upstreams/UpstreamTable.i18n.ts +++ b/src/upstreams/UpstreamTable.i18n.ts @@ -153,4 +153,113 @@ export const upstreamTableText = messages( speedTip: (samples: number) => `Speed · ${samples.toLocaleString()} ${samples === 1 ? "sample" : "samples"}`, }, + { + "zh-Hant": { + quota: "額度 / 計費", + day: "24 小時", + disabledTip: "已停用的上游不參與轉發。", + circuitOpen: "熔斷中", + circuitOpenTip: "此上游連續失敗,暫不參與轉發。", + authRejected: "憑據被拒", + authRejectedTip: (status: number) => `上游返回未授權(${status}),該上游的憑據可能已失效。`, + needsLogin: "需要重新登入", + needsLoginTip: "帳號的登入已失效。重新登入之前,經此上游的請求都會失敗。", + inputHigh: "輸入 token 偏多", + inputLow: "輸入 token 偏少", + cacheLow: "快取讀取偏低", + modelDiffersTip: (n: number, of: number) => `最近 7 天的 ${of.toLocaleString()} 次回答中,${n.toLocaleString()} 次寫的模型名與發出的不同:`, + modelPair: (sent: string, answered: string, n: number) => `發出 ${sent},回答 ${answered} · ${n.toLocaleString()} 次`, + inputTip: "最近 7 天,上游報告的輸入 token 為本地估算的倍數,與服務同一模型的其他上游相比:", + inputLine: (model: string, gap: string, here: string, hereN: number, k: number, others: string, othersN: number) => `${model} ${gap}:本上游 ${here}(${hereN.toLocaleString()} 次)· 其他 ${k} 個上游 ${others}(${othersN.toLocaleString()} 次)`, + cacheTip: "最近 7 天,可命中快取的輪次中輸入從快取讀取的比例,與服務同一模型的其他上游相比:", + cacheLine: (model: string, here: string, hereN: number, k: number, others: string, othersN: number) => `${model}:本上游 ${here}(${hereN.toLocaleString()} 輪)· 其他 ${k} 個上游 ${others}(${othersN.toLocaleString()} 輪)`, + inFlight: (n: number) => `${n} 個請求進行中`, + inFlightOf: (n: number, max: number) => `${n} 個請求進行中,併發上限 ${max} 個`, + check: "檢測連線", + linkTest: "鏈路測速", + speedTest: "推理測速…", + refreshModels: "重新整理模型列表", + refreshBalance: "重新整理餘額", + account: "額度與重置卡…", + traffic: "檢視流量", + select: (name: string) => `選擇 ${name}`, + selectAll: "選擇全部上游", + enable: "啟用", + locate: "在配置檔案中定位", + via: (egress: string) => `經 ${egress}`, + quotaOf: (window: string) => `${window}額度`, + windowLine: (window: string, used: number, left: string | null, reset: string | null) => `${window}額度:${[`已用 ${used}%`, left, reset && `${reset}重置`].filter(Boolean).join(",")}`, + sheet: (name: string) => `價目表 ${name}`, + defaultSheet: "預設", + unpriced: (n: number) => `${n} 次無法計價`, + dayRequests: (n: number) => `24 小時 ${n.toLocaleString()} 次請求`, + dayFailed: (n: number, success: number) => `失敗 ${n.toLocaleString()} 次,成功率 ${rate(success)}%`, + dayNoFailures: "無失敗", + dayCost: (cost: string) => `費用 ${cost}`, + latencyTip: (p95: string, samples: number) => `首 token P95 ${p95} · ${samples.toLocaleString()} 個樣本`, + speedTip: (samples: number) => `生成速度 · ${samples.toLocaleString()} 個樣本`, + }, + ko: { + upstream: "업스트림", + models: "모델", + actionsColumn: "작업", + disabled: "비활성화됨", + }, + es: { + upstream: "Proveedor", + models: "Modelos", + quota: "Cuota/facturación", + day: "24 horas", + timing: "TTFT / velocidad", + actionsColumn: "Acciones", + disabled: "Desactivado", + disabledTip: "No se recibe ninguna solicitud.", + circuitOpen: "Circuito abierto", + circuitOpenTip: "Este curso previo fracasó repetidamente y no recibe solicitudes por ahora.", + authRejected: "Credenciales rechazadas", + authRejectedTip: (status: number) => `El upstream devolvió una respuesta no autorizada (${status}). La credencial para este upsteam puede ya no ser válida.`, + needsLogin: "Inicie sesión de nuevo", + needsLoginTip: "El inicio de sesión de la cuenta ha expirado. Hasta que la cuenta se inicie de nuevo, las solicitudes a través de este upstream fallarán.", + modelDiffers: "El nombre del modelo difiere", + inputHigh: "Aportaciones notificadas altas", + inputLow: "Insumo notificado bajo", + cacheLow: "Lectura de caché baja", + modelDiffersTip: (n: number, of: number) => `Durante los últimos 7 días, en ${n.toLocaleString()} de ${count(of, "respuesta", "respuestas")}, el modelo nombrado difiere del enviado:`, + modelPair: (sent: string, answered: string, n: number) => `Enviado ${sent}, contestado ${answered} · ${n.toLocaleString()}×`, + inputTip: "En los últimos 7 días, los tokens de entrada reportados por el upstream como un múltiplo de la estimación local, en comparación con otros upsteams que sirven al mismo modelo:", + inputLine: (model: string, gap: string, here: string, hereN: number, k: number, others: string, othersN: number) => `${model} ${gap}: esta del proveedor ${here} (${count(hereN, "solicitud", "solicitudes")}) · ${count(k, "otras del proveedor", "otras del proveedor")} ${others} (${count(othersN, "solicitud", "solicitudes")})`, + cacheTip: "En los últimos 7 días, la cuota de entrada leída desde la caché del prompt sobre vueltas que podrían leerlo, en comparación con otras del proveedor que sirven al mismo modelo:", + cacheLine: (model: string, here: string, hereN: number, k: number, others: string, othersN: number) => `${model}: esta del proveedor ${here} (${count(hereN, "girar", "giros")}) · ${count(k, "otras del proveedor", "otras del proveedor")} ${others} (${count(othersN, "girar", "giros")})`, + inFlight: (n: number) => (n === 1 ? "1 solicitud en curso" : `${n} solicitudes en curso`), + inFlightOf: (n: number, max: number) => `${n === 1 ? "1 solicitud" : `${n} solicitudes`} en curso, límite de concurrencia ${max}`, + actions: (name: string) => `Acciones en relación con ${name}`, + check: "Comprobar la conexión", + linkTest: "Prueba de conexión", + speedTest: "Prueba de inferencia…", + refreshModels: "Actualizar la lista de modelos", + refreshBalance: "Actualizar el saldo", + account: "Límites de uso y reinicio de créditos…", + traffic: "Ver tráfico", + share: "Compartir…", + select: (name: string) => `Seleccionar ${name}`, + selectAll: "Seleccionar todas las del proveedor", + enable: "Activar", + disable: "Desactivar", + locate: "Mostrar en el archivo de configuraciónuración", + modelsOf: (name: string) => `Modelos para ${name}`, + used: (percent: number) => `${percent}% utilizado`, + quotaOf: (window: string) => `${window} límite de uso`, + windowLine: (window: string, used: number, left: string | null, reset: string | null) => `${window} límite: ${[`${used}% utilizado`, left, reset && `reinicia ${reset}`].filter(Boolean).join(", ")}`, + sheet: (name: string) => `Ficha de precios: ${name}`, + defaultSheet: "predeterminado", + requests: (n: number) => (n === 1 ? "1 solicitud" : `${n.toLocaleString()} solicitudes`), + unpriced: (n: number) => `${n} sin precio`, + dayRequests: (n: number) => n === 1 ? "1 solicitud en 24 horas" : `${n.toLocaleString()} solicitudes en 24 horas`, + dayFailed: (n: number, success: number) => `${n.toLocaleString()} falló, ${rate(success)}% tuvo éxito`, + dayNoFailures: "No hay fallas", + dayCost: (cost: string) => `Coste ${cost}`, + latencyTip: (p95: string, samples: number) => `Primer símbolo P95 ${p95} · ${samples.toLocaleString()} ${samples === 1 ? "Muestra" : "muestras"}`, + speedTip: (samples: number) => `Velocidad · ${samples.toLocaleString()} ${samples === 1 ? "Muestra" : "muestras"}`, + }, + }, ); diff --git a/src/upstreams/UpstreamsPage.i18n.tsx b/src/upstreams/UpstreamsPage.i18n.tsx index b28a55a4..bd18ce2e 100644 --- a/src/upstreams/UpstreamsPage.i18n.tsx +++ b/src/upstreams/UpstreamsPage.i18n.tsx @@ -126,4 +126,163 @@ export const upstreamsPageText = messages( sheetGone: "Deleting removes this price sheet's multiplier and model overrides from the config file. They can be restored from the backups.", }, + { + "zh-Hant": { + hero: { + upstreams: (n: ReactNode, _count: number) => <>{n} 個上游, + healthy: (n: ReactNode) => <>{n} 正常, + attention: (n: ReactNode, _count: number) => <>{n} 需處理, + disabled: (n: ReactNode) => <>{n} 已停用, + requests: (n: ReactNode, _count: number) => <>24 小時 {n} 次請求, + cost: (n: ReactNode) => <>費用 {n}, + }, + modelsFailed: (name: string) => `${name} 的模型列表獲取失敗`, + modelsFetched: (name: string, n: number) => `${name}:已獲取 ${n} 個模型`, + balanceReading: (name: string) => `正在讀取 ${name} 的餘額…`, + balanceReadEmpty: (name: string) => `已讀取 ${name} 的餘額`, + balanceFailed: (name: string) => `${name} 的餘額讀取失敗`, + pricesUpdated: (changed: number) => `預設價目表已更新,${changed} 個模型的價格有變化`, + pricesCurrent: "預設價目表已是最新", + tabs: { upstreams: "上游", proxies: "代理", pricing: "價目表" }, + linkTest: "鏈路測速", + speedTest: "推理測速", + exportSelected: (n: number) => `匯出所選 ${n} 個上游…`, + importConfig: "匯入配置…", + checkAll: "檢測全部", + autoUpdate: "自動更新", + newSheet: "新建價目表", + noUpstreams: "尚無上游", + noUpstreamsDesc: "上游是閘道器轉發請求的目標服務。新建上游並填寫介面地址與憑據後,用戶端請求即可經閘道器發出。", + noProxies: "尚無代理", + noProxiesDesc: "上游預設直連。需要經代理訪問的上游,先新建代理,再在上游的連線設定中選擇它。", + statsFailed: "24 小時統計讀取失敗", + statusFailed: "預設價目表狀態讀取失敗", + updateFailedTitle: "預設價目表更新失敗", + unpricedTitle: (n: number) => `最近 7 天有 ${n.toLocaleString()} 次請求無法計價`, + more: (total: number, _shown: number) => ` 等 ${total} 項`, + unpricedEnd: ",相關費用未計入統計。", + setPrices: "設定價格", + enabledToast: (name: string) => `已啟用上游 ${name}`, + saved: (name: string) => `已儲存 ${name}`, + what: { upstream: "上游", proxy: "代理", sheet: "價目表" }, + upstreamGone: "刪除後,此上游的地址、憑據與設定將從配置檔案中移除,可從備份中恢復。", + proxyGone: "刪除後,此代理的地址與認證資訊將從配置檔案中移除,可從備份中恢復。", + sheetGone: "刪除後,此價目表的倍率與模型覆蓋將從配置檔案中移除,可從備份中恢復。", + }, + ja: { + hero: { + upstreams: (n: ReactNode, _count: number) => <>{n} 件のアップストリーム, + healthy: (n: ReactNode) => <>正常 {n} 件, + attention: (n: ReactNode, _count: number) => <>要確認 {n} 件, + disabled: (n: ReactNode) => <>無効 {n} 件, + requests: (n: ReactNode, _count: number) => <>過去 24 時間のリクエスト {n} 件, + cost: (n: ReactNode) => <>費用 {n}, + }, + modelsFailed: (name: string) => `${name} のモデル一覧を取得できませんでした`, + modelsFetched: (name: string, n: number) => `${name}:${n} 個のモデルを取得しました`, + balanceReading: (name: string) => `${name} の残高を取得しています…`, + balanceRead: (name: string, brief: string) => `${name}:${brief}`, + balanceReadEmpty: (name: string) => `${name} の残高を取得しました`, + balanceFailed: (name: string) => `${name} の残高を取得できませんでした`, + pricesUpdated: (changed: number) => `既定の料金表を更新しました。${changed} 個のモデルの単価が変わりました`, + pricesCurrent: "既定の料金表は最新です", + tabs: { upstreams: "アップストリーム", proxies: "プロキシ", pricing: "料金表" }, + linkTest: "接続速度テスト", + speedTest: "推論速度テスト", + newUpstream: "アップストリームを追加", + exportSelected: (n: number) => `選択した ${n} 件をエクスポート…`, + importConfig: "設定をインポート…", + joinSync: "同期に参加…", + checkAll: "すべて確認", + newProxy: "プロキシを追加", + autoUpdate: "自動更新", + updateNow: "今すぐ更新", + newSheet: "料金表を作成", + noUpstreams: "アップストリームがありません", + noUpstreamsDesc: "アップストリームは転送先のサービスです。API アドレスと認証情報を登録すると、ゲートウェイからリクエストを転送できます。", + noProxies: "プロキシがありません", + noProxiesDesc: "通常は直接接続します。プロキシ経由で接続するには、プロキシを作成してアップストリームの接続設定で選択してください。", + statsFailed: "過去 24 時間の統計を読み込めませんでした", + statusFailed: "既定の料金表の状態を読み込めませんでした", + updateFailedTitle: "既定の料金表の更新に失敗しました", + unpricedTitle: (n: number) => `過去 7 日間のリクエスト ${n.toLocaleString("ja")} 件で料金を計算できませんでした`, + unpricedModels: "対象モデル", + listSep: "、", + provider: (name: string) => `(${name})`, + more: (total: number, _shown: number) => `など ${total} 件`, + unpricedEnd: "。これらの費用は集計されていません。", + setPrices: "料金を設定", + disabledToast: (name: string) => `アップストリーム ${name} を無効にしました`, + enabledToast: (name: string) => `アップストリーム ${name} を有効にしました`, + saved: (name: string) => `${name} を保存しました`, + what: { upstream: "アップストリーム", proxy: "プロキシ", sheet: "料金表" }, + upstreamGone: "アップストリームのアドレス、認証情報、設定を設定ファイルから削除します。バックアップから復元できます。", + proxyGone: "プロキシのアドレスと認証情報を設定ファイルから削除します。バックアップから復元できます。", + sheetGone: "料金表の倍率とモデル別設定を設定ファイルから削除します。バックアップから復元できます。", + }, + ko: { + hero: { + upstreams: (n: ReactNode, count: number) => <>{n} {count === 1 ? "업스트림" : "upstreams"}, + healthy: (n: ReactNode) => <>{n} healthy, + attention: (n: ReactNode, count: number) => <>{n} {count === 1 ? "needs" : "need"} attention, + disabled: (n: ReactNode) => <>{n} disabled, + requests: (n: ReactNode, count: number) => <>{n} {count === 1 ? "request" : "requests"} in 24 h, + cost: (n: ReactNode) => <>Cost {n}, + }, + tabs: { upstreams: "업스트림", proxies: "프록시", pricing: "Price sheets" }, + what: { upstream: "업스트림", proxy: "proxy", sheet: "price sheet" }, + }, + es: { + hero: { + upstreams: (n: ReactNode, count: number) => <>{n} {count === 1 ? "proveedor" : "del proveedor"}, + healthy: (n: ReactNode) => <>{n} sano, + attention: (n: ReactNode, count: number) => <>{n} {count === 1 ? "necesidades" : "necesidad"} atención, + disabled: (n: ReactNode) => <>{n} desactivado, + requests: (n: ReactNode, count: number) => <>{n} {count === 1 ? "solicitud" : "solicitudes"} en 24 h, + cost: (n: ReactNode) => <>Coste {n}, + }, + modelsFailed: (name: string) => `No se pudo obtener la lista de modelos para ${name}`, + modelsFetched: (name: string, n: number) => `${name}: ${n === 1 ? "1 modelo" : `${n} modelos`} se obtiene`, + balanceReading: (name: string) => `Leyendo el saldo para ${name}…`, + balanceReadEmpty: (name: string) => `Saldo debe decir ${name}`, + balanceFailed: (name: string) => `No se pudo leer el saldo para ${name}`, + pricesUpdated: (changed: number) => changed === 1 + ? "Actualización de la hoja de precios por defecto; cambio del precio de 1 modelo" + : `Actualización de la hoja de precios por defecto; cambio de los precios de los modelos ${changed}`, + pricesCurrent: "La hoja de precios por defecto está actualizada", + tabs: { upstreams: "Proveedores", proxies: "Proxies", pricing: "Fichas de precios" }, + linkTest: "Prueba de conexión", + speedTest: "Ensayo de inferencia", + newUpstream: "Nueva fase anterior", + exportSelected: (n: number) => (n === 1 ? "Exportar 1 seleccionado en sentido ascendente…" : `Exportar ${n} del proveedor seleccionadas…`), + importConfig: "Importar configuración…", + joinSync: "Unirse a la sincronización…", + checkAll: "Comprobar todo", + newProxy: "Nuevo proxy", + autoUpdate: "Actualización automática", + updateNow: "Actualizar ahora", + newSheet: "Nueva hoja de precios", + noUpstreams: "Sin del proveedor", + noUpstreamsDesc: "Un upstream es un servicio al que la puerta de enlace envía peticiones. Una vez que se crea uno con una URL base y credenciales, las peticiones del cliente salen a través de la puerta.", + noProxies: "Sin proxies", + noProxiesDesc: "Los flujos ascendentes se conectan directamente por defecto. Para un flujo ascendente que debe ser alcanzado a través de un proxy, cree el proxy primero y luego selecciónelo en la configuración de conexión del flujo ascendente.", + statsFailed: "No se pudieron cargar las estadísticas de 24 horas", + statusFailed: "No se pudo cargar el estado de la hoja de precios predeterminada", + updateFailedTitle: "No se pudo actualizar la hoja de precios por defecto", + unpricedTitle: (n: number) => n === 1 + ? "1 solicitud en los últimos 7 días fue sin precio" + : `${n.toLocaleString()} Las solicitudes en los últimos 7 días no tenían precio`, + unpricedModels: "Modelos afectados:", + more: (total: number, shown: number) => ` y ${total - shown} más`, + unpricedEnd: ". Su costo no está incluido en las estadísticas.", + setPrices: "Establecer precios", + disabledToast: (name: string) => `Upstream ${name} desactivado`, + enabledToast: (name: string) => `Corriente ascendente ${name} activada`, + saved: (name: string) => `${name} guardado`, + what: { upstream: "proveedor", proxy: "proxy", sheet: "hoja de precios" }, + upstreamGone: "Eliminar elimina la dirección, las credenciales y la configuración de este upstream desde el archivo de configuraciónuración. Se pueden restaurar desde las copias de seguridad.", + proxyGone: "Eliminar elimina la dirección de este proxy y los detalles de autenticación del archivo de configuraciónuración. Se pueden restaurar desde las copias de seguridad.", + sheetGone: "Eliminar elimina el multiplicador de esta hoja de precios y el modelo anula del archivo de configuraciónuración. Se pueden restaurar de las copias de seguridad.", + }, + }, ); diff --git a/src/upstreams/balance.i18n.ts b/src/upstreams/balance.i18n.ts index 29e6f8e9..9b9a96f5 100644 --- a/src/upstreams/balance.i18n.ts +++ b/src/upstreams/balance.i18n.ts @@ -84,4 +84,71 @@ export const balanceText = messages( expires: (date: string) => `Expires ${date}`, sheet: (name: string) => `Price sheet: ${name}`, }, + { + "zh-Hant": { + wallet: (amount: string) => `餘額 ${amount}`, + left: (pair: string) => `剩餘 ${pair}`, + spent: { + today: (amount: string) => `今日已用 ${amount}`, + month: (amount: string) => `本月已用 ${amount}`, + total: (amount: string) => `累計已用 ${amount}`, + }, + accountSpent: { + today: (amount: string) => `帳號今日已用 ${amount}`, + month: (amount: string) => `帳號本月已用 ${amount}`, + total: (amount: string) => `帳號累計已用 ${amount}`, + }, + sourceQuota: (source: string) => `${source} 額度`, + accountLimit: "帳號額度", + scopes: { key: "本金鑰", user: "帳號" }, + read: { + now: "剛剛讀取", + minutes: (n: number) => `${n} 分鐘前讀取`, + hours: (n: number) => `${n} 小時前讀取`, + at: (time: string) => `${time} 讀取`, + }, + failed: "餘額讀取失敗", + quotaLine: (used: string, left: string) => `額度:已用 ${used},剩餘 ${left}`, + quotaUsed: (used: string) => `額度:已用 ${used}`, + windowLine: (window: string, scope: string | null, used: string, percent: number, reset: string | null) => `${window}額度${scope ? `(${scope})` : ""}:已用 ${used}(${percent}%)${reset ? `,${reset}重置` : ""}`, + windowBrief: (window: string, scope: string | null, percent: number) => `${window}額度${scope ? `(${scope})` : ""}已用 ${percent}%`, + sheet: (name: string) => `價目表 ${name}`, + }, + es: { + wallet: (amount: string) => `Saldo ${amount}`, + left: (pair: string) => `${pair} izquierda`, + usedAmount: (amount: string) => `${amount} utilizados`, + used: (percent: number) => `${percent}% utilizado`, + units: { + tokens: (s: string) => `${s} fichas`, + requests: (s: string) => `${s} solicitudes`, + }, + spent: { + today: (amount: string) => `${amount} gastado hoy`, + month: (amount: string) => `${amount} pasó este mes`, + total: (amount: string) => `${amount} gastados hasta la fecha`, + }, + accountSpent: { + today: (amount: string) => `Cuenta: ${amount} hoy`, + month: (amount: string) => `Cuenta: ${amount} este mes`, + total: (amount: string) => `Cuenta: ${amount} hasta la fecha`, + }, + sourceQuota: (source: string) => `${source} cuota`, + accountLimit: "Límite de cuenta", + scopes: { key: "esta tecla", user: "cuenta" }, + read: { + now: "lea ahora mismo", + minutes: (n: number) => `leer ${n} min ago`, + hours: (n: number) => `leer ${n} h hace`, + at: (time: string) => `debe decir en ${time}`, + }, + failed: "Saldo no disponible", + quotaLine: (used: string, left: string) => `Contingente: ${used} utilizado, ${left} dejado`, + quotaUsed: (used: string) => `Contingente: ${used} utilizado`, + windowLine: (window: string, scope: string | null, used: string, percent: number, reset: string | null) => `${window} límite${scope ? ` (${scope})` : ""}: ${used} utilizado (${percent}%)${reset ? `, reinicia ${reset}` : ""}`, + windowBrief: (window: string, scope: string | null, percent: number) => `${window} límite${scope ? ` (${scope})` : ""} ${percent}% utilizado`, + expires: (date: string) => `Expira ${date}`, + sheet: (name: string) => `Ficha de precios: ${name}`, + }, + }, ); diff --git a/src/upstreams/labels.i18n.ts b/src/upstreams/labels.i18n.ts index 9151d59e..7474fdbf 100644 --- a/src/upstreams/labels.i18n.ts +++ b/src/upstreams/labels.i18n.ts @@ -176,4 +176,180 @@ export const labelsText = messages( cache_write_1h: "Cache writes 1h", }, }, + { + "zh-Hant": { + chatgptAccount: "ChatGPT 帳號", + protocolUnknown: "協議未識別", + billings: { + "per-token": { label: "按量計費", desc: "按價目表的單價與用量計算費用。" }, + free: { label: "不計費", desc: "費用記為 $0,例如本地模型。" }, + }, + proxyKinds: { + socks5h: "域名由代理解析,本機不發出 DNS 查詢。", + socks5: "域名在本機解析後,經代理連線目標地址。", + http: "透過 HTTP CONNECT 建立隧道。", + https: "與代理之間使用 TLS,再透過 CONNECT 建立隧道。", + }, + direct: "直連", + systemProxy: "系統代理", + apiKey: "API 金鑰", + accessKeys: "訪問金鑰", + accountSignIn: "帳號登入", + models: { + discovered: "自動發現", + manual: "手動新增", + failed: "獲取失敗", + noList: "未提供清單", + notFetched: "未獲取", + fetching: "獲取中", + scoped: "指定範圍", + }, + quotaWindows: { "5h": "5 小時", weekly: "每週", daily: "每天", monthly: "每月" }, + quotaSpans: { + w: (n: number) => `${n} 周`, + d: (n: number) => `${n} 天`, + h: (n: number) => `${n} 小時`, + m: (n: number) => `${n} 分鐘`, + }, + quotaSpansBefore: { + w: (n: number) => `${n} 周`, + d: (n: number) => `${n} 天`, + h: (n: number) => `${n} 小時`, + m: (n: number) => `${n} 分鐘`, + }, + quotaLeft: (left: string, total: string) => `剩餘 ${left} / ${total} 積分`, + l1Skips: { + plain_http: "http:// 地址不進行 TLS 握手", + ip_address: "地址已是 IP,無需 DNS 解析", + proxy_resolves: "域名由代理解析,本機不進行 DNS 解析", + }, + cannotConnect: "無法連線", + skips: { + disabled: "已停用", + out_of_scope: "不在啟用範圍內", + not_offered: "未提供此模型", + not_allowed: "金鑰不允許使用此模型", + busy: "併發已滿", + throttled: "速率限制中", + window_full: "用量已滿", + period_used_up: "本期用量已滿", + }, + defaultSheet: "預設價目表", + unpriced: "無法計價", + scaled: (multiplier: string) => `預設價目表 × ${multiplier}`, + override: "價目表覆蓋", + detailDefault: (date: string) => `預設價目表 · 資料日期 ${date}`, + detailScaled: (sheet: string, multiplier: string, date: string) => `價目表「${sheet}」· 預設價目表 × ${multiplier} · 資料日期 ${date}`, + detailOverride: (sheet: string) => `價目表「${sheet}」· 覆蓋價格`, + priceColumns: { + input: "輸入", + output: "輸出", + cache_read: "快取讀取", + cache_write_5m: "快取寫入 5 分鐘", + cache_write_1h: "快取寫入 1 小時", + }, + }, + ko: { + skips: { + disabled: "비활성화됨", + out_of_scope: "Model not enabled", + not_offered: "Model not offered", + not_allowed: "Model not allowed for this key", + busy: "At its concurrency limit", + throttled: "Rate limited", + window_full: "Usage limit reached", + period_used_up: "Usage limit reached for this period", + }, + priceColumns: { + input: "입력", + output: "출력", + cache_read: "Cache reads", + cache_write_5m: "Cache writes 5m", + cache_write_1h: "Cache writes 1h", + }, + }, + es: { + chatgptAccount: "Cuenta ChatGPT", + protocolUnknown: "Protocolo no detectado", + billings: { + "per-token": { + label: "Por token", + desc: "El costo se calcula a partir de los precios unitarios de la hoja de precios y el uso.", + }, + free: { label: "Libre", desc: "El costo se registra como $0, por ejemplo para los modelos locales." }, + }, + proxyKinds: { + socks5h: "El proxy resuelve nombres de dominio; no se envían consultas DNS desde este equipo.", + socks5: "Los nombres de dominio se resuelven en esta computadora, luego se accede a través del proxy.", + http: "Túneles a través de HTTP CONNECT.", + https: "Se conecta al proxy sobre TLS, luego túneles a través de CONNECT.", + }, + direct: "Directo", + systemProxy: "Proxy del sistema", + apiKey: "Clave API", + accessKeys: "Teclas de acceso", + accountSignIn: "Inicio de sesión en la cuenta", + models: { + discovered: "Descubierta", + manual: "Agregado a mano", + failed: "Ha fallado la obtención", + noList: "No se proporciona ninguna lista", + notFetched: "No obtenido", + fetching: "Obtener", + scoped: "Seleccionado", + }, + quotaWindows: { "5h": "5h", weekly: "Semanal", daily: "Diariamente", monthly: "mensual" }, + quotaSpans: { + w: (n: number) => (n === 1 ? "1 semana" : `${n} semanas`), + d: (n: number) => (n === 1 ? "1 día" : `${n} días`), + h: (n: number) => (n === 1 ? "1 hora" : `${n} horas`), + m: (n: number) => (n === 1 ? "1 minuto" : `${n} minutos`), + }, + quotaSpansBefore: { + w: (n: number) => `${n}-semana`, + d: (n: number) => `${n}-día`, + h: (n: number) => `${n}-hora`, + m: (n: number) => `${n} minutos`, + }, + quotaLeft: (left: string, total: string) => `${left} / ${total} créditos dejados`, + l1Steps: { + config: "Configuración", + dns: "Búsqueda de DNS", + tcp: "Apretón de manos TCP", + tls: "Apretón de manos TLS", + handshake: "Apretón de manos proxy", + }, + l1ToProxy: (step: string) => `${step} (poderes)`, + l1Skips: { + plain_http: "Sin apretón de manos TLS: la dirección utiliza http://", + ip_address: "Sin búsqueda de DNS: la dirección es una IP", + proxy_resolves: "No hay búsqueda local de DNS: el proxy resuelve el dominio", + }, + cannotConnect: "No se pudo conectar", + skips: { + disabled: "Desactivado", + out_of_scope: "Modelo no activado", + not_offered: "Modelo no ofrecido", + not_allowed: "Modelo no permitido para esta tecla", + busy: "En su límite de concurrencia", + throttled: "Tasa limitada", + window_full: "Límite de uso alcanzado", + period_used_up: "Límite de uso alcanzado para este período", + }, + defaultSheet: "Ficha de precios por defecto", + unpriced: "Sin precio", + scaled: (multiplier: string) => `Ficha de precios por defecto × ${multiplier}`, + override: "Superación de la hoja de precios", + detailDefault: (date: string) => `Ficha de precios por defecto · datos a partir de ${date}`, + detailScaled: (sheet: string, multiplier: string, date: string) => `Ficha de precios «${sheet}» · ficha de precios por defecto × ${multiplier} · datos a partir de ${date}`, + detailOverride: (sheet: string) => `Ficha de precios «${sheet}» · precio anulado`, + priceColumns: { + input: "Entrada", + output: "Salida", + cache_read: "Caché lee", + cache_write_5m: "Cache escribe 5m", + cache_write_1h: "Cache escribe 1h", + }, + }, + }, ); diff --git a/src/upstreams/presets.i18n.ts b/src/upstreams/presets.i18n.ts index de99e87a..729af6fa 100644 --- a/src/upstreams/presets.i18n.ts +++ b/src/upstreams/presets.i18n.ts @@ -50,4 +50,46 @@ export const presetsText = messages( ollama: [], }, }, + { + "zh-Hant": { + custom: "自定義", + desc: { + anthropic: "Claude 系列模型", + openai: "GPT 系列模型", + gemini: "Gemini 系列模型", + deepseek: "DeepSeek 系列模型", + zai: "GLM 系列模型", + bedrock: "AWS 上託管的多家模型", + openrouter: "多家模型的聚合平臺", + thinkwatch: "ThinkWatch 企業閘道器", + relay: "API 中轉平臺", + ollama: "本機執行的開源模型", + custom: "任何相容介面的服務", + }, + aliases: { + deepseek: ["深度求索"], + zai: ["智譜"], + thinkwatch: ["企業閘道器"], + sub2api: ["中轉"], + newapi: ["中轉"], + ollama: ["本地"], + }, + }, + es: { + custom: "Personalizado", + desc: { + anthropic: "Modelos Claude", + openai: "Modelos GPT", + gemini: "Modelos Géminis", + deepseek: "Modelos DeepSeek", + zai: "Modelos GLM", + bedrock: "Modelos alojados en AWS", + openrouter: "Muchos proveedores, una API", + thinkwatch: "Portal empresarial", + relay: "Plataforma de relé API", + ollama: "Modelos abiertos locales", + custom: "Cualquier API compatible", + }, + }, + }, ); diff --git a/src/upstreams/throttle.i18n.ts b/src/upstreams/throttle.i18n.ts index 96939163..677e9892 100644 --- a/src/upstreams/throttle.i18n.ts +++ b/src/upstreams/throttle.i18n.ts @@ -49,4 +49,35 @@ export const throttleText = messages( limitsTitle: "Usage limits", paused: (status: number, d: string) => `${status} · Paused ${d}`, }, + { + "zh-Hant": { + minutes: (m: number) => `${m} 分鐘`, + hours: (h: number) => `${h} 小時`, + hourMin: (h: number, m: number) => `${h} 小時 ${m} 分`, + rateLimited: (left: string) => `速率限制中 · ${left}後恢復`, + windowFull: (left: string) => `用量已滿 · ${left}後恢復`, + periodUsedUp: { + day: "今日用量已滿", + week: "本週用量已滿", + month: "本月用量已滿", + }, + rateLimitedTip: (at: string) => `上游返回 429,${at} 恢復傳送。`, + resumesAt: (at: string) => `${at} 恢復傳送。`, + paused: (status: number, d: string) => `${status} · 暫停 ${d}`, + }, + es: { + hours: (h: number) => unit(h, "hora", "horas"), + rateLimited: (left: string) => `Tasa limitada · volver en ${left}`, + windowFull: (left: string) => `Límite de uso alcanzado · en ${left}`, + periodUsedUp: { + day: "Límite de uso diario alcanzado", + week: "Límite de uso semanal alcanzado", + month: "Límite de uso mensual alcanzado", + }, + rateLimitedTip: (at: string) => `La del proveedor respondió 429. El envío continúa ${at}.`, + resumesAt: (at: string) => `Envío de currículums ${at}.`, + limitsTitle: "Límites de uso", + paused: (status: number, d: string) => `${status} · Pausa ${d}`, + }, + }, ); diff --git a/src/upstreams/upstreamForm.i18n.ts b/src/upstreams/upstreamForm.i18n.ts index 8399a588..8ebced5e 100644 --- a/src/upstreams/upstreamForm.i18n.ts +++ b/src/upstreams/upstreamForm.i18n.ts @@ -53,4 +53,60 @@ export const upstreamFormText = messages( unrecognized: "Model list format not recognized", empty: "Model list is empty", }, + { + "zh-Hant": { + name: "填寫名稱", + nameTaken: (name: string) => `名稱「${name}」已被其他上游使用`, + baseUrl: "填寫介面地址", + baseUrlBackslash: "介面地址中不能含反斜槓,請使用正斜槓 /", + baseUrlUserinfo: "介面地址的主機前不能帶使用者名稱或密碼,憑據請填在金鑰或請求頭中", + key: "填寫 API 金鑰", + signIn: "登入後繼續", + oauth: "填寫 Refresh Token 與 Token 端點", + accessKeys: "填寫訪問金鑰 ID 與私有訪問金鑰", + profile: "填寫 AWS profile 的名稱", + headerName: "填寫請求頭名稱", + headerValue: (header: string) => `填寫請求頭「${header}」的值`, + concurrency: "併發上限須為 1 到 1000 之間的整數", + minSpeed: "最低生成速度須為 1 到 1000 之間的整數", + minSpeedWindow: "判定時長鬚為 5 到 120 之間的整數", + limitRequired: "填寫用量上限的數值", + sheetName: "填寫價目表名稱", + sheetTaken: (name: string) => `價目表名稱「${name}」已被使用`, + pickModel: "至少選擇一個模型", + found: (n: number) => `發現 ${n} 個模型`, + notImplemented: (status: number) => `上游未提供模型列表介面(HTTP ${status})`, + unrecognized: "模型列表格式無法識別", + empty: "模型列表為空", + }, + ko: { + name: "이름을 입력하세요.", + }, + es: { + name: "Introduce un nombre.", + nameTaken: (name: string) => `El nombre “${name}” ya es usado por otra fuente`, + baseUrl: "Introduzca el URL de la base", + baseUrlBackslash: "La URL de la base no puede contener una barra inversa; utilice barras hacia adelante", + baseUrlUserinfo: "La URL base no puede tener un nombre de usuario o contraseña antes del host; poner credenciales en la clave o encabezados", + key: "Introduzca la tecla API", + signIn: "Inicia sesión para continuar", + oauth: "Ingrese el token de actualización y el punto final del token", + accessKeys: "Introduzca la clave de acceso ID y la clave secreta de acceso", + profile: "Introduzca el nombre del perfil AWS", + headerName: "Introduzca un nombre de cabecera", + headerValue: (header: string) => `Introduzca un valor para el encabezado “${header}”`, + concurrency: "El límite de concurrencia debe ser un número entero de 1 a 1000", + minSpeed: "La velocidad de generación mínima debe ser de 1 a 1000", + minSpeedWindow: "El período de medición debe ser de un número entero de 5 a 120", + limitRequired: "Introduzca una cantidad para cada límite de uso", + limitsInvalid: "Fijar los límites de uso", + sheetName: "Introduzca un nombre de hoja de precios", + sheetTaken: (name: string) => `El nombre de la hoja de precios “${name}” ya está en uso`, + pickModel: "Seleccionar al menos un modelo", + found: (n: number) => (n === 1 ? "1 modelo encontrado" : `${n} modelos encontrados`), + notImplemented: (status: number) => `Sin punto final de la lista de modelos (HTTP ${status})`, + unrecognized: "Formato de lista de modelos no reconocido", + empty: "La lista de modelos está vacía", + }, + }, ); diff --git a/src/useRequests.i18n.ts b/src/useRequests.i18n.ts index 2a2c361f..2abfc17b 100644 --- a/src/useRequests.i18n.ts +++ b/src/useRequests.i18n.ts @@ -8,4 +8,12 @@ export const requestsText = messages( { answeredLocally: "Answered locally", }, + { + "zh-Hant": { + answeredLocally: "本地應答", + }, + es: { + answeredLocally: "Respuestas locales", + }, + }, );