diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 53c64fff9..f8fb54f39 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4193,6 +4193,27 @@ const I18N = { "look for a plugin": "找找插件", ", or ": ",或", "credits": "积分", + // plugins' usage windows: their names and units, which the card and the tray's tooltip say (yi_time) + "Extra credits": "额外积分", + "Prepaid credits": "预付积分", + "Add-on credits": "加购积分", + "Dedicated credits": "专属积分", + "Shared credits": "共享积分", + "Total credits": "积分合计", + "Monthly credits": "每月积分", + "Purchased credits": "已购积分", + "Promotional Credits": "促销积分", + "Free model tokens": "免费模型 token", + "Free models": "免费模型", + "Free usage": "免费用量", + "Free trial": "免费试用", + "Monthly": "每月", + "Included": "套餐内", + "5-hour window": "5 小时窗口", + "Dollar Usage": "美元用量", + "Neurons/day (free allowance)": "每日 Neurons(免费额度)", + "AI Q&A": "AI 问答", + "questions": "次提问", "videos": "个视频", "Video · 24 hours": "视频 · 24 小时", "Video · 7 days": "视频 · 7 天", @@ -8608,6 +8629,27 @@ const I18N = { "look for a plugin": "找找外掛", ", or ": ",或", "credits": "積分", + // plugins' usage windows: their names and units, which the card and the tray's tooltip say (yi_time) + "Extra credits": "額外積分", + "Prepaid credits": "預付積分", + "Add-on credits": "加購積分", + "Dedicated credits": "專屬積分", + "Shared credits": "共享積分", + "Total credits": "積分合計", + "Monthly credits": "每月積分", + "Purchased credits": "已購積分", + "Promotional Credits": "促銷積分", + "Free model tokens": "免費模型 token", + "Free models": "免費模型", + "Free usage": "免費用量", + "Free trial": "免費試用", + "Monthly": "每月", + "Included": "方案內", + "5-hour window": "5 小時區間", + "Dollar Usage": "美元用量", + "Neurons/day (free allowance)": "每日 Neurons(免費額度)", + "AI Q&A": "AI 問答", + "questions": "次提問", "your Google Cloud project, with gcloud's sign-in": "你的 Google Cloud 專案,透過 gcloud 登入", "Project ID": "專案 ID", "Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there": "你的 Google Cloud 專案,需已啟用 Agent Platform API(aiplatform.googleapis.com):請求在這個專案中發出並計費", @@ -13044,6 +13086,27 @@ const I18N = { "look for a plugin": "プラグインを探す", ", or ": "、または", "credits": "クレジット", + // plugins' usage windows: their names and units, which the card and the tray's tooltip say (yi_time) + "Extra credits": "追加クレジット", + "Prepaid credits": "前払いクレジット", + "Add-on credits": "アドオンクレジット", + "Dedicated credits": "専用クレジット", + "Shared credits": "共有クレジット", + "Total credits": "クレジット合計", + "Monthly credits": "月間クレジット", + "Purchased credits": "購入済みクレジット", + "Promotional Credits": "プロモーションクレジット", + "Free model tokens": "無料モデルのトークン", + "Free models": "無料モデル", + "Free usage": "無料利用分", + "Free trial": "無料トライアル", + "Monthly": "月間", + "Included": "プラン内", + "5-hour window": "5 時間枠", + "Dollar Usage": "ドル利用額", + "Neurons/day (free allowance)": "1 日の Neurons(無料枠)", + "AI Q&A": "AI Q&A", + "questions": "件の質問", "videos": "本", "Video · 24 hours": "動画 · 24 時間", "Video · 7 days": "動画 · 7 日", @@ -17494,6 +17557,27 @@ const I18N = { "look for a plugin": "nach einer Erweiterung suchen", ", or ": ", oder ", "credits": "Credits", + // plugins' usage windows: their names and units, which the card and the tray's tooltip say (yi_time) + "Extra credits": "Zusätzliche Credits", + "Prepaid credits": "Prepaid-Credits", + "Add-on credits": "Add-on-Credits", + "Dedicated credits": "Dedizierte Credits", + "Shared credits": "Geteilte Credits", + "Total credits": "Credits gesamt", + "Monthly credits": "Monatliche Credits", + "Purchased credits": "Gekaufte Credits", + "Promotional Credits": "Aktionsguthaben", + "Free model tokens": "Token für kostenlose Modelle", + "Free models": "Kostenlose Modelle", + "Free usage": "Kostenlose Nutzung", + "Free trial": "Kostenlose Testphase", + "Monthly": "Monatlich", + "Included": "Inklusive", + "5-hour window": "5-Stunden-Fenster", + "Dollar Usage": "Dollar-Nutzung", + "Neurons/day (free allowance)": "Neurons pro Tag (Freikontingent)", + "AI Q&A": "KI-Fragen", + "questions": "Fragen", "videos": "Videos", "Video · 24 hours": "Video · 24 Stunden", "Video · 7 days": "Video · 7 Tage", diff --git a/internal/gui/tests/quota-window-words.test.cjs b/internal/gui/tests/quota-window-words.test.cjs new file mode 100644 index 000000000..97e031594 --- /dev/null +++ b/internal/gui/tests/quota-window-words.test.cjs @@ -0,0 +1,80 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// yi_time on Discord: a plugin names and counts its usage windows in +// English (WorkBuddy's "Credits" and "Extra credits", in "credits"), and +// the Usage page's card says them in the page's language, in every +// language magpie has, as the tray's tooltip does (traywords.go). No +// backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const quotas = [ + { provider: "workbuddy", name: "WorkBuddy", icon: "workbuddy-color", plan: "Pro", user: "李雷", windows: [ + { name: "Credits", used: 0, display: "0 / 500", amount: 0, limit: 500, unit: "credits" }, + { name: "Extra credits", used: 10, display: "20 / 200", amount: 20, limit: 200, unit: "credits", aside: true }, + ] }, + { provider: "qoder", name: "Qoder", icon: "qoder", plan: "Pro", user: "me@example.com", windows: [ + { name: "Add-on credits", used: 50, display: "50 / 100", amount: 50, limit: 100, unit: "credits" }, + ] }, +]; + +function serve(lang) { + const settings = { lang, theme: "light", currency: "usd" }; + const state = { agents: [], profiles: [], settings }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { wb: ["Credits", "Extra credits"], unit: "credits", qoder: "Add-on credits" }, + zh: { wb: ["积分", "额外积分"], unit: "积分", qoder: "加购积分" }, + "zh-TW": { wb: ["積分", "額外積分"], unit: "積分", qoder: "加購積分" }, + ja: { wb: ["クレジット", "追加クレジット"], unit: "クレジット", qoder: "アドオンクレジット" }, + de: { wb: ["Credits", "Zusätzliche Credits"], unit: "Credits", qoder: "Add-on-Credits" }, +}; +const squash = (s) => s.replace(/\s+/g, " ").trim(); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width}px ${lang}: a plugin's window names and units in the page's language`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=usage"); + + const card = page.locator(".subscription-card", { hasText: "WorkBuddy" }); + await card.locator(".quota-name").first().waitFor(); + const names = (await card.locator(".quota-name").allTextContents()).map(squash); + for (const n of w.wb) assert.ok(names.includes(n), `${lang} WorkBuddy names ${JSON.stringify(names)} lack ${n}`); + const count = squash(await card.locator(".quota-n").first().textContent()); + assert.ok(count.startsWith("0 / 500 " + w.unit), `${lang} count ${count}`); + const qoder = page.locator(".subscription-card", { hasText: "Qoder" }); + await qoder.locator(".quota-name").first().waitFor(); + assert.equal(squash(await qoder.locator(".quota-name").first().textContent()), w.qoder); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/traytip_words_test.go b/internal/gui/traytip_words_test.go new file mode 100644 index 000000000..a3220e573 --- /dev/null +++ b/internal/gui/traytip_words_test.go @@ -0,0 +1,86 @@ +package gui + +import ( + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// yi_time on Discord, magpie in Chinese on Windows (v0.1.2777): the tray +// icon's tooltip said "WorkBuddy / Credits 0 / 500 credits · 已用 0% · 27 +// 天 13 小时 后重置". The window's name and unit come from the WorkBuddy +// plugin in English; the Usage page's card says them in the page's +// language (t(w.name), t(w.unit)), and the tooltip says them as the card +// does, in every language. +func TestTrayTooltipSaysWindowWordsAsTheCard(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + at := now.Add(27*24*time.Hour + 13*time.Hour + 20*time.Minute) + card := provider.SubscriptionQuota{Provider: "workbuddy", Name: "WorkBuddy", + Windows: []provider.QuotaWindow{{Name: "Credits", Used: 0, ResetsAt: &at, Display: "0 / 500", Amount: 0, Limit: 500, Unit: "credits"}}} + want := map[string]string{ + "en": "WorkBuddy\nCredits 0 / 500 credits · 0% used · resets in 27d 13h", + "zh": "WorkBuddy\n积分 0 / 500 积分 · 已用 0% · 27 天 13 小时 后重置", + "zh-TW": "WorkBuddy\n積分 0 / 500 積分 · 已用 0% · 27 天 13 小時 後重設", + "ja": "WorkBuddy\nクレジット 0 / 500 クレジット · 使用済み 0% · 27日 13時間 後にリセット", + "de": "WorkBuddy\nCredits 0 / 500 Credits · 0% verbraucht · Reset in 27 T 13 h", + } + for lang, w := range want { + if _, tip := trayCardText(lang, card, now, false, false, nil); tip != w { + t.Errorf("%s tooltip =\n%q, want\n%q", lang, tip, w) + } + } + + // a pool's window, named with its pool (trayShared): the pool's name + // is the vendor's, its window's the page's + pooled := provider.SubscriptionQuota{Provider: "antigravity", Name: "Antigravity", + Windows: []provider.QuotaWindow{{Name: "5 hours", Pool: "Gemini", Used: 10, Aside: true}}} + if _, tip := trayCardText("zh", pooled, now, false, false, nil); !strings.Contains(tip, "Gemini · 5 小时 已用 10%") { + t.Errorf("zh pooled tooltip = %q", tip) + } +} + +// The words plugins name and count their usage windows in are said in every +// language the page has, so neither the card nor the tray's tooltip shows +// one in English (the names and units in magpie-community/plugins' +// usage() results, 2026-11-03; a model's or a plan's own name stays as +// given). +func TestPluginWindowWordsSaidInEveryLanguage(t *testing.T) { + words := []string{ + // units + "credits", "tokens", "requests", "questions", + // window names + "Credits", "Extra credits", "Prepaid credits", "Free model tokens", // workbuddy + "Add-on credits", "Dedicated credits", "Shared credits", "Total credits", // qoder + "Monthly credits", "Purchased credits", "5-hour window", // agnes + "Promotional Credits", // gcp-ai + "Free models", // devin + "Free usage", "Monthly", "Included", "Weekly", // cursor + "Free trial", // kiro + "Dollar Usage", // trae + "Neurons/day (free allowance)", // cloudflare-workers-ai + "AI Q&A", // orcaterm + "5 hours", "7 days", + } + for _, lang := range []string{"zh", "zh-TW", "ja", "de"} { + for _, w := range words { + if _, ok := pageWords()[lang][w]; !ok { + t.Errorf("i18n.js's %s doesn't say %q", lang, w) + } + } + } +} + +// parsePageWords reads every entry of a block, two to a line too, with +// its escapes, and leaves out what isn't an entry. +func TestParsePageWords(t *testing.T) { + src := "const I18N = {\n zh: {\n // a comment: \"not\": \"this\"\n \"Repository\": \"仓库\", \"Branch\": \"分支\",\n \"say \\\"{n}\\\"\": \"说「{n}」\",\n },\n \"zh-TW\": {\n \"Credits\": \"積分\",\n },\n};\nconst NOTICES = [\n \"Credits\": \"no\",\n];\n" + got := parsePageWords(src) + if got["zh"]["Repository"] != "仓库" || got["zh"]["Branch"] != "分支" || got["zh"][`say "{n}"`] != "说「{n}」" || got["zh-TW"]["Credits"] != "積分" { + t.Errorf("parsed %v", got) + } + if _, ok := got["zh"]["not"]; ok || len(got) != 2 { + t.Errorf("parsed a comment or past the table: %v", got) + } +} diff --git a/internal/gui/trayusage.go b/internal/gui/trayusage.go index b92c95b36..b9f0cfd2a 100644 --- a/internal/gui/trayusage.go +++ b/internal/gui/trayusage.go @@ -262,7 +262,9 @@ func trayUsageText(q provider.SubscriptionQuota, now time.Time, left, pace bool) // follows its figure, in both, as the Usage page's cards show it. The text // has the windows of the kinds given alone (trayShownKinds); the tooltip // has them all. The tooltip's own words are in lang (trayLang), as the -// tray menu's are; a window's name and an error are the card's. +// tray menu's are, and so are a window's name and unit where the page has +// a word for them, as its card says them (pageWord); an error is the +// card's. func trayCardText(lang string, q provider.SubscriptionQuota, now time.Time, left, pace bool, kinds []string) (label, tip string) { if strings.HasPrefix(q.Provider, trayTotal) { return q.Balance, q.Name // trayTotalCard's: its rows, and its tooltip @@ -310,9 +312,13 @@ func trayCardText(lang string, q provider.SubscriptionQuota, now time.Time, left if used != math.Trunc(used) { tipPct = fmt.Sprintf("%.1f%%", used) } - line := w.Name + " " + trayText(lang, word, tipPct) + // the window's name and its count's unit as its card says them + // (t(w.name), t(w.unit) in app.js) + name := trayWindowName(lang, w.Name) + w.Unit = pageWord(lang, w.Unit) + line := name + " " + trayText(lang, word, tipPct) if c := w.Count(left); c != "" { - line = w.Name + " " + c + " · " + trayText(lang, word, tipPct) + line = name + " " + c + " · " + trayText(lang, word, tipPct) } line += paceNote if at := resetAt(w, now); !at.IsZero() && at.After(now) { diff --git a/internal/gui/traywords.go b/internal/gui/traywords.go new file mode 100644 index 000000000..2c44fa376 --- /dev/null +++ b/internal/gui/traywords.go @@ -0,0 +1,87 @@ +package gui + +import ( + "encoding/json" + "regexp" + "strings" + "sync" +) + +// pageWords are the page's own translations (assets/i18n.js's I18N), by +// language, read once: the words a usage card's window is named and +// counted in ("Credits", "credits", "5 hours") come from the vendor or a +// plugin in English, and the Usage page says them with t(). The tray's +// tooltip says them with the same table (pageWord), so a window reads in +// the tray as on its card, in every language the page has (yi_time on +// Discord: "Credits 0 / 500 credits · 已用 0%"). +var pageWords = sync.OnceValue(func() map[string]map[string]string { + b, err := assets.ReadFile("assets/i18n.js") + if err != nil { + return nil + } + return parsePageWords(string(b)) +}) + +var ( + pageLangHead = regexp.MustCompile(`^ "?([\w-]+)"?: \{`) + pagePair = regexp.MustCompile(`"((?:[^"\\]|\\.)*)"\s*:\s*"((?:[^"\\]|\\.)*)"`) +) + +// parsePageWords reads I18N's language blocks from i18n.js's source: each +// ` zh: {` or ` "zh-TW": {` line starts one, and its entries are +// ` "English": "translation",` lines, one or more to a line. A string +// JSON can't read (a JS-only escape) is left out: that word reads in +// English, as the page's own fallback does. +func parsePageWords(src string) map[string]map[string]string { + if i := strings.Index(src, "\n};"); i >= 0 { + src = src[:i] + } + out := map[string]map[string]string{} + var cur map[string]string + for _, line := range strings.Split(src, "\n") { + if m := pageLangHead.FindStringSubmatch(line); m != nil { + cur = map[string]string{} + out[m[1]] = cur + continue + } + if cur == nil || !strings.HasPrefix(line, " \"") { + continue + } + for _, m := range pagePair.FindAllStringSubmatch(line, -1) { + var k, v string + if json.Unmarshal([]byte(`"`+m[1]+`"`), &k) != nil || json.Unmarshal([]byte(`"`+m[2]+`"`), &v) != nil { + continue + } + cur[k] = v + } + } + return out +} + +// pageWord is s as the page says it in lang (its t()): s itself in +// English, or where the page has no word for it. +func pageWord(lang, s string) string { + if v, ok := pageWords()[lang][s]; ok && v != "" { + return v + } + return s +} + +// trayWindowName is a window's name as its card says it in lang: the +// name whole when the page has it, else each " · " part the page has +// ("Gemini · 5 hours", a pool's window named with its pool by trayShared, +// a model's with its family by trayModels), as the card writes +// pool + " · " + t(name). +func trayWindowName(lang, name string) string { + if lang == "en" || name == "" { + return name + } + if w := pageWord(lang, name); w != name { + return w + } + parts := strings.Split(name, " · ") + for i, p := range parts { + parts[i] = pageWord(lang, p) + } + return strings.Join(parts, " · ") +}