diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9366ce289..a2e9e81b5 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3680,7 +3680,7 @@ function recoveredOnce() { const files = fresh.map((n) => n.file).join(", "); const bak = fresh.length === 1 && fresh[0].bak && !fresh[0].bak.startsWith("0001-") ? new Date(fresh[0].bak) : null; status(bak - ? t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.", { file: files, time: bak.toLocaleString(locale) }) + ? t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup of {time}. A change made after that may be missing; the damaged file is kept beside it.", { file: files, time: bak.toLocaleString(intlLang()) }) : t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.", { file: files }), "warn", 20000); } @@ -4666,7 +4666,7 @@ function contextTag(n, name) { if (!(n >= 1e6) || /\b\d+M\b/.test(name || "")) return null; const m = n / 1e6; const tag = el("span", "badge ctx", (Number.isInteger(m) ? m : m.toFixed(1)) + "M"); - tag.title = t("holds {n} tokens", { n: n.toLocaleString() }); + tag.title = t("holds {n} tokens", { n: n.toLocaleString(intlLang()) }); return tag; } @@ -6632,9 +6632,9 @@ function modelInfo(m) { lines.push(t(imgUnknown ? "Images: not known" : m.images ? (m.group ? "Accepts images (one of its models does)" : "Accepts images") : "Text only")); if (m.context) { box.append(el("span", "badge mi-ctx", ctxShort(m.context))); - lines.push(t(m.group ? "Context: {n} tokens (the largest of its models')" : "Context: {n} tokens", { n: m.context.toLocaleString() })); + lines.push(t(m.group ? "Context: {n} tokens (the largest of its models')" : "Context: {n} tokens", { n: m.context.toLocaleString(intlLang()) })); } - if (m.output) lines.push(t("Output: up to {n} tokens", { n: m.output.toLocaleString() })); + if (m.output) lines.push(t("Output: up to {n} tokens", { n: m.output.toLocaleString(intlLang()) })); if (m.group && m.members?.length) lines.push(t("Models: {models}", { models: m.members.join(", ") })); box.title = lines.join("\n"); return box; @@ -7160,7 +7160,7 @@ function renderActivity() { const chev = el("span", "call-chev"); chev.append(svg(CHEV_R, 11, 1.6)); r.append(chev); - r.append(el("span", "when", new Date(c.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }))); + r.append(el("span", "when", new Date(c.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" }))); r.append(el("span", "a", c.agent || "—")); r.append(el("span", "m", c.model)); r.append(el("span", "p", c.from === c.to ? c.from : `${c.from} → ${c.to}`)); @@ -12759,10 +12759,10 @@ function accountQuota(data, user, capFor = () => 0, settable = null) { m.append(el("span", "aq-n", t(w.name)), track, el("b", "", quotaText(w))); if (w.resetsAt) { const at = new Date(w.resetsAt); - m.title = resetText(at, at.toLocaleString()); + m.title = resetText(at, at.toLocaleString(intlLang())); if (used >= 80) m.append(el("span", "aq-r", resetInText(at))); } - const out = runsOutText(w, (at) => at.toLocaleString()); + const out = runsOutText(w, (at) => at.toLocaleString(intlLang())); if (out) m.title = [m.title, out].filter(Boolean).join("\n"); if (w.tiers) m.title = tiersText(w); line.append(settable ? settable(m, w) : m); @@ -12797,7 +12797,7 @@ function poolLine(line, ws, q, capFor = () => 0, settable = null) { m.append(settable ? settable(part, w) : part); } const w = p.ws[0]; - m.title = p.ws.map((x) => t(x.name) + " " + quotaText(x) + (x.resetsAt ? " · " + resetText(new Date(x.resetsAt), new Date(x.resetsAt).toLocaleString()) : "")).join("\n") + m.title = p.ws.map((x) => t(x.name) + " " + quotaText(x) + (x.resetsAt ? " · " + resetText(new Date(x.resetsAt), new Date(x.resetsAt).toLocaleString(intlLang())) : "")).join("\n") + (w.members ? "\n\n" + poolTip(w) : w.tiers ? "\n\n" + tiersText(w) : ""); line.append(m); } @@ -12909,7 +12909,7 @@ function capHeldNote(held, cap, several, direct) { // signed in to it isn't: the note doesn't say it is safe at its cap const n = el("span", "using acap-held acap-direct", t("At its cap · {agent} still uses it", { agent: direct })); n.title = t("A usage window is at {n}%, past this account's {cap}% cap: requests through magpie are refused with a usage-cap error until it renews", { n: Math.round(held.used), cap }) - + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString()) : "") + + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + "\n" + directNote(direct); return n; } @@ -12917,13 +12917,13 @@ function capHeldNote(held, cap, several, direct) { const names = held.some.join(", "); const n = el("span", "using acap-held", held.back ? t("{names} at its cap · back {in}", { names, in: untilText(held.back) }) : t("{names} at its cap", { names })); n.title = t("{names} is at {n}%, past this account's {cap}% cap, so magpie sends the requests it counts to the other accounts until it renews; other models still use this account", { names, n: Math.round(held.used), cap }) - + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString()) : "") + + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + (several ? "" : "\n" + t("With no other account on, those requests are refused with a usage-cap error until then")); return n; } const n = el("span", "using acap-held", held.back ? t("At its cap · back {in}", { in: untilText(held.back) }) : t("At its cap")); n.title = t("A usage window is at {n}%, past this account's {cap}% cap, so magpie counts it as used up and sends requests to the other accounts until that window renews", { n: Math.round(held.used), cap }) - + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString()) : "") + + (held.back ? " · " + resetText(new Date(held.back), new Date(held.back).toLocaleString(intlLang())) : "") + (several ? "" : "\n" + t("With no other account on, requests are refused with a usage-cap error until then")); return n; } @@ -12953,7 +12953,7 @@ function windowCapMeter(m, p, user, w) { b.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); b.click(); } }; b.append(...m.childNodes); if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own }))); - const reset = m.title || (w.resetsAt ? resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString()) : ""); + const reset = m.title || (w.resetsAt ? resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString(intlLang())) : ""); b.title = [reset, own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name }) : own ? t("{window} has a cap of its own: magpie counts this account as used up once {window} is at {n}%, until it renews. Click to change", { window: name, n: own }) : t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n"); @@ -13292,7 +13292,7 @@ function untilText(at) { return t("in {n}d", { n: Math.round(h / 24) }); } -function resetText(at, when = at <= Date.now() ? at.toLocaleString() : resetClock(at)) { +function resetText(at, when = at <= Date.now() ? at.toLocaleString(intlLang()) : resetClock(at)) { return t(at <= Date.now() ? "Reset time passed {when}" : "Resets {when}", { when }); } @@ -13469,7 +13469,7 @@ function renderKeyAccounts(p) { row.append(cp); // one the gateway passes over after a failure: why, and until when if (k.rest && new Date(k.rest.until) > Date.now()) { - const r = el("span", "key-rest", t("Resting · {why} · back at {time}", { why: (k.rest.status ? k.rest.status + " " : "") + t(KEY_FAIL[k.rest.why] || "failed"), time: new Date(k.rest.until).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })); + const r = el("span", "key-rest", t("Resting · {why} · back at {time}", { why: (k.rest.status ? k.rest.status + " " : "") + t(KEY_FAIL[k.rest.why] || "failed"), time: new Date(k.rest.until).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }) })); r.title = t("The gateway passes this key over until then, and tries the next one"); row.append(r); } @@ -14388,7 +14388,7 @@ const dayOfKey = (k) => new Date(k + "T12:00:00"); // isn't this one, one day alone as itself function rangeName({ from, to }) { const year = new Date().getFullYear(); - const name = (k) => dayOfKey(k).toLocaleDateString(intlLang() || "en", { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) }); + const name = (k) => dayOfKey(k).toLocaleDateString(intlLang(), { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) }); return from === to ? name(from) : name(from) + " – " + name(to); } // noCallsIn is what an empty page says of the period it is on @@ -14441,11 +14441,11 @@ function openRangeMenu(anchor, current, choose) { box.append(head, quick, nav, grid); const draw = (focusDay) => { head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last"); - month.textContent = shown.toLocaleDateString(intlLang() || "en", { year: "numeric", month: "long" }); + month.textContent = shown.toLocaleDateString(intlLang(), { year: "numeric", month: "long" }); next.disabled = dayKeyOf(new Date(shown.getFullYear(), shown.getMonth() + 1, 1, 12)) > today; const cells = []; // the weekdays, Monday first, as the app's weeks are - for (let i = 0; i < 7; i++) cells.push(el("span", "rm-wd", new Date(2024, 0, 1 + i, 12).toLocaleDateString(intlLang() || "en", { weekday: "narrow" }))); + for (let i = 0; i < 7; i++) cells.push(el("span", "rm-wd", new Date(2024, 0, 1 + i, 12).toLocaleDateString(intlLang(), { weekday: "narrow" }))); const first = new Date(shown); const lead = (first.getDay() + 6) % 7; for (let i = 0; i < lead; i++) cells.push(el("span", "rm-pad")); @@ -14455,7 +14455,7 @@ function openRangeMenu(anchor, current, choose) { const b = el("button", "rm-day", String(d.getDate())); b.type = "button"; b.dataset.day = k; - b.setAttribute("aria-label", d.toLocaleDateString(intlLang() || "en", { year: "numeric", month: "long", day: "numeric" })); + b.setAttribute("aria-label", d.toLocaleDateString(intlLang(), { year: "numeric", month: "long", day: "numeric" })); if (k === today) b.classList.add("today"); if (lo && (k === lo || k === hi)) b.classList.add("end"); if (lo && hi && k > lo && k < hi) b.classList.add("in"); @@ -15420,7 +15420,7 @@ function balanceCurve(sub) { if (d) g.append(sv("path", { d, class: "qc-line" }, { stroke: "var(--c1)" })); if (x1 > now) g.append(sv("line", { x1: X(now), x2: X(now), y1: 0, y2: H, class: "qc-now" })); pace.textContent = out ? t("Runs out {in} at this pace", { in: untilText(Math.max(out, now + 60e3)) }) : ""; - pace.title = out ? new Date(out).toLocaleString() : ""; + pace.title = out ? new Date(out).toLocaleString(intlLang()) : ""; g.setAttribute("aria-label", t("Balance over time") + (out ? " · " + pace.textContent : "")); axis.replaceChildren(el("span", "", quotaTimeText(x0, now)), el("span", "", quotaTimeText(x1, now))); }; @@ -15466,7 +15466,7 @@ function planTerm(q) { } function planSpan(q) { const s = el("span", "plan", [q.plan, planTerm(q)].filter(Boolean).join(" · ")); - if (q.until) s.title = t(q.renew === "auto" ? "Renews {date}" : q.renew === "off" ? "Expires {date}" : "Until {date}", { date: new Date(q.until).toLocaleString() }); + if (q.until) s.title = t(q.renew === "auto" ? "Renews {date}" : q.renew === "off" ? "Expires {date}" : "Until {date}", { date: new Date(q.until).toLocaleString(intlLang()) }); return s; } @@ -16066,7 +16066,7 @@ async function hidePanelUsage(key, hide) { // now (a vendor rate limiting its usage endpoint) says when it was read. function asOfText(q, short = false) { const text = short ? t("As of {when}", { when: stamp(q.asOf) }) - : t("As of {when} — couldn't be read just now", { when: new Date(q.asOf).toLocaleString() }); + : t("As of {when} — couldn't be read just now", { when: new Date(q.asOf).toLocaleString(intlLang()) }); return q.windows?.some((w) => w.resetsAt && new Date(w.resetsAt).getTime() <= Date.now()) ? text + " · " + t("A cached window has expired; current allowance is unknown") : text; } @@ -16127,7 +16127,7 @@ function panelQuotaCard(q) { rn.append(el("span", "", w.pool.split(/[ &]/)[0]), el("span", "", shortWindow(w.window))); } r.append(dial, rn); - r.title = t(w.name) + " · " + quotaText(w) + (w.resetsAt ? "\n" + resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString()) + (new Date(w.resetsAt) > Date.now() ? " · " + untilText(new Date(w.resetsAt)) : "") : "") + r.title = t(w.name) + " · " + quotaText(w) + (w.resetsAt ? "\n" + resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString(intlLang())) + (new Date(w.resetsAt) > Date.now() ? " · " + untilText(new Date(w.resetsAt)) : "") : "") + (w.tiers ? "\n\n" + tiersText(w) + "\n" : "") + (w.members ? "\n\n" + poolTip(w) + "\n" : "") + "\n" + t(quotaLeft ? "Show how much of each window is used" : "Show how much of each window is left"); @@ -16175,7 +16175,7 @@ function resetsWords(r, q) { if (r.until) { const at = new Date(r.until); w.append(el("span", "resets-until", " · " + t("until {when}", { when: resetClock(at) }))); - if (!r.each?.length) w.title += "\n" + t("The first runs out {when}", { when: at.toLocaleString() }); + if (!r.each?.length) w.title += "\n" + t("The first runs out {when}", { when: at.toLocaleString(intlLang()) }); } if (r.each?.length) w.title += "\n" + resetsEach(r); return w; @@ -16184,7 +16184,7 @@ function resetsWords(r, q) { if (r.until) { const at = new Date(r.until); w.append(el("span", "resets-until", " · " + t("until {when}", { when: resetClock(at) }))); - w.title = r.each?.length ? resetsEach(r) : t("The first runs out {when}", { when: at.toLocaleString() }); + w.title = r.each?.length ? resetsEach(r) : t("The first runs out {when}", { when: at.toLocaleString(intlLang()) }); // whether the one that runs out first is kept from going to waste: // with Auto-use on it is used shortly before it does (#624, #719) if (q && autoResetKept(q)) { @@ -16202,7 +16202,7 @@ function resetsWords(r, q) { // first, which the card already shows). function resetsEach(r) { return r.each.map((c, i) => { - const when = c.until ? new Date(c.until).toLocaleString() : ""; + const when = c.until ? new Date(c.until).toLocaleString(intlLang()) : ""; if (c.window === "fiveHour") return when ? t("Five-hour reset runs out {when}", { when }) : t("Five-hour reset never runs out"); if (c.window === "weekly") return when ? t("Weekly reset runs out {when}", { when }) : t("Weekly reset never runs out"); return when ? t("Reset {n} runs out {when}", { n: i + 1, when }) : t("Reset {n} never runs out", { n: i + 1 }); @@ -16214,7 +16214,7 @@ function resetsEach(r) { function resetUseTitle(q) { const r = q.resets; return (r.until - ? t("Uses the reset that runs out first ({when}), never one that lasts longer.", { when: new Date(r.until).toLocaleString() }) + ? t("Uses the reset that runs out first ({when}), never one that lasts longer.", { when: new Date(r.until).toLocaleString(intlLang()) }) : t("Uses one of its resets; none of them runs out.")) + "\n" + t("This account's windows start again at once, as if none had been used. You're asked before anything is spent."); } @@ -16510,7 +16510,7 @@ function askReset(q) { ed.append(el("p", "lib-confirm", t(q.resets.count === 1 ? "{who} has 1 reset. Using it starts its windows again at once, as if none of them had been used. It can't be undone." : "{who} has {n} resets. Using one starts its windows again at once, as if none of them had been used. It can't be undone.", { who, n: q.resets.count }))); - if (q.resets.until) ed.append(el("p", "lib-confirm", t("The one used is the one that runs out first, {when}.", { when: new Date(q.resets.until).toLocaleString() }))); + if (q.resets.until) ed.append(el("p", "lib-confirm", t("The one used is the one that runs out first, {when}.", { when: new Date(q.resets.until).toLocaleString(intlLang()) }))); // nothing used yet: a reset would start nothing again if (!q.windows?.some((w) => w.used > 0)) ed.append(el("p", "lib-confirm reset-idle", t("None of its windows has been used yet, so there is nothing to start again."))); const bar = el("div", "bar"); @@ -16655,7 +16655,7 @@ function readWhen(q, refresh = false) { const when = el("span", "quota-ago", t("Updated {when}", { when: ago(q.readAt) })); when.dataset.ago = q.readAt; s.append(when); - s.title = new Date(q.readAt).toLocaleString(); + s.title = new Date(q.readAt).toLocaleString(intlLang()); } else return null; if (refresh) s.prepend(quotaRefresh(q)); return s; @@ -16822,7 +16822,7 @@ function quotaWindows(sub) { r.append(el("span", "", resetText(at) + (at > Date.now() ? " ·" : ""))); if (at > Date.now()) r.append(" ", el("span", "", untilText(at))); quota.append(r); - quota.title = resetText(at, at.toLocaleString()); + quota.title = resetText(at, at.toLocaleString(intlLang())); } // credits that run out before then, or with no reset at all const out = runsOutText(w); @@ -16830,7 +16830,7 @@ function quotaWindows(sub) { if (!r) quota.append(r = el("div", "quota-reset")); else r.append(" · "); r.append(el("span", "", out + " ·"), " ", el("span", "", untilText(new Date(w.runsOutAt)))); - quota.title = [quota.title, runsOutText(w, (at) => at.toLocaleString())].filter(Boolean).join("\n"); + quota.title = [quota.title, runsOutText(w, (at) => at.toLocaleString(intlLang()))].filter(Boolean).join("\n"); } // what the whole window holds, by what magpie routed in it (Chiao), on // the reset's line, so the window keeps its three rows @@ -16933,7 +16933,7 @@ function renderUsage() { const n = u.series.length; const every = n <= 8 ? 1 : n <= 31 ? Math.ceil(n / 6) : Math.ceil(n / 5); // the day in the reader's language (the label comes as "Sep 5" in every one) - const dayOf = (p) => u.bucket === "hour" || !p.time ? p.label : new Date(p.time).toLocaleDateString(intlLang() || "en", { month: "short", day: "numeric" }); + const dayOf = (p) => u.bucket === "hour" || !p.time ? p.label : new Date(p.time).toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); u.series.forEach((p, i) => { const b = el("div", "bar"); const inp = el("i", "in"), out = el("i", "out"); @@ -17189,7 +17189,7 @@ function renderLedgerLoading() { } } -const ledNum = (n) => (n || 0).toLocaleString(intlLang() || "en"); +const ledNum = (n) => (n || 0).toLocaleString(intlLang()); // an average first token is a fraction of a millisecond: whole ones under a // second, rounded first so 999.6 reads 1.0 s rather than 1000 ms const ledTook = (ms = 0) => (ms = Math.round(ms) || 0) < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) }); @@ -17197,7 +17197,7 @@ function ledTime(when) { const d = new Date(when), now = new Date(); const opts = { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }; if (d.toDateString() !== now.toDateString()) Object.assign(opts, { month: "short", day: "numeric" }); - return d.toLocaleString(intlLang() || "en", opts); + return d.toLocaleString(intlLang(), opts); } // the model the reply named: amber, as the Routing page's tag, when it is // another than the one sent; plain when it is that one under a dated name, @@ -17539,7 +17539,7 @@ function ledCategories(l, split, metric) { // when a point is: the hour, the day or the week it stands for function ledWhen(p, bucket) { - const d = new Date(p.time), lang = intlLang() || "en"; + const d = new Date(p.time), lang = intlLang(); if (bucket === "hour") return d.toLocaleString(lang, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false }); const day = d.toLocaleDateString(lang, { year: "numeric", month: "2-digit", day: "2-digit" }); return bucket === "week" ? t("week of {label}", { label: day }) : day; @@ -17547,7 +17547,7 @@ function ledWhen(p, bucket) { function ledTick(p, bucket) { const d = new Date(p.time); if (bucket === "hour") return String(d.getHours()).padStart(2, "0") + ":00"; - return d.toLocaleDateString(intlLang() || "en", { month: "numeric", day: "numeric" }); + return d.toLocaleDateString(intlLang(), { month: "numeric", day: "numeric" }); } const SVGNS = "http://www.w3.org/2000/svg"; @@ -17969,7 +17969,7 @@ async function loadLedHeat() { } const ledHeatDate = (s) => { const [y, m, d] = String(s).split("-").map(Number); return new Date(y, m - 1, d); }; function ledHeatTip(x) { - const loc = intlLang() || "en"; + const loc = intlLang(); const tip = el("div"); tip.append(el("b", "", x.day.toLocaleDateString(loc, { year: "numeric", month: "short", day: "numeric", weekday: "short" }))); if (!x.calls) { @@ -18027,7 +18027,7 @@ function drawLedHeat() { l.style.gridArea = `${i + 2} / 1`; grid.append(l); } - const loc = intlLang() || "en"; + const loc = intlLang(); const weeks = Math.ceil(days.length / 7), labels = []; let month = -1; days.forEach((x, i) => { @@ -18355,7 +18355,7 @@ function renderLedger() { } const routeFilter = $("#ledRoute"); routeFilter.hidden = !ledRoute; - $("#ledRouteLabel").textContent = ledRouteInfo ? t("Request: {what}", { what: new Date(ledRouteInfo.time).toLocaleString(intlLang() || "en") + " · " + ledRouteInfo.model }) : ""; + $("#ledRouteLabel").textContent = ledRouteInfo ? t("Request: {what}", { what: new Date(ledRouteInfo.time).toLocaleString(intlLang()) + " · " + ledRouteInfo.model }) : ""; $("#ledRouteClear").title = t("Clear filter"); $("#ledRouteClear").setAttribute("aria-label", t("Clear filter")); $("#ledRouteClear").onclick = () => { @@ -18406,7 +18406,7 @@ function renderLedger() { // the link opens the route, not the row's details as well when.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; } - td(when, "when", new Date(r.t).toLocaleString(intlLang() || "en")); + td(when, "when", new Date(r.t).toLocaleString(intlLang())); const who = el("span", "who"); // an agent on another computer, whose magpie passed the request on const name = r.agentName || r.agent; @@ -18943,7 +18943,7 @@ function sessCost(s) { const sessModelNames = (models) => [...new Set(models.map((m) => m || t("a model with no name")))].join(", "); function ago(when) { const sec = (new Date(when) - Date.now()) / 1000; - const rtf = new Intl.RelativeTimeFormat(intlLang() || "en", { numeric: "auto" }); + const rtf = new Intl.RelativeTimeFormat(intlLang(), { numeric: "auto" }); for (const [unit, n] of [["year", 31536000], ["month", 2592000], ["week", 604800], ["day", 86400], ["hour", 3600], ["minute", 60]]) { if (Math.abs(sec) >= n) return rtf.format(Math.round(sec / n), unit); } @@ -18976,7 +18976,7 @@ function renderSessRange(loading) { // a "YYYY-MM-DD" as a local date, and back const sessDate = (d) => { const [y, m, day] = d.split("-").map(Number); return new Date(y, m - 1, day); }; const sessISO = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; -const sessDay = (d) => d.toLocaleDateString(intlLang() || "en", { month: "short", day: "numeric" }); +const sessDay = (d) => d.toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); // a length of time, as hours and minutes function fmtDur(sec) { const m = Math.round(sec / 60); @@ -19294,7 +19294,7 @@ function sessLegend() { } // the short names of the days of the week, Monday first function sessWeekdays() { - const loc = intlLang() || "en"; + const loc = intlLang(); return Array.from({ length: 7 }, (_, i) => new Date(2024, 0, 1 + i).toLocaleDateString(loc, { weekday: "short" })); } function sessCardHead(title) { @@ -19484,7 +19484,7 @@ function sessCalendar(days, value, tip, pad = 0) { l.style.gridArea = `${i + 2} / 1`; cal.append(l); } - const loc = intlLang() || "en"; + const loc = intlLang(); let month = -1, labelAt = -9; // the days before the range, from the Monday it is laid out from: their // months named as the range's are, the days themselves left blank diff --git a/internal/gui/assets/caller-keys.js b/internal/gui/assets/caller-keys.js index 1579e05b7..d28a5ec4d 100644 --- a/internal/gui/assets/caller-keys.js +++ b/internal/gui/assets/caller-keys.js @@ -403,7 +403,7 @@ function gatewayLimitLine(k) { parts.push(t(u.spent ? "refused until {when}" : "resets {when}", { when: resetClock(at) })); if (u.inFlight) parts.push(t(u.inFlight === 1 ? "1 in flight" : "{n} in flight", { n: u.inFlight })); line.textContent = parts.join(" · "); - line.title = t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(), when: at.toLocaleString() }) + line.title = t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(intlLang()), when: at.toLocaleString(intlLang()) }) + (u.unpriced ? "\n" + t("{n} calls without a known price aren't in the cost", { n: u.unpriced }) : ""); return line; } diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 34424a250..9a4d6e2be 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -608,7 +608,7 @@ pre.append(document.createTextNode(text.slice(at, at + TEXT_STEP))); at = Math.min(text.length, at + TEXT_STEP); more.hidden = at >= text.length; - more.textContent = t("Show more · {n} characters left", { n: (text.length - at).toLocaleString() }); + more.textContent = t("Show more · {n} characters left", { n: (text.length - at).toLocaleString(intlLang()) }); }; more.onclick = (e) => { e.stopPropagation(); step(); }; step(); @@ -624,9 +624,9 @@ if (pc.text) head.append(copyBtn(pc.text, pc.name || t(ROLE_NAMES[pc.role] || "Text"))); box.append(head); if (pc.role === "image") box.append(el("div", "ctx-piece-note", t("An image: magpie doesn't show it here"))); - else if (pc.role === "sealed") box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: (pc.size || 0).toLocaleString() }))); + else if (pc.role === "sealed") box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: (pc.size || 0).toLocaleString(intlLang()) }))); else { - if (pc.size) box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: pc.size.toLocaleString() }))); + if (pc.size) box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: pc.size.toLocaleString(intlLang()) }))); if (pc.text) box.append(longText(pc.text)); else if (!pc.size) box.append(el("div", "ctx-piece-note", t("Empty"))); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d0b54659b..1dd6f1015 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -17929,7 +17929,7 @@ function setLocale(pref) { locale = p === "system" ? sysLocale(sys) : p; // set only when it changes: settings come back on every refresh, and a // view that redraws for a new language shouldn't redraw for the same one - const lang = intlLang() || "en"; + const lang = LANG_TAGS[locale] || "en"; if (document.documentElement.lang !== lang) document.documentElement.lang = lang; translateStatic(); } @@ -17941,10 +17941,17 @@ function sysLocale(sys) { return sys.startsWith("zh") ? "zh" : sys.startsWith("ja") ? "ja" : sys.startsWith("de") ? "de" : "en"; } -// intlLang is the language's tag for Intl's dates and numbers, undefined -// for English (the system's own formats). +// intlLang is the tag every date, time and number the GUI shows is +// formatted in: the GUI's language, never the system's alone. English takes +// the system's own English (en-GB keeps its day-month order) and is plain +// "en" on a system in another language, so a Chinese Mac set to English +// reads "Oct 11", not "10月11日" (#1843). Never format with no locale, [] or +// undefined: those follow the system, not the language picked here. +const LANG_TAGS = { zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" }; function intlLang() { - return { zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" }[locale]; + if (LANG_TAGS[locale]) return LANG_TAGS[locale]; + const sys = navigator.language || ""; + return /^en(-|$)/i.test(sys) ? sys : "en"; } function t(s, vars) { diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 535adf572..2ebcb85c7 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -838,7 +838,7 @@ // only some (#741); one rtk couldn't give says why const g = rtk.gain; const gain = el("p", "lib-rtk-gain", g - ? t("{saved} tokens saved over {n} commands — {pct}% on average", { saved: tokens(g.saved), n: g.commands.toLocaleString(), pct: Math.round(g.pct) }) + ? t("{saved} tokens saved over {n} commands — {pct}% on average", { saved: tokens(g.saved), n: g.commands.toLocaleString(intlLang()), pct: Math.round(g.pct) }) : rtk.gainErr ? t("magpie couldn't read what RTK saved: {why}", { why: rtk.gainErr }) : t("Nothing saved yet: the agents' commands go through RTK once it's switched on and the agent is restarted.")); @@ -957,7 +957,7 @@ bar.append(saved, kept); const when = step === 7 ? t("week of {label}", { label: short(b.day) }) : short(b.day); bar.title = b.commands - ? t("{when} · {saved} tokens saved over {n} commands — {pct}%", { when, saved: tokens(b.saved), n: b.commands.toLocaleString(), pct: b.input ? Math.round(100 * b.saved / b.input) : 0 }) + ? t("{when} · {saved} tokens saved over {n} commands — {pct}%", { when, saved: tokens(b.saved), n: b.commands.toLocaleString(intlLang()), pct: b.input ? Math.round(100 * b.saved / b.input) : 0 }) : t("{when} · nothing", { when }); bars.append(bar); const end = i === k - 1 && (k - 1) % every >= every / 2; @@ -967,7 +967,7 @@ const key = (cls, text) => { const x = el("span", "lib-rtk-key"); x.append(el("i", cls), el("span", "", text)); return x; }; foot.append(key("out", t("saved")), key("in", t("still sent")), el("span", "grow"), el("span", "", sum.commands - ? t("{saved} tokens saved over {n} commands — {pct}%", { saved: tokens(sum.saved), n: sum.commands.toLocaleString(), pct: sum.input ? Math.round(100 * sum.saved / sum.input) : 0 }) + ? t("{saved} tokens saved over {n} commands — {pct}%", { saved: tokens(sum.saved), n: sum.commands.toLocaleString(intlLang()), pct: sum.input ? Math.round(100 * sum.saved / sum.input) : 0 }) : t("Nothing run through RTK in this time"))); chart.append(head, bars, labels, foot); return chart; @@ -3764,7 +3764,7 @@ const l = c.limited; if (!l) return t(c.error); const d = l.until ? new Date(l.until) : null; - const time = d && !isNaN(d) ? d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : ""; + const time = d && !isNaN(d) ? d.toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }) : ""; if (l.token) return time ? t("GitHub's rate limit for your GitHub token is used up until {time}", { time }) : t("GitHub's rate limit for your GitHub token is used up for now"); return time ? t("GitHub allows 60 requests an hour without a token, used up until {time}. Add a GitHub token in Settings → Network and sharing to raise it to 5,000.", { time }) @@ -3773,7 +3773,7 @@ // what a check found of a skill, for a tooltip: the last commit to it function checkLine(c) { - const when = c.date ? new Date(c.date).toLocaleDateString() : ""; + const when = c.date ? new Date(c.date).toLocaleDateString(intlLang()) : ""; return [c.message, [when, c.commit?.slice(0, 7)].filter(Boolean).join(" · ")].filter(Boolean).join("\n"); } @@ -4395,7 +4395,7 @@ if (!x.featured || x.installs) { const n = el("span", "mk-installs"); n.append(svg(GLYPH.down, 11, 1.5), el("span", "", compact(x.installs))); - n.title = t("{n} installs", { n: x.installs.toLocaleString() }); + n.title = t("{n} installs", { n: x.installs.toLocaleString(intlLang()) }); foot.append(n); } foot.append(el("span", "grow"), addButton(x, () => addSkill(x))); diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 6270ab471..c6e6c99db 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -305,7 +305,7 @@ default: return t("npm answered with an error: {error}", { error: c.error || "" }); } } - const checkedAt = () => checked ? new Date(checked.at).toLocaleTimeString(document.documentElement.lang || undefined, { hour: "2-digit", minute: "2-digit" }) : ""; + const checkedAt = () => checked ? new Date(checked.at).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }) : ""; // the built-ins with accounts this plugin could run in their place const movableOf = (pkg) => (mine?.movable || []).filter((c) => c.package === pkg); @@ -485,7 +485,7 @@ if (l.npm?.weekly) { const d = el("span", "pm-dl"); d.append(glyph(DOWN, 11, 1.5), el("span", "", t("{n}/week", { n: count(l.npm.weekly) }))); - d.title = t("{n} downloads on npm last week", { n: l.npm.weekly.toLocaleString() }); + d.title = t("{n} downloads on npm last week", { n: l.npm.weekly.toLocaleString(intlLang()) }); meta.append(d); } if (l.npm?.version) { @@ -517,7 +517,7 @@ function stars(n) { const d = el("span", "pm-dl"); d.append(glyph(STAR, 11, 1.4), el("span", "", count(n))); - d.title = t("{n} stars on GitHub", { n: (n || 0).toLocaleString() }); + d.title = t("{n} stars on GitHub", { n: (n || 0).toLocaleString(intlLang()) }); return d; } @@ -861,7 +861,7 @@ } else if (e.autoUpdated && e.autoUpdated.to === e.version) { // magpie updated it by itself lately: the row says so, quietly const c = el("span", "pm-chip soft", t("Auto-updated")); - c.title = t("magpie updated it from v{from} to v{to} on {date}", { from: e.autoUpdated.from, to: e.autoUpdated.to, date: new Date(e.autoUpdated.at).toLocaleDateString(document.documentElement.lang || undefined, { month: "short", day: "numeric" }) }); + c.title = t("magpie updated it from v{from} to v{to} on {date}", { from: e.autoUpdated.from, to: e.autoUpdated.to, date: new Date(e.autoUpdated.at).toLocaleDateString(intlLang(), { month: "short", day: "numeric" }) }); nm.append(c); } else if ((ck?.status === "current" || ck?.status === "update") && e.version) { const c = el("span", "pm-chip soft", t("Up to date")); @@ -1096,7 +1096,7 @@ d.title = m.error; return d; } - const lang = document.documentElement.lang || undefined; + const lang = intlLang(); let s = t("Gateway middleware: {hooks}", { hooks: m.hooks.join(t(", ")) }); if (m.calls) s += " · " + t("{n} calls, {us} µs each", { n: m.calls.toLocaleString(lang), us: m.avgMicros < 10 ? m.avgMicros.toFixed(1) : Math.round(m.avgMicros).toLocaleString(lang) }); d.append(el("span", "", s)); @@ -1189,7 +1189,7 @@ try { const p = await api("plugins/page?name=" + encodeURIComponent(l.package)); const at = l.github && !entryOf(l.package) ? l.github.pushed : p.updated; - upd.textContent = at && !at.startsWith("0001") ? new Date(at).toLocaleDateString(document.documentElement.lang || undefined, { year: "numeric", month: "short", day: "numeric" }) : "—"; + upd.textContent = at && !at.startsWith("0001") ? new Date(at).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }) : "—"; readme.replaceChildren(markdown(p.readme || t("No README"))); } catch (e) { upd.textContent = "—"; diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 8c6acbc41..941ff79fe 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -240,10 +240,15 @@ } const took = (ms = 0) => ms < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) }); // (the formats made once: made for each call, they were much of what the - // accounts' countdowns cost) - const HM = new Intl.DateTimeFormat([], { hour: "2-digit", minute: "2-digit" }), WD = new Intl.DateTimeFormat([], { weekday: "short" }); + // accounts' countdowns cost), made again when the GUI's language changes + let fmtLang = null, HM, WD; function clock(s) { const d = new Date(s), n = new Date(); + if (fmtLang !== intlLang()) { + fmtLang = intlLang(); + HM = new Intl.DateTimeFormat(fmtLang, { hour: "2-digit", minute: "2-digit" }); + WD = new Intl.DateTimeFormat(fmtLang, { weekday: "short" }); + } const hm = HM.format(d); return d.toDateString() === n.toDateString() ? hm : WD.format(d) + " " + hm; } @@ -685,7 +690,7 @@ function condText(c) { let m; if ((m = /^intent "(.*)"$/.exec(c))) return t("asks for “{intent}”", { intent: m[1].replace(/\\"/g, '"').replace(/\\\\/g, "\\") }); - if ((m = /^tokens ≥ (\d+)$/.exec(c))) return t("≥ {n} tokens", { n: Number(m[1]).toLocaleString() }); + if ((m = /^tokens ≥ (\d+)$/.exec(c))) return t("≥ {n} tokens", { n: Number(m[1]).toLocaleString(intlLang()) }); if (c === "images") return t("has an image"); if (c === "reasoning") return t("reasoning on"); if (c === "compacting") return t("compacting"); @@ -1922,7 +1927,7 @@ const dayName = (d) => { const x = new Date(d + "T12:00:00"), n = new Date(), y = new Date(n.getTime() - 864e5); return x.toDateString() === n.toDateString() ? t("today") : x.toDateString() === y.toDateString() ? t("yesterday") - : x.toLocaleDateString([], { month: "short", day: "numeric", weekday: "short" }); + : x.toLocaleDateString(intlLang(), { month: "short", day: "numeric", weekday: "short" }); }; async function loadDays(d) { try { @@ -2227,7 +2232,7 @@ } function reqRow(r, said, how, tr, ag, meta, metrics, title) { const b = el("button", "rt-req " + how); - const when = el("span", "at", new Date(r.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })); + const when = el("span", "at", new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit" })); const asked = el("span", "asked"); const sw = el("i", "ag"); sw.style.setProperty("--agent", hueOf(r.agent)); @@ -2711,8 +2716,8 @@ } function replayBar(p, fast) { const d = new Date(p.real); - rClock.textContent = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) + "." + Math.floor(d.getMilliseconds() / 100); - const day = d.toDateString() === new Date().toDateString() ? t("today") : d.toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" }); + rClock.textContent = d.toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) + "." + Math.floor(d.getMilliseconds() / 100); + const day = d.toDateString() === new Date().toDateString() ? t("today") : d.toLocaleDateString(intlLang(), { weekday: "short", month: "short", day: "numeric" }); setText(rDay, day); // a quiet stretch cut short: the clock runs fast through it, whatever // the speed picked @@ -2739,7 +2744,7 @@ const [said] = outcome(r); row.append(el("span", "rp-n", t("request {i} of {n}", { i: g.n, n: p.plan.length })), sw, el("b", "", agentName(r.agent)), el("code", "mdl", r.model), ...(r.kind ? [kindTag(r)] : []), el("span", "rp-to", "→ " + said), - el("span", "rp-at", t("sent {time}", { time: new Date(r.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) }))); + el("span", "rp-at", t("sent {time}", { time: new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) }))); row.onclick = () => { cur = r; renderLog(); }; return row; }) : [el("span", "rp-wait", t("starting…"))])); @@ -3072,7 +3077,7 @@ // what a rule matches, in words function ruleText(r) { const bits = []; - if (r.tokens) bits.push(t("≥ {n} tokens", { n: r.tokens.toLocaleString() })); + if (r.tokens) bits.push(t("≥ {n} tokens", { n: r.tokens.toLocaleString(intlLang()) })); if (r.images) bits.push(t("has an image")); if (r.effort) bits.push(r.effort === "on" ? t("reasoning on") : t("reasoning ≥ {level}", { level: r.effort })); if (r.agents?.length) bits.push(r.agents.map((id) => (state.clients || state.agents || []).find((a) => a.id === id)?.name || id).join(" / ")); @@ -4170,10 +4175,10 @@ ctxIn.setAttribute("aria-invalid", String(!!ctxErr)); const big = ns.length ? Math.max(...ns) : 0, small = ns.length ? Math.min(...ns) : 0; ctxHint.textContent = ctxErr || (mode === "custom" - ? t("Agents are told the group takes {n} tokens; a longer conversation still goes on to a member with room for it.", { n: (d.context || 0).toLocaleString() }) + ? t("Agents are told the group takes {n} tokens; a longer conversation still goes on to a member with room for it.", { n: (d.context || 0).toLocaleString(intlLang()) }) : mode === "smallest" - ? (small ? t("Agents are told {n} tokens, its smallest model's, so they compact before any member would turn the conversation away.", { n: small.toLocaleString() }) : t("Agents are told its smallest model's window, so they compact before any member would turn the conversation away.")) - : (big ? t("Agents are told {n} tokens, its largest model's; a conversation too long for one member goes on to one with room for it.", { n: big.toLocaleString() }) : t("Agents are told its largest model's window; a conversation too long for one member goes on to one with room for it."))); + ? (small ? t("Agents are told {n} tokens, its smallest model's, so they compact before any member would turn the conversation away.", { n: small.toLocaleString(intlLang()) }) : t("Agents are told its smallest model's window, so they compact before any member would turn the conversation away.")) + : (big ? t("Agents are told {n} tokens, its largest model's; a conversation too long for one member goes on to one with room for it.", { n: big.toLocaleString(intlLang()) }) : t("Agents are told its largest model's window; a conversation too long for one member goes on to one with room for it."))); }; const CTX_OPTS = [["largest", "Largest model's"], ["smallest", "Smallest model's"], ["custom", "Custom"]]; ctxW.append(segs(CTX_OPTS.map(([id, n]) => [id, t(n)]), ctxMode(), (v) => { @@ -4350,9 +4355,9 @@ const m = infoOf(r.use), bits = []; if (r.pause) bits.push(t("left out of the group then: not tried, not a fallback")); if (!r.pause && r.images && m && m.ready && !m.images) bits.push(t("it doesn't take images")); - if (!r.pause && r.tokens && m?.context && m.context < r.tokens) bits.push(t("it takes {n} tokens", { n: m.context.toLocaleString() })); + if (!r.pause && r.tokens && m?.context && m.context < r.tokens) bits.push(t("it takes {n} tokens", { n: m.context.toLocaleString(intlLang()) })); // a summary longer than it takes goes by the next rule, or the group - if (!r.pause && r.compact && m?.context && d.members.some((id) => (infoOf(id)?.context || 0) > m.context)) bits.push(t("longer conversations skip it: it takes {n} tokens", { n: m.context.toLocaleString() })); + if (!r.pause && r.compact && m?.context && d.members.some((id) => (infoOf(id)?.context || 0) > m.context)) bits.push(t("longer conversations skip it: it takes {n} tokens", { n: m.context.toLocaleString(intlLang()) })); const from = clockOf(r.time?.from), to = clockOf(r.time?.to); if (from && to && to < from) bits.push(t("runs past midnight, into the next day")); hint.textContent = bits.join(" · "); @@ -4941,7 +4946,7 @@ const asked = el("span", "pr-a"); asked.append(icon(ag?.icon || "generic"), el("span", "pr-who", agentName(r.agent)), el("code", "m", r.model)); if (r.kind) asked.append(kindTag(r)); - const when = el("span", "at", new Date(r.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })); + const when = el("span", "at", new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })); // where it went: the provider, the account or key, and the model that // answered — marked when the reply names another than the one sent const to = el("span", "pr-to"); diff --git a/internal/gui/intl_lang_test.go b/internal/gui/intl_lang_test.go new file mode 100644 index 000000000..39ed42f35 --- /dev/null +++ b/internal/gui/intl_lang_test.go @@ -0,0 +1,34 @@ +package gui + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// TestDatesFollowGUILanguage: every date, time and number the GUI formats +// is given intlLang(), the GUI's language. With no locale, [] or undefined +// it follows the system instead, and a Chinese Mac set to English read +// Routing's days as "10月11日 周日" (#1843). The browser test +// dates-gui-lang.test.cjs checks what Routing shows; this keeps every other +// call from slipping back, since CI doesn't run the browser tests. +func TestDatesFollowGUILanguage(t *testing.T) { + bare := regexp.MustCompile(`\.toLocale(Date|Time)?String\(\s*(\)|\[\]|undefined\b|document\.documentElement\.lang)|new Intl\.\w+\(\s*(\)|\[\]|undefined\b)|intlLang\(\) \|\|`) + files, err := filepath.Glob(filepath.Join("assets", "*.js")) + if err != nil || len(files) == 0 { + t.Fatalf("no assets: %v", err) + } + for _, f := range files { + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(b), "\n") { + if bare.MatchString(line) { + t.Errorf("%s:%d formats in the system's locale, not the GUI's: give it intlLang()\n\t%s", f, i+1, strings.TrimSpace(line)) + } + } + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 25b107da9..11dabc3d2 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -204,6 +204,15 @@ asked for and names the pill, with the bar held where it was; three days need no such pill; a window narrowed then widened fits again. Chromium and WebKit, in English, Chinese, Japanese and German. +`dates-gui-lang.test.cjs` checks that dates and times read in the GUI's +language, not the system's (#1843): English on a zh-CN browser, English on +en-GB (the system's own English kept), and Chinese, Traditional Chinese, +Japanese and German on en-US. Routing's day pills, those in the bar and those +under its last pill's menu, and a request's time must match `intlLang()`'s +tag and not the browser's. Chromium and WebKit, at 1100px and 390px. +`TestDatesFollowGUILanguage` (Go, run in CI) fails on any formatting call in +the assets given no locale, `[]` or `undefined`. + `agent-disconnect-preview.test.cjs` checks the disconnect confirmation's file previews fill the body instead of the editor's label column. omp and Codex previews, restored values, expanding hidden lines, scrolling, Cancel, diff --git a/internal/gui/tests/dates-gui-lang.test.cjs b/internal/gui/tests/dates-gui-lang.test.cjs new file mode 100644 index 000000000..047164bb4 --- /dev/null +++ b/internal/gui/tests/dates-gui-lang.test.cjs @@ -0,0 +1,108 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Dates and times read in the GUI's language, not the system's (#1843): a +// Mac in Chinese with magpie set to English showed Routing's day pills as +// "10月11日 周日", since they were formatted with no locale and so followed +// the system. Every language is tried on a system in another one (English +// on zh-CN, the rest on en-US), and English on an en-GB system keeps the +// system's own English. Routing's day pills and a request's time are read. +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 now = new Date(); +const ymd = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +// days before yesterday, so none reads "today" or "yesterday" +const days = Array.from({ length: 3 }, (_, i) => ({ day: ymd(new Date(now.getTime() - (i + 3) * 864e5)), requests: 10 + i })); +// 14:05:09 local, so a 12-hour clock shows PM and a 24-hour one 14 +const reqAt = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 5, 9); +const who = { id: "fixture-key", provider: "fixture", name: "Fixture", who: "key-1", kind: "key", model: "model-a", routing: "", used: 0 }; +const route = { + id: 7, seq: 7, time: reqAt.toISOString(), agent: "fixture", model: "model-a", provider: "fixture", + order: [who], tries: [{ id: who.id, model: "model-a", start: reqAt.toISOString(), done: true, status: 200, ms: 900 }], + done: true, status: 200, ms: 900, tokens: 1200, +}; + +function serve(lang) { + 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({ agents: [{ id: "fixture", name: "Fixture", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((res) => setTimeout(res, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 7, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [route] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days, routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// [GUI language, the system's locale, the tag its dates must read in] +const cases = [ + ["en", "zh-CN", "en"], + ["en", "en-GB", "en-GB"], + ["zh", "en-US", "zh-CN"], + ["zh-TW", "en-US", "zh-TW"], + ["ja", "en-US", "ja-JP"], + ["de", "en-US", "de-DE"], +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, sys, tag] of cases) { + test(`${engine}: GUI in ${lang} on a ${sys} system reads dates in ${tag}`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const width of [1100, 390]) { + const context = await browser.newContext({ viewport: { width, height: 760 }, locale: sys, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-days .rt-day").nth(1).waitFor({ state: "attached" }); + await page.locator(".rt-req .at").first().waitFor(); + await page.waitForTimeout(200); + assert.equal(await page.evaluate(() => navigator.language), sys, "the browser stands in for the system's locale"); + + const [want, other] = await page.evaluate(([ds, tag, sys]) => [tag, sys].map((loc) => ds.map((d) => + new Date(d + "T12:00:00").toLocaleDateString(loc, { month: "short", day: "numeric", weekday: "short" }))), [days.map((d) => d.day), tag, sys]); + // the days as shown: the pills in the bar, then those past its width + // in the menu under its last pill (#961) + const pills = await page.locator(".rt-days .rt-day:not(.rt-day-more)").evaluateAll((xs) => xs.slice(1).filter((x) => !x.hidden && x.getBoundingClientRect().width > 0).map((x) => x.querySelector("span").textContent)); + const shown = [...pills]; + if (pills.length < days.length) { + // (dispatched: at 390 the bar sits below the fold, and the page + // keeps its scroll on a click) + await page.locator(".rt-days .rt-day-more").dispatchEvent("click"); + const items = page.locator(".proto-menu .pm-item"); + await items.first().waitFor(); + const texts = await items.allInnerTexts(); + for (let i = pills.length; i < days.length; i++) { + const hit = texts.find((s) => s.includes(want[i])); + shown.push(hit ? want[i] : texts.join(" | ")); + } + await page.keyboard.press("Escape"); + } + assert.deepEqual(shown, want, `${width}px: the days read in ${tag}`); + if (tag !== sys) assert.notDeepEqual(shown, other, `${width}px: the days read in the system's ${sys}`); + if (lang === "en") assert.doesNotMatch(shown.join(" "), /[ -鿿]/, `${width}px: English days hold CJK: ${shown}`); + + const at = await page.locator(".rt-req .at").first().textContent(); + const wantAt = await page.evaluate(([at, tag]) => new Date(at).toLocaleTimeString(tag, { hour: "2-digit", minute: "2-digit", second: "2-digit" }), [route.time, tag]); + assert.equal(at, wantAt, `${width}px: the request's time reads in ${tag}`); + assert.deepEqual(errors, []); + await context.close(); + } + }); + } +} diff --git a/internal/gui/tests/github-token.test.cjs b/internal/gui/tests/github-token.test.cjs index 777bdac7e..97705f27d 100644 --- a/internal/gui/tests/github-token.test.cjs +++ b/internal/gui/tests/github-token.test.cjs @@ -141,7 +141,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await check.waitFor(); await check.click(); await page.waitForFunction(() => document.querySelector("#view-library .lib-unchecked")); - const time = await page.evaluate((u) => new Date(u).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), UNTIL); + const time = await page.evaluate((u) => new Date(u).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }), UNTIL); const want = (st.from ? w.withToken : w.limited).replace("{time}", time); assert((await page.locator("#status").textContent()).includes(want), `status: ${await page.locator("#status").textContent()}`); assert.equal(await page.locator("#view-library .lib-unchecked").getAttribute("title"), want); diff --git a/internal/gui/tests/reset-each-title.test.cjs b/internal/gui/tests/reset-each-title.test.cjs index 00508bb4a..4562f96ea 100644 --- a/internal/gui/tests/reset-each-title.test.cjs +++ b/internal/gui/tests/reset-each-title.test.cjs @@ -99,7 +99,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", }; // the titles the three cards' resets should carry, dates as the page says them const want = async (page) => { - const [wa, wb, wc] = await page.evaluate((ds) => ds.map((d) => new Date(d).toLocaleString()), [a, b, c]); + const [wa, wb, wc] = await page.evaluate((ds) => ds.map((d) => new Date(d).toLocaleString(intlLang())), [a, b, c]); return { codex: [w.nth(1, wa), w.nth(2, wc), w.never(3)], team: [w.five(wa), w.week(wb), w.five(wc)],