usage: a currency "By provider" shows each provider's costs in what it sells in
onkashiko on X: DeepSeek, Kimi (China), Zhipu and other domestic vendors
price in yuan, the rest in dollars, and one currency for every cost made
the Usage page read wrong for half of them.
Settings > Usage > Currency gains a third choice, By provider. With it,
a figure of one provider's calls (a model's, an account's, a key's row,
a request, a routing try, a quota card's whole) shows in the currency
that provider sells in, and every sum across providers (the total,
agents, sessions, charts, the tray, Bark's daily, the day page) in the
currency a "Totals in" row picks, a row shown only while By provider is
chosen. GUI, TUI and CLI agree. Costs stay stored in dollars; only the
display converts, at the live rate (internal/fx).
Which providers sell in yuan (provider.PricesInYuan): a .cn host; a
preset at its own site that is a yuan preset (deepseek, zhipu,
volcengine, tencent-cloud, bailian, siliconflow…), ends in -cn, or is in
its China region; a plugin id ending in -cn; a provider of one's own
with a yuan models.dev catalog served at that catalog's site. A relay
made from DeepSeek's preset, Z.ai, Kimi's and MiniMax's international
endpoints stay in dollars: they share a catalog with their Chinese
twins, so the catalog alone can't tell.
Known limit: models.dev has only dollar prices (converted from the
vendors' yuan at ~6.7-7.0), so a yuan figure is that dollar price at
today's rate and can differ a few percent from the vendor's own list.
A second ask from onkashiko: set the currency of the menu bar and of
the totals apart, sums converted by themselves.
So Settings > Usage also gains an Advanced fold (closed by default, open while
set) with one row, Menu bar currency: Same as totals (the default), $ or
¥ (settings.TrayCurrency, TrayCostIn). It sets the menu bar's totals
cards and the tray tooltip's cost; the Usage page, the panel, the TUI,
the CLI and Bark's daily message stay in the totals' currency
(totalsCurrency). Like the other menu bar settings it stays on this
computer (KeepOwn). Every sum is still made in dollars and converted
once, at the live rate, so a mixed-currency total is never added up
from yuan and dollars.
Settings' currency rows (Currency, Totals in, Menu bar currency and the
rate in the tooltip) moved out of app.js into currencyprefs.js, imported
when Settings draws its usage prefs, and costInYuan is packed: the core
is 3 bytes under coreScriptBudget, with no raise.
Run:
- go test -count=1 at this tree on mote: internal/settings,
settingsapi, tui, cli, catalog, provider, fx and gui all ok
(TestCoreScriptBudget included). The full go test ./... and the whole
GUI suite are queued behind other sessions' suites on suite.lock
(mote and mica, load 35 and 60) and had not started at push.
- GUI files at this tree (mica): currency-provider, currency, i18n-keys,
i18n-en-no-cjk, tray-cost, tray-totals, every settings-*, old-webkit:
362 pass, 28 red. Every red is red the same at origin/main ac0b5c287
on mote, and filed: settings-search (#6133, #6353), settings-hints
(#6107, #6353), settings-lines-wrap de 440px (#6353), old-webkit
appearance.js (#6467) and :has() (#5919). The one red of this change,
settings-groups' list of Usage's parts (now with the Advanced fold),
is fixed here: 14 of 14.
- currency-provider.test.cjs (new): en, zh, zh-TW, ja, de at 900 and
420px, both engines; By provider, Totals in ¥, then Advanced: $ for
the menu bar with totals in ¥, totals stay ¥21.60, the fold opens
itself after a reload. Plus currency.test.cjs (3 choices now),
i18n-keys, i18n-en-no-cjk, tray-cost: green in both engines.
- TestTrayCostIn (values, refused eur/provider, KeepOwn),
TestFXByProvider (trayCurrency vs totalsCurrency), TestCoreScriptBudget.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., GOOS=linux go build -tags nogui,
GOOS=windows go build on mote at this tree: ok.
- Broken by hand, each red: costInYuan ignoring the provider (GUI
test: deepseek showed $1.00 for ¥7.20), PricesInYuan without the
preset's site check (a relay made from DeepSeek's preset read as
yuan), CostIn without its By provider branch (settings test),
TrayCostIn ignoring TrayCurrency (TestTrayCostIn, TestFXByProvider),
the fold not opening while set (webkit), the row saving into
totalCurrency (chromium).
- Real app in a sandbox HOME on mote (dev build, magpie web and magpie
usage) with DeepSeek, OpenAI and Z.ai presets and one call each: the
window and the CLI both show deepseek-v4-pro ≈¥15.44, gpt-4.1 ≈$1.00,
glm-4.6 ≈$0.290 and the total ≈¥24.07 at 6.685; /api/settings' fx
carries yuan ["deepseek"].
Not tried: Windows and Linux windows and trays, the real menu bar with
Menu bar currency changed (drawn natively; covered through trayCurrency
in Go), a real Kimi CN or Zhipu account.
This commit is contained in:
@@ -672,7 +672,7 @@ covers it in both engines, every language and a narrow window.
|
||||
- The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`.
|
||||
- The Usage page's Allowances head ends in a Settings › link (`#usageToSet`, wired in `plugins/usage/page.js`) to Settings › Allowances, where how the allowances show and their alerts are set (the scattered settings audit after netube99 on X); it lights the Allowance display row (`#quotaLeftRow`).
|
||||
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks, with `&all=1` (`loadQuotas("all")`, `AskEveryClaudeUsage`), so saved Claude accounts are read again too, as their cards' refresh reads them (#5380); an opening's asked read on its way doesn't take its place. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
|
||||
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency, `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
|
||||
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency (with *By provider*, `settings.CurrencyByProvider`, in the currency picked for totals, `TotalCostIn`: a sum of every provider has no one currency of its own; Settings › Usage › Advanced › *Menu bar currency*, `settings.TrayCurrency`, per computer through `KeepOwn`, sets the menu bar's and its tooltip's apart, `TrayCostIn`, while Bark's daily message stays in the totals'; the currency rows are drawn by `currencyprefs.js`, imported when Settings draws its usage prefs), `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
|
||||
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon, unless a card is in the menu bar: Windows' notification area shows no text beside an icon, so the icon itself is the first card's figure (Benjaminliang_1 on X; `trayIconFigure`, `trayNumberIcon` in [`traynumber.go`](../../internal/gui/traynumber.go)). It is the first row of the first card whose first row is a percentage, used or left as Allowance display has it, through *Menu bar windows*' pick, its digits alone, drawn in Segoe UI Semibold (Go's bold where the font can't be read) at `SM_CXSMICON`, white on a dark taskbar and near black on a light one, as tall as fits with a pixel above and below, centred by its ink, and three digits narrowed into the square. A balance or magpie's totals are skipped for the next card; with none the icon is the bird. It is drawn again when the figure, the icon size or the taskbar's theme changes (`SystemThemeChanged` wakes the loop); the tooltip still says every card. Settings › *Tray icon number* (`settings.TrayNoNumber`, Windows' alone, on by default) keeps the bird when off. One icon is set for the current theme, not a light and a dark one: Wails' Windows tray shares one handle between them. Linux keeps its label and tooltip; the Mac its cells. See `TestTrayIconFigure`, `TestTrayNumberIcon` and `tray-windows.test.cjs`. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`. Every tooltip, the idle one, magpie's totals' and each card's (its use or what is left, the pace, when it resets, "as of …"), is in magpie's language, as the tray menu is: `watchTrayUsage` passes `trayLang(settings.Lang, systemLang)` to `trayCardsView`, `trayUsageCards` and `trayIdleTip`, whose words are in `trayWords` beside the menu's, and a change of language in Settings refreshes it at once (`onTrayUsage`). A window's name and an error are the card's own (yi_time on Discord: English on a Windows magpie set to Chinese; `TestTrayTooltipFollowsMagpiesLanguage`).
|
||||
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text but the first card's figure as its icon) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
|
||||
- Settings › *Menu bar windows* (`settings.TrayWindows`, StrikingRaw on X) picks which of a subscription's windows its menu bar card shows, keyed by provider id (every account of it, the in-use `|*` card too) and by window kind, not position: `trayWindowKind` names a window by its span ("5h", "1d", "7d", "month", "15m"), by `name:` its name when the span isn't known. Unset shows every window, as before; a pick none of whose kinds the card still has shows every window again (`trayShownKinds`), never an empty card. Only the bar's rows, the Linux label and Windows' icon figure are filtered; the tooltip still says every window. One row draws in the menu bar's own font (13pt regular), two stacked rows in 10pt regular, both with digits of one width (`mpRowFont`, `TestTrayRowFont`; qingnianxiaozhe on X found the old 9.5pt semibold and 11pt medium heavier than Surge's and iStat Menus' figures beside them). The GUI learns the kinds from `trayKind` on `/api/usage/quotas` (`withTrayKinds`; model and aside windows get none). The row lists a pill per ticked subscription with two or more kinds, opening the app's menu (All windows, then each kind), shown on Windows too, where the first card's pick decides the tray icon's figure; its code is in `traywindows.js`, imported when Settings draws ticked cards. Per computer through `KeepOwn`. See `TestTrayWindowsPicked`, `TestTrayWindowsKept` and `tray-windows.test.cjs`.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"deepseek": {
|
||||
"id": "deepseek",
|
||||
"name": "DeepSeek",
|
||||
"api": "https://api.deepseek.com",
|
||||
"models": {}
|
||||
},
|
||||
"stepfun": {
|
||||
"id": "stepfun",
|
||||
"name": "StepFun (China)",
|
||||
"api": "https://api.stepfun.com/v1",
|
||||
"models": {}
|
||||
},
|
||||
"zhipuai": {
|
||||
"id": "zhipuai",
|
||||
"name": "Zhipu AI",
|
||||
"api": "https://open.bigmodel.cn/api/paas/v4",
|
||||
"models": {}
|
||||
},
|
||||
"moonshotai": {
|
||||
"id": "moonshotai",
|
||||
"name": "Moonshot AI",
|
||||
"api": "https://api.moonshot.ai/v1",
|
||||
"models": {}
|
||||
},
|
||||
"moonshotai-cn": {
|
||||
"id": "moonshotai-cn",
|
||||
"name": "Moonshot AI (China)",
|
||||
"api": "https://api.moonshot.cn/v1",
|
||||
"models": {}
|
||||
},
|
||||
"alibaba-cn": {
|
||||
"id": "alibaba-cn",
|
||||
"name": "Alibaba (China)",
|
||||
"api": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"models": {}
|
||||
},
|
||||
"siliconflow-cn": {
|
||||
"id": "siliconflow-cn",
|
||||
"name": "SiliconFlow (China)",
|
||||
"api": "https://api.siliconflow.cn/v1",
|
||||
"models": {}
|
||||
},
|
||||
"zai": {
|
||||
"id": "zai",
|
||||
"name": "Z.AI",
|
||||
"api": "https://api.z.ai/api/paas/v4",
|
||||
"models": {}
|
||||
},
|
||||
"minimax": {
|
||||
"id": "minimax",
|
||||
"name": "MiniMax (minimax.io)",
|
||||
"api": "https://api.minimax.io/anthropic/v1",
|
||||
"models": {}
|
||||
},
|
||||
"openai": {
|
||||
"id": "openai",
|
||||
"name": "OpenAI",
|
||||
"api": "",
|
||||
"models": {}
|
||||
},
|
||||
"xiaomi": {
|
||||
"id": "xiaomi",
|
||||
"name": "Xiaomi",
|
||||
"api": "https://api.xiaomimimo.com/v1",
|
||||
"models": {}
|
||||
},
|
||||
"openrouter": {
|
||||
"id": "openrouter",
|
||||
"name": "OpenRouter",
|
||||
"api": "https://openrouter.ai/api/v1",
|
||||
"models": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// yuanSellers are the models.dev providers that sell in China's yuan
|
||||
// whose id and name don't say so: DeepSeek's own API (its balance comes
|
||||
// back in CNY), Volcengine's Ark, Tencent's, Zhipu's bigmodel.cn under the
|
||||
// plain zhipuai, Qiniu's, Ant's Bailing. Xiaomi's plain "xiaomi" is left
|
||||
// out: its pay-as-you-go is sold abroad too.
|
||||
var yuanSellers = map[string]bool{
|
||||
"deepseek": true, "volcengine": true, "volcengine-coding-plan": true,
|
||||
"tencent-tokenhub": true, "tencent-token-plan": true, "tencent-coding-plan": true,
|
||||
"zhipuai": true, "zhipuai-coding-plan": true, "qiniu-ai": true, "bailing": true,
|
||||
}
|
||||
|
||||
// PricedInYuan is whether a models.dev provider sells in China's yuan
|
||||
// rather than in dollars: one of yuanSellers, or one whose id ends in
|
||||
// -cn, whose name says "(China)" or whose API is on a .cn host. Its
|
||||
// models.dev prices are still in dollars, converted from the yuan; only
|
||||
// how a cost of it is shown (Settings' currency "provider") asks this.
|
||||
func PricedInYuan(id string) bool {
|
||||
id = strings.ToLower(strings.TrimSpace(id))
|
||||
if id == "" {
|
||||
return false
|
||||
}
|
||||
if yuanSellers[id] || strings.HasSuffix(id, "-cn") || strings.Contains(id, "-cn-") {
|
||||
return true
|
||||
}
|
||||
p, ok := load()[id]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return strings.Contains(p.Name, "(China)") || YuanHost(p.API)
|
||||
}
|
||||
|
||||
// APIHost is the host models.dev says a provider serves its models at
|
||||
// (api.deepseek.com), lower case; "" when it isn't in the catalog.
|
||||
func APIHost(id string) string {
|
||||
p, ok := load()[strings.ToLower(strings.TrimSpace(id))]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(p.API))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.ToLower(u.Hostname())
|
||||
}
|
||||
|
||||
// YuanHost is whether a base URL is on a .cn host, a mainland Chinese
|
||||
// vendor's, which sells in yuan.
|
||||
func YuanHost(base string) bool {
|
||||
u, err := url.Parse(strings.TrimSpace(base))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.HasSuffix(strings.ToLower(u.Hostname()), ".cn")
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A models.dev provider's currency, which its prices (always in dollars,
|
||||
// converted from the yuan for China's sellers) don't say.
|
||||
func TestPricedInYuan(t *testing.T) {
|
||||
// models.dev's own names and API URLs for these ids, as of 2026-11-13
|
||||
freshCache(t)
|
||||
b, err := os.ReadFile(filepath.Join("testdata", "models.dev-yuan-2026-11-13.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(CachePath()), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(CachePath(), b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
Reset()
|
||||
for id, want := range map[string]bool{
|
||||
"deepseek": true, "zhipuai": true, "moonshotai-cn": true, "kimi-code-plan-cn": true,
|
||||
"stepfun": true, "minimax-cn": true, "alibaba-cn": true, "siliconflow-cn": true, "volcengine": true,
|
||||
"xiaomi-token-plan-cn": true, " DeepSeek ": true,
|
||||
"openai": false, "anthropic": false, "moonshotai": false, "zai": false, "minimax": false,
|
||||
"openrouter": false, "xiaomi": false, "": false, "no-such-provider": false,
|
||||
} {
|
||||
if got := PricedInYuan(id); got != want {
|
||||
t.Errorf("PricedInYuan(%q) = %v, want %v", id, got, want)
|
||||
}
|
||||
}
|
||||
if h := APIHost("deepseek"); h != "api.deepseek.com" {
|
||||
t.Errorf("APIHost(deepseek) = %q", h)
|
||||
}
|
||||
if h := APIHost("no-such-provider"); h != "" {
|
||||
t.Errorf("APIHost(no-such-provider) = %q, want none", h)
|
||||
}
|
||||
for base, want := range map[string]bool{"https://open.bigmodel.cn/api": true, "https://api.z.ai/api": false, "http://x.cn:8080/v1": true, "https://cn.example.com": false, "": false} {
|
||||
if got := YuanHost(base); got != want {
|
||||
t.Errorf("YuanHost(%q) = %v, want %v", base, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-16
@@ -18,21 +18,26 @@ import (
|
||||
stats "github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// costCurrency and costRate are cost's currency and, for cny, the
|
||||
// CNY-per-USD rate to show it at — loadCostCurrency sets them once at a
|
||||
// command's start, not again for every row it prints.
|
||||
// costSettings, costRate and costYuan are Settings' currency choice, the
|
||||
// CNY-per-USD rate to show a cost in yuan at, and, for the choice
|
||||
// "provider", the providers that sell in yuan — loadCostCurrency sets
|
||||
// them once at a command's start, not again for every row it prints.
|
||||
var (
|
||||
costCurrency = "usd"
|
||||
costSettings settings.Settings
|
||||
costRate float64
|
||||
costYuan map[string]bool
|
||||
)
|
||||
|
||||
// loadCostCurrency reads Settings' currency choice and, only for cny, the
|
||||
// exchange rate (internal/fx, its own 12h cache — this asks the network
|
||||
// only when that's stale).
|
||||
// loadCostCurrency reads Settings' currency choice and, only when a cost
|
||||
// may be in yuan, the exchange rate (internal/fx, its own 12h cache —
|
||||
// this asks the network only when that's stale).
|
||||
func loadCostCurrency() {
|
||||
costCurrency = settings.Load().Currency
|
||||
costRate = 0
|
||||
if costCurrency == "cny" {
|
||||
costSettings = settings.Load()
|
||||
costRate, costYuan = 0, nil
|
||||
if costSettings.Currency == settings.CurrencyByProvider {
|
||||
costYuan = pr.YuanPricedSet()
|
||||
}
|
||||
if costSettings.Currency != "usd" && costSettings.Currency != "" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
costRate = fx.Get(ctx).CNYPerUSD
|
||||
cancel()
|
||||
@@ -220,7 +225,7 @@ func printUsage(out io.Writer, s stats.Summary, title string, names map[string]s
|
||||
if s.Tokens() > 0 {
|
||||
share = fmt.Sprintf("%3.0f%%", 100*float64(g.Tokens())/float64(s.Tokens()))
|
||||
}
|
||||
fmt.Fprintln(out, " "+pad(name(g), w), muted.Render(share), pad(fmtTokens(g.Tokens()), 7), faint.Render(pad(plural(g.Calls, "call"), 10)), cost(g.Totals), faint.Render(speed(g.Totals)), muted.Render(stats.FormatCredits(g.Totals)))
|
||||
fmt.Fprintln(out, " "+pad(name(g), w), muted.Render(share), pad(fmtTokens(g.Tokens()), 7), faint.Render(pad(plural(g.Calls, "call"), 10)), costOf(g.Totals, g.Provider), faint.Render(speed(g.Totals)), muted.Render(stats.FormatCredits(g.Totals)))
|
||||
}
|
||||
}
|
||||
provider := func(id string) string {
|
||||
@@ -349,14 +354,23 @@ func credits(t stats.Totals) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// cost renders list-price cost, saying when some calls could not be
|
||||
// priced, in costCurrency at costRate (set once per command by
|
||||
// loadCostCurrency).
|
||||
func cost(t stats.Totals) string {
|
||||
// cost renders a list-price cost of several providers' calls, saying
|
||||
// when some could not be priced, in the currency Settings shows a total in
|
||||
// at costRate (set once per command by loadCostCurrency).
|
||||
func cost(t stats.Totals) string { return costOf(t, "") }
|
||||
|
||||
// costOf is cost of one provider's calls, in the currency Settings shows
|
||||
// that provider's in (its own, with the choice "provider"); "" is a sum
|
||||
// of several.
|
||||
func costOf(t stats.Totals, providerID string) string {
|
||||
if t.Cost == 0 && t.Unpriced > 0 {
|
||||
return faint.Render("no price")
|
||||
}
|
||||
s := stats.FormatCost(t.Cost, costCurrency, costRate)
|
||||
cncy := costSettings.TotalCostIn()
|
||||
if providerID != "" && providerID != stats.UnknownProvider {
|
||||
cncy = costSettings.CostIn(costYuan[providerID])
|
||||
}
|
||||
s := stats.FormatCost(t.Cost, cncy, costRate)
|
||||
if t.Unpriced > 0 {
|
||||
s += muted.Render("+")
|
||||
}
|
||||
|
||||
+19
-5
@@ -388,6 +388,19 @@ type fxJSON struct {
|
||||
Rate float64 `json:"rate"`
|
||||
At *time.Time `json:"at,omitempty"`
|
||||
Stale bool `json:"stale"`
|
||||
// Yuan, with the currency "provider", are the providers whose costs
|
||||
// are shown in yuan, as they sell in it (provider.PricesInYuan)
|
||||
Yuan []string `json:"yuan,omitempty"`
|
||||
}
|
||||
|
||||
// costFX is currentFX with, for the currency "provider", which providers'
|
||||
// costs are in yuan.
|
||||
func costFX(s settings.Settings) fxJSON {
|
||||
out := currentFX()
|
||||
if s.Currency == settings.CurrencyByProvider {
|
||||
out.Yuan = provider.YuanPriced()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// currentFX is the rate known now, never waited for: a stale one is asked
|
||||
@@ -881,7 +894,7 @@ func settingsState() settingsJSON {
|
||||
}
|
||||
s.TerminalDefault = found.Default
|
||||
}
|
||||
s.FX = currentFX()
|
||||
s.FX = costFX(s.Settings)
|
||||
if (s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0 || s.MaskAlert) && notifyProblem != nil {
|
||||
s.NotifyProblem = notifyProblem()
|
||||
}
|
||||
@@ -1688,10 +1701,11 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
// Windows' icon or not, and
|
||||
// with their Pace numbers or not, with magpie's totals' cost or not,
|
||||
// which of each subscription's windows, and the language the tooltip
|
||||
// is in (yi_time)
|
||||
// is in (yi_time), and the currency its totals' cost is in
|
||||
if (!slices.Equal(settings.Load().TrayUsages, cur.TrayUsages) || in.TrayUsageEvery != cur.TrayUsageEvery ||
|
||||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird || in.TrayNoNumber != cur.TrayNoNumber || in.TrayPace != cur.TrayPace ||
|
||||
in.TrayNoCost != cur.TrayNoCost || !maps.EqualFunc(in.TrayWindows, cur.TrayWindows, slices.Equal) || in.Lang != cur.Lang || in.ChineseUnits != cur.ChineseUnits) && onTrayUsage != nil {
|
||||
in.TrayNoCost != cur.TrayNoCost || !maps.EqualFunc(in.TrayWindows, cur.TrayWindows, slices.Equal) || in.Lang != cur.Lang || in.ChineseUnits != cur.ChineseUnits ||
|
||||
in.TrayCostIn() != cur.TrayCostIn()) && onTrayUsage != nil {
|
||||
onTrayUsage()
|
||||
}
|
||||
// an alert turned on or moved is looked at now, the Mac asked for its
|
||||
@@ -3247,8 +3261,8 @@ func state() stateJSON {
|
||||
// state() is asked for after nearly every click, so the rate — a
|
||||
// network fetch once every TTL — is only worth its rare latency when
|
||||
// cny is actually chosen; usd never looks at it
|
||||
if s.Settings.Currency == "cny" {
|
||||
s.FX = currentFX()
|
||||
if s.Settings.Currency != "usd" {
|
||||
s.FX = costFX(s.Settings)
|
||||
}
|
||||
s.Unlisted = unlistedModels()
|
||||
s.CLIBehind = cliBehind()
|
||||
|
||||
@@ -5178,15 +5178,20 @@ body.window .row + .row.agent.conn > .who { min-height: 41px; } /* the line abov
|
||||
.ag-longest, .ag-isolated, .ag-iso-claude { cursor: pointer; }
|
||||
.ag-longest-say, .ag-isolated-say, .ag-iso-claude-say { color: var(--fg-2); }
|
||||
/* the Claude Magpie app's own Claude Code folder (#6459), folded under Advanced */
|
||||
.ag-iso-more > summary { font-size: 12px; line-height: 18px; color: var(--fg-2); list-style: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 0; border-radius: 4px; cursor: pointer; transition: color .12s ease; }
|
||||
.ag-iso-more > summary::-webkit-details-marker { display: none; }
|
||||
.ag-iso-more > summary::before { content: ""; flex: none; width: 10px; height: 10px; background: var(--muted); transition: transform .2s cubic-bezier(.23, 1, .32, 1), background-color .12s ease;
|
||||
.ag-iso-more > summary, .prefs-more > summary { font-size: 12px; line-height: 18px; color: var(--fg-2); list-style: none; display: inline-flex; align-items: center; gap: 5px; padding: 3px 0; border-radius: 4px; cursor: pointer; transition: color .12s ease; }
|
||||
.ag-iso-more > summary::-webkit-details-marker, .prefs-more > summary::-webkit-details-marker { display: none; }
|
||||
.ag-iso-more > summary::before, .prefs-more > summary::before { content: ""; flex: none; width: 10px; height: 10px; background: var(--muted); transition: transform .2s cubic-bezier(.23, 1, .32, 1), background-color .12s ease;
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M3.6 1.6 7 5 3.6 8.4' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M3.6 1.6 7 5 3.6 8.4' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat; }
|
||||
.ag-iso-more[open] > summary::before { transform: rotate(90deg); }
|
||||
@media (hover: hover) and (pointer: fine) { .ag-iso-more > summary:hover { color: var(--fg); } }
|
||||
.ag-iso-more > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) { .ag-iso-more > summary, .ag-iso-more > summary::before { transition: none; } }
|
||||
.ag-iso-more[open] > summary::before, .prefs-more[open] > summary::before { transform: rotate(90deg); }
|
||||
@media (hover: hover) and (pointer: fine) { .ag-iso-more > summary:hover, .prefs-more > summary:hover { color: var(--fg); } }
|
||||
.ag-iso-more > summary:focus-visible, .prefs-more > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) { .ag-iso-more > summary, .ag-iso-more > summary::before, .prefs-more > summary, .prefs-more > summary::before { transition: none; } }
|
||||
/* a settings page's rarely changed rows, folded under Advanced (the menu
|
||||
bar's currency, onkashiko on X) */
|
||||
.prefs-more { margin: 10px 0 0; }
|
||||
.prefs-more > summary { margin-left: 2px; }
|
||||
.prefs-more > .list { margin-top: 6px; }
|
||||
/* which copy is left on the old list: a sentence that wraps as one, under the warning's words */
|
||||
.ag-vl.ag-stale-copy { display: block; padding-left: 14px; font-size: 12px; line-height: 1.6; color: var(--fg-2); }
|
||||
/* Codex's daemon: restarted from its line, a button that sits in the sentence */
|
||||
|
||||
+28
-19
@@ -16004,14 +16004,21 @@ function fmtN(n) {
|
||||
// or cny, converted with fx (the rate this session last got from magpie,
|
||||
// with when that was and whether it's stale — kept only for the tooltip;
|
||||
// see applyPrefs, which fills both from what /api/settings answers).
|
||||
// "provider" shows a cost of one provider's calls in what that provider
|
||||
// sells in (yuanProviders, from fx's yuan: DeepSeek, Kimi's .cn, Zhipu…)
|
||||
// and every sum across providers in totalCurrency.
|
||||
let currency = "usd";
|
||||
let totalCurrency = "usd";
|
||||
let yuanProviders = [];
|
||||
let fx = { rate: 0, at: null, stale: true };
|
||||
function fmtCost(t) {
|
||||
// costInYuan is whether a cost of prov's calls (none: a sum) shows in yuan
|
||||
const costInYuan = (p) => fx.rate > 0 && (currency !== "provider" ? currency === "cny" : p && p !== "session-unknown" ? yuanProviders.includes(p) : totalCurrency === "cny");
|
||||
function fmtCost(t, prov) {
|
||||
// no cost read (null, or a reply without one) is unknown: nothing shown,
|
||||
// not $0 and not a throw that stops the page drawing (#3406)
|
||||
if (typeof t.cost !== "number" || (!t.cost && t.unpriced)) return "";
|
||||
let c = t.cost, sign = "$";
|
||||
if (currency === "cny" && fx.rate > 0) { c = c * fx.rate; sign = "¥"; }
|
||||
if (costInYuan(prov)) { c = c * fx.rate; sign = "¥"; }
|
||||
const s = c >= 100 ? c.toFixed(0) : c >= 1 ? c.toFixed(2) : c.toFixed(3);
|
||||
return sign + s + (t.unpriced ? "+" : "");
|
||||
}
|
||||
@@ -18656,25 +18663,26 @@ function familyQuota(sub) {
|
||||
// holdsLine: a window's whole (WindowHolds), how in its tooltip. With a
|
||||
// baseCost (#5861, no long-context premium) its figure switches every card.
|
||||
let holdsBase = kept("holdsBase", false);
|
||||
function holdsCostText(h) {
|
||||
const c = fmtCost({ cost: holdsBase ? h.baseCost : h.cost });
|
||||
function holdsCostText(h, prov) {
|
||||
const c = fmtCost({ cost: holdsBase ? h.baseCost : h.cost }, prov);
|
||||
return holdsBase ? t("≈ {cost} base", { cost: c }) : t("≈ {cost} API", { cost: c });
|
||||
}
|
||||
function holdsLine(h) {
|
||||
const cost = (c) => fmtCost({ cost: c });
|
||||
function holdsLine(h, prov) {
|
||||
const cost = (c) => fmtCost({ cost: c }, prov);
|
||||
const line = el("span", "quota-holds");
|
||||
line.append(el("span", "", t("Whole ≈ {n} tokens", { n: fmtN(h.tokens) }) + (h.priced ? " ·" : "")));
|
||||
const two = h.priced && h.baseCost > 0;
|
||||
if (two) {
|
||||
const b = el("button", "quota-holds-cost", holdsCostText(h));
|
||||
const b = el("button", "quota-holds-cost", holdsCostText(h, prov));
|
||||
b.type = "button";
|
||||
b._holds = h;
|
||||
b._prov = prov;
|
||||
b.onclick = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
holdsBase = !holdsBase;
|
||||
keep("holdsBase", holdsBase);
|
||||
for (const o of document.querySelectorAll(".quota-holds-cost")) if (o._holds) o.textContent = holdsCostText(o._holds);
|
||||
for (const o of document.querySelectorAll(".quota-holds-cost")) if (o._holds) o.textContent = holdsCostText(o._holds, o._prov);
|
||||
};
|
||||
line.append(" ", b);
|
||||
} else if (h.priced) line.append(" ", el("span", "", "≈ " + cost(h.cost)));
|
||||
@@ -18812,7 +18820,7 @@ function quotaWindows(sub) {
|
||||
// the reset's line, so the window keeps its three rows
|
||||
if (w.holds) {
|
||||
if (!r) quota.append(r = el("div", "quota-reset"));
|
||||
const line = holdsLine(w.holds);
|
||||
const line = holdsLine(w.holds, sub.provider);
|
||||
// a past cycle's whole is reckoned at its own last reading (#2009)
|
||||
// the last window's, kept until this one has data to tell its own
|
||||
if (sub.history || w.holds.prevAt) line.title = t("Estimated from the window that began {start}, read {at}", { start: quotaCycleDate(w.holds.since), at: quotaCycleDate(w.recordedAt || w.holds.prevAt) }) + "\n" + line.title;
|
||||
@@ -18862,9 +18870,9 @@ function ledCredits(x) {
|
||||
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) });
|
||||
|
||||
// a cost as an axis says it: the currency Settings picks, no more digits than it takes
|
||||
function ledMoney(v) {
|
||||
function ledMoney(v, prov) {
|
||||
let sign = "$";
|
||||
if (currency === "cny" && fx.rate > 0) { v *= fx.rate; sign = "¥"; }
|
||||
if (costInYuan(prov)) { v *= fx.rate; sign = "¥"; }
|
||||
return sign + (v >= 10 ? v.toFixed(0) : v >= 1 ? v.toFixed(1) : v.toFixed(2));
|
||||
}
|
||||
|
||||
@@ -19337,7 +19345,7 @@ function openSessCombo(anchor, all, opts, value, choose, head) {
|
||||
const THEMES = [["system", "System"], ["light", "Light"], ["dark", "Dark"]];
|
||||
const LOCALES = [["system", "System"], ["en", "English"], ["zh", "简体中文"], ["zh-TW", "繁體中文"], ["ja", "日本語"], ["de", "Deutsch"]];
|
||||
const TRAYS = [["panel", "Open the quick panel"], ["window", "Open the main window"]];
|
||||
const CURRENCIES = [["usd", "$ USD"], ["cny", "¥ CNY"]];
|
||||
const CURRENCIES = [["usd", "$ USD"], ["cny", "¥ CNY"], ["provider", "By provider"]];
|
||||
// The text size is the windows' own zoom, as a browser's Ctrl/Cmd +: the
|
||||
// page is laid out again in larger CSS pixels, so everything it measures is
|
||||
// as at 100%, and magpie sizes the windows around it (textsize.go). None is
|
||||
@@ -19591,8 +19599,12 @@ function applyPrefs(s, rate) {
|
||||
const moved = !!got && got.rate !== fx.rate;
|
||||
if (got) fx = got;
|
||||
let costs = false;
|
||||
if (currency !== (s.currency || "usd") || (moved && currency === "cny")) {
|
||||
const yuan = got?.yuan || [];
|
||||
if (currency !== (s.currency || "usd") || totalCurrency !== (s.totalCurrency || "usd") ||
|
||||
(currency === "provider" && yuan + "" !== yuanProviders + "") || (moved && currency !== "usd")) {
|
||||
currency = s.currency || "usd";
|
||||
totalCurrency = s.totalCurrency || "usd";
|
||||
yuanProviders = yuan;
|
||||
costs = true;
|
||||
}
|
||||
if (chineseUnits !== !!s.chineseUnits) {
|
||||
@@ -20671,7 +20683,8 @@ function renderTrayUsage(s, keep) {
|
||||
$("#quotaReadsSegs").replaceChildren(segs([["", t("Automatic")], ["asked", t("When I ask")]], s.quotaReads || "", (v) =>
|
||||
writingPrefs(api("settings/quota-reads", { reads: v })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
|
||||
.catch(settingsErr)));
|
||||
$("#currencySegs").replaceChildren(segs(CURRENCIES.map(([id, name]) => [id, t(name)]), s.currency || "usd", (v) => savePrefs({ ...keep, currency: v })));
|
||||
// the currency rows, in currencyprefs.js
|
||||
import("./currencyprefs.js").then(() => currencyPrefs(s, keep), () => {});
|
||||
// 万 and 亿 are Chinese's alone: in English a count is always K, M and B
|
||||
$("#unitsRow").hidden = locale !== "zh" && locale !== "zh-TW";
|
||||
$("#unitsSegs").replaceChildren(segs([[false, t("K / M / B")], [true, t("万 / 亿")]], !!s.chineseUnits,
|
||||
@@ -20683,10 +20696,6 @@ function renderTrayUsage(s, keep) {
|
||||
renderAgentPrefs();
|
||||
renderAgentPrefLinks();
|
||||
renderProvPrefLinks();
|
||||
const rate = s.fx?.rate;
|
||||
const currencySub = $("#currencySub");
|
||||
currencySub.textContent = t("What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted");
|
||||
currencySub.title = rate ? t("1 USD = {rate} CNY{when}", { rate: rate.toFixed(2), when: s.fx.at ? " · " + (s.fx.stale ? t("last fetched {when}", { when: syncWhen(s.fx.at) }) : t("fetched {when}", { when: syncWhen(s.fx.at) })) : "" }) : "";
|
||||
$("#trayUsageRow").hidden = web;
|
||||
if (web) return;
|
||||
const mac = document.body.classList.contains("mac");
|
||||
@@ -22846,7 +22855,7 @@ function prefsKeep(s) {
|
||||
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, checkinAt: s.checkinAt || "", noStats: !!s.noStats, noUsageStats: !!s.noUsageStats, signInLinkOnly: !!s.signInLinkOnly,
|
||||
replyModel: s.replyModel || "", noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null, retryAfterCap: s.retryAfterCap ?? null,
|
||||
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
|
||||
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayNoNumber: !!s.trayNoNumber, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", videoGen: s.videoGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
|
||||
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayNoNumber: !!s.trayNoNumber, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", videoGen: s.videoGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd", totalCurrency: s.totalCurrency || "", trayCurrency: s.trayCurrency || "",
|
||||
chineseUnits: !!s.chineseUnits, dayStart: s.dayStart || 0, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
|
||||
turnDoneAlert: s.turnDoneAlert || 0, maskAlert: !!s.maskAlert };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Settings › Usage › Currency, its Totals in row and Advanced's Menu bar
|
||||
// currency. app.js imports this when Settings draws its usage prefs
|
||||
// (renderTrayUsage), so it weighs nothing on the core.
|
||||
|
||||
window.currencyPrefs = function currencyPrefs(s, keep) {
|
||||
const two = CURRENCIES.slice(0, 2).map(([id, name]) => [id, t(name)]);
|
||||
$("#currencySegs").replaceChildren(segs(CURRENCIES.map(([id, name]) => [id, t(name)]), s.currency || "usd", (v) => savePrefs({ ...keep, currency: v })));
|
||||
// "provider": each provider's costs in what it sells in, every sum in
|
||||
// Totals in (onkashiko on X)
|
||||
$("#totalCurrencyRow").hidden = s.currency !== "provider";
|
||||
$("#totalCurrencySegs").replaceChildren(segs(two, s.totalCurrency || "usd", (v) => savePrefs({ ...keep, totalCurrency: v })));
|
||||
// the menu bar's and its tooltip's totals in a currency of their own, or
|
||||
// as the totals are (onkashiko on X): seldom changed, so under Advanced,
|
||||
// open when it is set
|
||||
$("#trayCurrencySegs").replaceChildren(segs([["", t("Same as totals")], ...two], s.trayCurrency || "", (v) => savePrefs({ ...keep, trayCurrency: v })));
|
||||
if (s.trayCurrency) $("#usageMore").open = true;
|
||||
const rate = s.fx?.rate, sub = $("#currencySub");
|
||||
sub.textContent = s.currency === "provider" ? t("Each provider's costs in what it sells in: yuan for DeepSeek, Kimi, Zhipu and other Chinese vendors, dollars for the rest")
|
||||
: t("What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted");
|
||||
sub.title = rate ? t("1 USD = {rate} CNY{when}", { rate: rate.toFixed(2), when: s.fx.at ? " · " + (s.fx.stale ? t("last fetched {when}", { when: syncWhen(s.fx.at) }) : t("fetched {when}", { when: syncWhen(s.fx.at) })) : "" }) : "";
|
||||
};
|
||||
@@ -1523,6 +1523,11 @@ const I18N = {
|
||||
"Codex's multi-agent V1 is on, but magpie couldn't read Codex's config to check its own multi_agent_v2.": "Codex 的 multi-agent V1 已开启,但 magpie 读不到 Codex 的配置,无法确认它自己的 multi_agent_v2。",
|
||||
"$ USD": "$ 美元",
|
||||
"¥ CNY": "¥ 人民币",
|
||||
"By provider": "按供应商",
|
||||
"Totals in": "合计币种",
|
||||
"Menu bar currency": "菜单栏币种",
|
||||
"Same as totals": "同合计",
|
||||
"Each provider's costs in what it sells in: yuan for DeepSeek, Kimi, Zhipu and other Chinese vendors, dollars for the rest": "每家供应商的费用按其计价币种显示:DeepSeek、Kimi、智谱等国内厂商用人民币,其余用美元",
|
||||
"What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted": "用量页、托盘面板、TUI 和命令行的费用按此币种显示;厂商余额保持其原币种,不换算",
|
||||
"1 USD = {rate} CNY{when}": "1 美元 = {rate} 元{when}",
|
||||
"fetched {when}": "{when}获取",
|
||||
@@ -6767,6 +6772,11 @@ const I18N = {
|
||||
"Codex's multi-agent V1 is on, but magpie couldn't read Codex's config to check its own multi_agent_v2.": "Codex 的 multi-agent V1 已開啟,但 magpie 讀不到 Codex 的設定,無法確認它自己的 multi_agent_v2。",
|
||||
"$ USD": "$ 美元",
|
||||
"¥ CNY": "¥ 人民幣",
|
||||
"By provider": "按供應商",
|
||||
"Totals in": "合計幣種",
|
||||
"Menu bar currency": "選單列幣種",
|
||||
"Same as totals": "同合計",
|
||||
"Each provider's costs in what it sells in: yuan for DeepSeek, Kimi, Zhipu and other Chinese vendors, dollars for the rest": "每家供應商的費用按其計價幣種顯示:DeepSeek、Kimi、智譜等中國大陸廠商用人民幣,其餘用美元",
|
||||
"What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted": "用量頁、托盤面板、TUI 和命令列的費用按此幣種顯示;廠商餘額保持其原幣種,不換算",
|
||||
"1 USD = {rate} CNY{when}": "1 美元 = {rate} 元{when}",
|
||||
"fetched {when}": "{when}取得",
|
||||
@@ -11979,6 +11989,11 @@ const I18N = {
|
||||
"Codex's multi-agent V1 is on, but magpie couldn't read Codex's config to check its own multi_agent_v2.": "Codex の multi-agent V1 はオンですが、magpie は Codex の設定を読めなかったため、それ自身の multi_agent_v2 を確認できません。",
|
||||
"$ USD": "$ 米ドル",
|
||||
"¥ CNY": "¥ 人民元",
|
||||
"By provider": "プロバイダー別",
|
||||
"Totals in": "合計の通貨",
|
||||
"Menu bar currency": "メニューバーの通貨",
|
||||
"Same as totals": "合計と同じ",
|
||||
"Each provider's costs in what it sells in: yuan for DeepSeek, Kimi, Zhipu and other Chinese vendors, dollars for the rest": "各プロバイダーの費用をその販売通貨で表示:DeepSeek、Kimi、Zhipu など中国のベンダーは人民元、その他はドル",
|
||||
"What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted": "費用(使用量ページ、トレイパネル、TUI、CLI のもの)をどの通貨で表示するか。ベンダー自身の残高はすでにその通貨建てなので、換算されません",
|
||||
"1 USD = {rate} CNY{when}": "1 USD = {rate} CNY{when}",
|
||||
"fetched {when}": "{when}に取得",
|
||||
@@ -17222,6 +17237,11 @@ const I18N = {
|
||||
"Codex's multi-agent V1 is on, but magpie couldn't read Codex's config to check its own multi_agent_v2.": "Codex' multi-agent V1 ist an, aber magpie konnte Codex' Konfiguration nicht lesen, um dessen eigenes multi_agent_v2 zu prüfen.",
|
||||
"$ USD": "$ USD",
|
||||
"¥ CNY": "¥ CNY",
|
||||
"By provider": "Je Anbieter",
|
||||
"Totals in": "Summen in",
|
||||
"Menu bar currency": "Währung in der Menüleiste",
|
||||
"Same as totals": "Wie Summen",
|
||||
"Each provider's costs in what it sells in: yuan for DeepSeek, Kimi, Zhipu and other Chinese vendors, dollars for the rest": "Die Kosten jedes Anbieters in seiner Verkaufswährung: Yuan für DeepSeek, Kimi, Zhipu und andere chinesische Anbieter, Dollar für den Rest",
|
||||
"What a cost — the Usage page's, the tray panel's, the TUI's and the CLI's — is shown as; a vendor's own balance, already in its own currency, is never converted": "Wie Kosten angezeigt werden — auf der Seite „Nutzung“, im Tray-Panel, in der TUI und in der CLI; das eigene Guthaben eines Anbieters, bereits in seiner Währung, wird nie umgerechnet",
|
||||
"1 USD = {rate} CNY{when}": "1 USD = {rate} CNY{when}",
|
||||
"fetched {when}": "abgerufen {when}",
|
||||
|
||||
@@ -330,6 +330,10 @@
|
||||
<div class="who"><div class="name" data-t>Currency</div><div class="sub" id="currencySub"></div></div>
|
||||
<div id="currencySegs"></div>
|
||||
</div>
|
||||
<div class="row pref" id="totalCurrencyRow" hidden>
|
||||
<div class="who"><div class="name" data-t>Totals in</div></div>
|
||||
<div id="totalCurrencySegs"></div>
|
||||
</div>
|
||||
<div class="row pref">
|
||||
<div class="who"><div class="name" data-t>Day starts at</div></div>
|
||||
<div id="dayStartSegs"></div>
|
||||
@@ -340,6 +344,15 @@
|
||||
</div>
|
||||
<div id="provPrefLinks"></div>
|
||||
</div>
|
||||
<details class="prefs-more app-only" id="usageMore">
|
||||
<summary data-t>Advanced</summary>
|
||||
<div class="list prefs">
|
||||
<div class="row pref" id="trayCurrencyRow">
|
||||
<div class="who"><div class="name" data-t>Menu bar currency</div></div>
|
||||
<div id="trayCurrencySegs"></div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<div class="row-head" id="alertHead"><span class="label" data-t>Alerts</span></div>
|
||||
<div class="list prefs" id="alertList">
|
||||
<div class="row pref" id="usageAlertRow">
|
||||
|
||||
@@ -946,7 +946,7 @@ function routingPage(part) {
|
||||
// read it for this request (Weighed.price)
|
||||
const p = f.price;
|
||||
if (p) {
|
||||
const price = t("{in} in, {out} out a million tokens", { in: fmtCost({ cost: p.input }), out: fmtCost({ cost: p.output }) });
|
||||
const price = t("{in} in, {out} out a million tokens", { in: fmtCost({ cost: p.input }, f.provider), out: fmtCost({ cost: p.output }, f.provider) });
|
||||
if (p.peak) return restedTo(t("it costs least now, even at its peak price — {price}.", { price }))
|
||||
|| t("Cheapest first: {model} costs least on {who} now, even at its peak price — {price}.", { model: f.model, who: w, price });
|
||||
return restedTo(t("it costs least now — {price}.", { price }))
|
||||
@@ -4130,10 +4130,17 @@ function routingPage(part) {
|
||||
return said ? ledCredits({ credits: n, credited: said }).textContent : "";
|
||||
}
|
||||
const creditsNote = () => t("What it cost in its plan's credits, as the reply said");
|
||||
// the one provider a request's cost is of, for Settings' currency "By
|
||||
// provider": none (a sum, in the totals' currency) when its tries went to
|
||||
// more than one
|
||||
function routeProvider(r) {
|
||||
const ids = new Set((r.tries || []).map((tr) => tr.id).filter(Boolean));
|
||||
return ids.size === 1 ? [...ids][0] : !ids.size && !r.group ? r.provider : "";
|
||||
}
|
||||
function routeCost(r) {
|
||||
const credits = routeCredits([r]);
|
||||
if (!r.priced) return credits || "—";
|
||||
return "≈" + fmtCost({ cost: r.cost || 0, unpriced: 0 }) + (r.unpriced ? "+" : "") + (credits ? " · " + credits : "");
|
||||
return "≈" + fmtCost({ cost: r.cost || 0, unpriced: 0 }, routeProvider(r)) + (r.unpriced ? "+" : "") + (credits ? " · " + credits : "");
|
||||
}
|
||||
// byKey: grouped by the gateway key each came with, one sent with none
|
||||
// (from this computer, or kept before routes named their key) a group of
|
||||
|
||||
@@ -926,7 +926,7 @@ function renderUsage() {
|
||||
const hit = g.cache_read && hitRate !== null ? " · " + t("hit rate {p}", { p: hitPct(hitRate) }) : "";
|
||||
num.append(el("b", "", fmtN(usageTokens(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit));
|
||||
r.append(num);
|
||||
r.append(el("div", "cost", fmtCost(g) ? "≈" + fmtCost(g) : ""));
|
||||
r.append(el("div", "cost", fmtCost(g, g.provider) ? "≈" + fmtCost(g, g.provider) : ""));
|
||||
if (act) act(r, g);
|
||||
box.append(r);
|
||||
}
|
||||
@@ -1942,7 +1942,7 @@ function ledDetail(r) {
|
||||
if (r.in || r.out || r.cache_read || r.cache_write || !ledFailed_(r)) {
|
||||
add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum) + (r.cache_unknown ? " · " + t("The vendor doesn't count the cache") : ""), "led-tokens");
|
||||
}
|
||||
if (r.priced) add("Cost", "≈" + fmtCost({ cost: r.cost, unpriced: 0 }));
|
||||
if (r.priced) add("Cost", "≈" + fmtCost({ cost: r.cost, unpriced: 0 }, r.provider));
|
||||
if (r.credits != null) add("Credits", ledCredits({ credits: r.credits, credited: 1 }).textContent);
|
||||
if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) }));
|
||||
else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) }));
|
||||
@@ -3300,7 +3300,7 @@ function renderLedger() {
|
||||
// (jiabubu on Discord): in place of the dash a plan's model has for a
|
||||
// price, or under the price; a reply that said none says nothing
|
||||
const credits = r.credits != null ? ledCredits({ credits: r.credits, credited: 1 }).textContent : "";
|
||||
const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }) : credits || "—", "n cost" + (r.priced || credits ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : credits ? t("What it cost in its plan's credits, as the reply said") : t("No known price for this model"));
|
||||
const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }, r.provider) : credits || "—", "n cost" + (r.priced || credits ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : credits ? t("What it cost in its plan's credits, as the reply said") : t("No known price for this model"));
|
||||
if (r.priced && r.pricing_model) {
|
||||
const reference = el("div", "price-reference", t("Price reference: {model}", { model: r.pricing_model }));
|
||||
reference.title = t("Model used for the API price estimate; this is not an observed model forwarding event.");
|
||||
|
||||
@@ -111,7 +111,7 @@ func barkSummary(ctx context.Context, now time.Time) (title, body string) {
|
||||
if pct <= 0 {
|
||||
pct = barkNearPct
|
||||
}
|
||||
currency, rate := trayCurrency()
|
||||
currency, rate := totalsCurrency()
|
||||
return barkDailyText(trayLang(s.Lang, systemLang), trayTotalSum(usage.Today), currency, rate,
|
||||
provider.NearLimits(qs, pct, s.BalanceAlert, now), s.BalanceAlert, s.QuotaLeft, now)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/fx"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Currency "By provider" (onkashiko on X): the window is told which
|
||||
// providers sell in yuan, beside the rate, and the menu bar's totals — a
|
||||
// sum of every provider — go in the currency picked for totals.
|
||||
func TestFXByProvider(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
fx.Reset()
|
||||
cache := fx.CachePath()
|
||||
if err := os.MkdirAll(filepath.Dir(cache), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(fx.Rate{CNYPerUSD: 7.25, At: time.Now().Add(-time.Hour)})
|
||||
if err := os.WriteFile(cache, b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fx.Reset()
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "deepseek", Name: "DeepSeek", Preset: "deepseek", Key: "k", Chat: "https://api.deepseek.com/v1"},
|
||||
{ID: "zai", Name: "Z.ai", Preset: "zai", Key: "k", Chat: "https://api.z.ai/api/paas/v4"},
|
||||
{ID: "openai", Name: "OpenAI", Preset: "openai", Key: "k", Chat: "https://api.openai.com/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := settings.Save(settings.Settings{Currency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := state().FX; got.Yuan != nil {
|
||||
t.Fatalf("cny: no provider list needed, got %v", got.Yuan)
|
||||
}
|
||||
|
||||
if err := settings.Save(settings.Settings{Currency: settings.CurrencyByProvider}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, got := range []fxJSON{state().FX, settingsState().FX} {
|
||||
if got.Rate != 7.25 || !slices.Contains(got.Yuan, "deepseek") || slices.Contains(got.Yuan, "zai") || slices.Contains(got.Yuan, "openai") {
|
||||
t.Fatalf("by provider: FX = %+v, want the rate and deepseek alone in yuan", got)
|
||||
}
|
||||
}
|
||||
if c, _ := trayCurrency(); c != "usd" {
|
||||
t.Fatalf("by provider, totals unset: menu bar in %s, want usd", c)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Currency: settings.CurrencyByProvider, TotalCurrency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, rate := trayCurrency(); c != "cny" || rate != 7.25 {
|
||||
t.Fatalf("by provider, totals in cny: menu bar in %s at %v", c, rate)
|
||||
}
|
||||
// the menu bar set apart from the totals (onkashiko on X), and the
|
||||
// daily Bark message, a total, still in the totals'
|
||||
if err := settings.Save(settings.Settings{Currency: settings.CurrencyByProvider, TotalCurrency: "cny", TrayCurrency: "usd"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, _ := trayCurrency(); c != "usd" {
|
||||
t.Fatalf("menu bar set to usd, totals in cny: menu bar in %s", c)
|
||||
}
|
||||
if c, rate := totalsCurrency(); c != "cny" || rate != 7.25 {
|
||||
t.Fatalf("menu bar set to usd, totals in cny: totals in %s at %v", c, rate)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Currency: "usd", TrayCurrency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, rate := trayCurrency(); c != "cny" || rate != 7.25 {
|
||||
t.Fatalf("menu bar set to cny, totals in usd: menu bar in %s at %v", c, rate)
|
||||
}
|
||||
}
|
||||
@@ -102,11 +102,9 @@ func pageDay(params map[string]any) (any, error) {
|
||||
want(m.Icon)
|
||||
}
|
||||
}
|
||||
// a cost as Settings shows it: in USD, or in CNY at the rate known now
|
||||
cur := settings.Load().Currency
|
||||
if cur == "" {
|
||||
cur = "usd"
|
||||
}
|
||||
// a cost as Settings shows a sum of several providers': in USD, or in
|
||||
// CNY at the rate known now
|
||||
cur := settings.Load().TotalCostIn()
|
||||
return struct {
|
||||
usageapi.Day
|
||||
Icons map[string]pageIcon `json:"icons"`
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Currency "By provider" (onkashiko on X): each provider's costs show in
|
||||
// what it sells in — DeepSeek's in yuan, OpenAI's in dollars — and every
|
||||
// sum across providers in the currency the "Totals in" row picks, a row
|
||||
// shown only while By provider is chosen. The menu bar's own currency
|
||||
// (its second ask) is a row folded under Advanced. Every language, at a narrow
|
||||
// window; no backend, the API is faked here as the Go side answers it
|
||||
// (fx.yuan only in By provider, costFX).
|
||||
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 { openPart } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
const usage = {
|
||||
calls: 5, errors: 0, input: 12000, output: 4000, cache_read: 0, cache_write: 0, reasoning: 0,
|
||||
unpriced: 0, cost: 3, bucket: "day",
|
||||
series: [{ label: "Mon", input: 12000, output: 4000, calls: 5, cost: 3 }],
|
||||
agents: [{ name: "Claude Code", calls: 5, cost: 3, input: 12000, output: 4000 }],
|
||||
models: [
|
||||
{ id: "deepseek/deepseek-chat", name: "deepseek-chat", provider: "deepseek", calls: 3, cost: 1, input: 6000, output: 2000 },
|
||||
{ id: "openai/gpt-5", name: "gpt-5", provider: "openai", calls: 2, cost: 2, input: 6000, output: 2000 },
|
||||
],
|
||||
};
|
||||
|
||||
const fxOf = (s) => ({ rate: 7.2, at: new Date().toISOString(), stale: false, ...(s.currency === "provider" ? { yuan: ["deepseek"] } : {}) });
|
||||
|
||||
function settingsPayload(over) {
|
||||
const s = {
|
||||
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
...over,
|
||||
};
|
||||
return { ...s, fx: fxOf(s) };
|
||||
}
|
||||
|
||||
function server(lang, saved) {
|
||||
let cur = settingsPayload({ lang });
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", currency: cur.currency, totalCurrency: cur.totalCurrency }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") {
|
||||
const body = req.postDataJSON();
|
||||
saved.push(body);
|
||||
cur = settingsPayload({ ...cur, ...body });
|
||||
}
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/usage") return json(usage);
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
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 route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const LANGS = [
|
||||
["en", "By provider", "Totals in", "Advanced", "Menu bar currency", "Same as totals"],
|
||||
["zh", "按供应商", "合计币种", "高级", "菜单栏币种", "同合计"],
|
||||
["zh-TW", "按供應商", "合計幣種", "進階", "選單列幣種", "同合計"],
|
||||
["ja", "プロバイダー別", "合計の通貨", "詳細設定", "メニューバーの通貨", "合計と同じ"],
|
||||
["de", "Je Anbieter", "Summen in", "Erweitert", "Währung in der Menüleiste", "Wie Summen"],
|
||||
];
|
||||
|
||||
const modelCost = (page, name) => page.locator("#usageModels .row", { hasText: name }).locator(".cost").textContent().then((s) => s.trim());
|
||||
const totalCost = (page) => page.locator("#usageCost b").textContent().then((s) => s.trim());
|
||||
|
||||
async function toUsage(page) {
|
||||
await page.locator('[data-view="usage"]').click();
|
||||
await page.locator("#usageModels .row").first().waitFor();
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
|
||||
async function toSettings(page) {
|
||||
await page.locator("#prefs").click();
|
||||
await openPart(page, "usage");
|
||||
await page.locator("#currencySegs .opt").first().waitFor();
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": By provider shows each provider in its own currency, totals in the chosen one", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const pages = [];
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-currency-provider-${i}.png`) }).catch(() => {});
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
for (const [lang, byProvider, totalsIn, advanced, menuBar, sameAs] of LANGS) {
|
||||
for (const width of [900, 420]) {
|
||||
await t.test(`${lang} at ${width}px`, async () => {
|
||||
const errors = [], saved = [];
|
||||
const context = await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
pages.push(page);
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, saved));
|
||||
|
||||
// dollars everywhere by default
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator("#usageModels .row").first().waitFor();
|
||||
assert.equal(await totalCost(page), "≈$3.00");
|
||||
assert.equal(await modelCost(page, "deepseek-chat"), "≈$1.00");
|
||||
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
|
||||
|
||||
// Settings: the third choice, and no "Totals in" row until it is picked
|
||||
await toSettings(page);
|
||||
const segs = page.locator("#currencySegs .opt");
|
||||
assert.equal(await segs.count(), 3);
|
||||
assert.equal((await segs.nth(2).textContent()).trim(), byProvider);
|
||||
assert.equal(await page.locator("#totalCurrencyRow").isVisible(), false, "Totals in shows only for By provider");
|
||||
await segs.nth(2).click();
|
||||
await page.locator("#currencySegs .opt.on", { hasText: byProvider }).waitFor();
|
||||
await page.locator("#totalCurrencyRow").waitFor({ state: "visible" });
|
||||
assert.equal((await page.locator("#totalCurrencyRow .name").textContent()).trim(), totalsIn);
|
||||
assert.equal(saved.at(-1).currency, "provider");
|
||||
const totals = page.locator("#totalCurrencySegs .opt");
|
||||
assert.equal(await totals.count(), 2, "totals are $ or ¥, never By provider");
|
||||
assert.equal(await totals.nth(0).evaluate((b) => b.classList.contains("on")), true, "totals start in $");
|
||||
// nothing of either row spills out of a narrow window
|
||||
for (const sel of ["#currencySegs", "#totalCurrencySegs"]) {
|
||||
const box = await page.locator(sel).boundingBox();
|
||||
assert(box.x >= 0 && box.x + box.width <= width + 0.5, `${sel} spills out at ${width}px: ${JSON.stringify(box)}`);
|
||||
}
|
||||
|
||||
// Usage: DeepSeek in yuan (1 × 7.2), OpenAI and the total in dollars
|
||||
await toUsage(page);
|
||||
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
|
||||
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
|
||||
assert.equal(await totalCost(page), "≈$3.00");
|
||||
|
||||
// totals in yuan: the sum goes ¥, each provider keeps its own
|
||||
await toSettings(page);
|
||||
await page.locator("#totalCurrencySegs .opt").nth(1).click();
|
||||
await page.locator("#totalCurrencySegs .opt.on").nth(0).waitFor();
|
||||
assert.equal(await page.locator("#totalCurrencySegs .opt").nth(1).evaluate((b) => b.classList.contains("on")), true);
|
||||
assert.equal(saved.at(-1).totalCurrency, "cny");
|
||||
assert.equal(saved.at(-1).currency, "provider", "picking the totals' currency keeps By provider");
|
||||
await toUsage(page);
|
||||
assert.equal(await totalCost(page), "≈¥21.60");
|
||||
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
|
||||
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
|
||||
|
||||
// the menu bar's currency, set apart from the totals' (onkashiko's
|
||||
// second ask): folded under Advanced, closed while unset
|
||||
await toSettings(page);
|
||||
const more = page.locator("#usageMore");
|
||||
assert.equal((await more.locator("summary").textContent()).trim(), advanced);
|
||||
assert.equal(await more.evaluate((d) => d.open), false, "Advanced starts folded");
|
||||
assert.equal(await page.locator("#trayCurrencyRow").isVisible(), false);
|
||||
await more.locator("summary").click();
|
||||
await page.locator("#trayCurrencyRow").waitFor({ state: "visible" });
|
||||
assert.equal((await page.locator("#trayCurrencyRow .name").textContent()).trim(), menuBar);
|
||||
const bar = page.locator("#trayCurrencySegs .opt");
|
||||
assert.equal(await bar.count(), 3, "same as totals, $ and ¥");
|
||||
assert.equal((await bar.nth(0).textContent()).trim(), sameAs);
|
||||
assert.equal(await bar.nth(0).evaluate((b) => b.classList.contains("on")), true, "follows the totals until picked");
|
||||
const box = await page.locator("#trayCurrencySegs").boundingBox();
|
||||
assert(box.x >= 0 && box.x + box.width <= width + 0.5, `#trayCurrencySegs spills out at ${width}px: ${JSON.stringify(box)}`);
|
||||
await bar.nth(1).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll("#trayCurrencySegs .opt")[1]?.classList.contains("on"));
|
||||
assert.equal(saved.at(-1).trayCurrency, "usd");
|
||||
assert.equal(saved.at(-1).totalCurrency, "cny", "the menu bar's pick leaves the totals'");
|
||||
assert.equal(saved.at(-1).currency, "provider");
|
||||
await toUsage(page);
|
||||
assert.equal(await totalCost(page), "≈¥21.60", "the menu bar's pick leaves the Usage page's totals");
|
||||
|
||||
// after a restart, straight onto Usage: the same
|
||||
await page.reload();
|
||||
await page.locator("#usageModels .row").first().waitFor();
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await totalCost(page), "≈¥21.60");
|
||||
assert.equal(await modelCost(page, "deepseek-chat"), "≈¥7.20");
|
||||
assert.equal(await modelCost(page, "gpt-5"), "≈$2.00");
|
||||
|
||||
// a set menu bar currency opens Advanced, so it is seen
|
||||
await toSettings(page);
|
||||
assert.equal(await page.locator("#usageMore").evaluate((d) => d.open), true, "Advanced open while the menu bar's is set");
|
||||
assert.equal(await page.locator("#trayCurrencySegs .opt").nth(1).evaluate((b) => b.classList.contains("on")), true, "$ kept");
|
||||
|
||||
// back to $ USD: the Totals in row goes, everything is in dollars
|
||||
await toSettings(page);
|
||||
await page.locator("#currencySegs .opt").nth(0).click();
|
||||
await page.locator("#totalCurrencyRow").waitFor({ state: "hidden" });
|
||||
await toUsage(page);
|
||||
assert.equal(await modelCost(page, "deepseek-chat"), "≈$1.00");
|
||||
assert.equal(await totalCost(page), "≈$3.00");
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -99,7 +99,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await openPart(page, "usage");
|
||||
await page.locator("#currencySegs .opt").first().waitFor();
|
||||
const segs = page.locator("#currencySegs .opt");
|
||||
assert.equal(await segs.count(), 2);
|
||||
assert.equal(await segs.count(), 3, "$, ¥ and By provider");
|
||||
assert.equal((await segs.nth(0).textContent()).trim(), usd);
|
||||
assert.equal((await segs.nth(1).textContent()).trim(), cny);
|
||||
assert.equal(await segs.nth(0).evaluate((b) => b.classList.contains("on")), true, "usd starts picked");
|
||||
|
||||
@@ -184,7 +184,7 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// keyrates.js when a provider with two or more keys opens;
|
||||
// the checks above
|
||||
// still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js", "currencyprefs.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -131,12 +131,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
workbuddyCheckins: [{ user: "Ann", day: today, at: new Date().toISOString(), outcome: "claimed", credit: 2, streak: 3 }],
|
||||
});
|
||||
|
||||
// Settings' Usage part: its list and the Alerts, no service's rows
|
||||
// Settings' Usage part: its list, its Advanced fold (the menu bar's
|
||||
// currency) and the Alerts, no service's rows
|
||||
await page.goto("http://magpie.test/?view=settings&tab=usage");
|
||||
await page.locator("#setPage-usage #currencySegs .opt").first().waitFor();
|
||||
const parts = await page.evaluate(() => [...document.querySelectorAll("#setPage-usage > *")]
|
||||
.map((h) => h.querySelector("#currencySegs") ? "usage" : h.id));
|
||||
assert.deepEqual(parts, ["usage", "alertHead", "alertList"]);
|
||||
assert.deepEqual(parts, ["usage", "usageMore", "alertHead", "alertList"]);
|
||||
assert.equal(await page.locator("#warmTabs, .warm-panes").count(), 0, "no tabs left");
|
||||
for (const id of ["#warmSegs", "#warmAtSegs", "#claudeWarmSegs", "#claudeWarmAtSegs", "#wbCheckinSegs", "#traeCheckinSegs"]) {
|
||||
assert.equal(await page.locator("#setPage-usage").locator(id).count(), 0, id + " is out of Settings");
|
||||
|
||||
@@ -522,10 +522,21 @@ func trayMoney(t usage.Totals, noCost bool) usage.Totals {
|
||||
return t
|
||||
}
|
||||
|
||||
// trayCurrency is the currency Settings shows costs in, and the yuan's
|
||||
// rate when that is CNY.
|
||||
// trayCurrency is the currency the menu bar and its tooltip show magpie's
|
||||
// totals' cost in (Settings' Menu bar currency, else the totals'), and the
|
||||
// yuan's rate when that is CNY.
|
||||
func trayCurrency() (currency string, rate float64) {
|
||||
currency = settings.Load().Currency
|
||||
return currencyRate(settings.Load().TrayCostIn())
|
||||
}
|
||||
|
||||
// totalsCurrency is the currency Settings shows a sum of costs in (a
|
||||
// total's, of every provider), and the yuan's rate when that is CNY.
|
||||
func totalsCurrency() (currency string, rate float64) {
|
||||
return currencyRate(settings.Load().TotalCostIn())
|
||||
}
|
||||
|
||||
func currencyRate(currency string) (string, float64) {
|
||||
var rate float64
|
||||
if currency == "cny" {
|
||||
rate = fx.Soon().CNYPerUSD // never waited for, as the Settings page's
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// yuanPresets are the presets that sell in China's yuan whose id doesn't
|
||||
// end in -cn and whose API isn't on a .cn host: DeepSeek, Zhipu's
|
||||
// bigmodel.cn, Volcengine's Ark, Tencent Cloud, Baidu Qianfan, Huawei
|
||||
// Cloud, Alibaba's Bailian. Their international twins (Z.ai, Kimi,
|
||||
// MiniMax, StepFun's .ai, Qwen) share a models.dev catalog with them, so
|
||||
// the catalog alone can't tell a preset's currency.
|
||||
var yuanPresets = map[string]bool{
|
||||
"deepseek": true, "zhipu": true, "volcengine": true, "volcengine-decision": true,
|
||||
"tencent-cloud": true, "baidu-qianfan": true, "huaweicloud": true,
|
||||
"bailian-token-plan": true, "bailian-decision": true, "siliconflow": true, "modelscope": true,
|
||||
}
|
||||
|
||||
// PricesInYuan is whether p sells in China's yuan, for Settings' currency
|
||||
// "provider", which shows each provider's costs in what it prices in. A
|
||||
// preset's provider at the preset's own site does when it is a yuan preset
|
||||
// (yuanPresets, or an id ending in -cn: Kimi (China), MiniMax (China)…)
|
||||
// or in its China region (a first catalog ending in -cn: Xiaomi's); one
|
||||
// moved to another site (a relay made from DeepSeek's preset) is not that
|
||||
// vendor. Any provider on a .cn host does, and so does a plugin's id
|
||||
// ending in -cn (Qoder CN). A provider of its own (no preset) does with a
|
||||
// yuan catalog (catalog.PricedInYuan) served at that catalog's own site.
|
||||
// Everything else is in dollars.
|
||||
func (p Provider) PricesInYuan() bool {
|
||||
h := strings.ToLower(p.Host())
|
||||
if host, _, err := net.SplitHostPort(h); err == nil {
|
||||
h = host
|
||||
}
|
||||
if strings.HasSuffix(h, ".cn") {
|
||||
return true
|
||||
}
|
||||
cs := p.Catalogs()
|
||||
if pr := Preset(p.Preset); pr != nil {
|
||||
if h != "" && !sameSite(h, HostOf(cmp.Or(pr.Chat, pr.Anthropic, pr.Responses, pr.Decide))) {
|
||||
return false
|
||||
}
|
||||
id := strings.ToLower(pr.ID)
|
||||
return yuanPresets[id] || strings.HasSuffix(id, "-cn") || len(cs) > 0 && strings.HasSuffix(cs[0], "-cn")
|
||||
}
|
||||
if strings.HasSuffix(strings.ToLower(p.ID), "-cn") {
|
||||
return true
|
||||
}
|
||||
if len(cs) == 0 || !catalog.PricedInYuan(cs[0]) {
|
||||
return false
|
||||
}
|
||||
return h == "" || sameSite(h, catalog.APIHost(cs[0]))
|
||||
}
|
||||
|
||||
// sameSite is whether two hosts share their last two labels
|
||||
// (api.deepseek.com and platform.deepseek.com).
|
||||
func sameSite(a, b string) bool {
|
||||
site := func(h string) string {
|
||||
parts := strings.Split(h, ".")
|
||||
if len(parts) > 2 {
|
||||
parts = parts[len(parts)-2:]
|
||||
}
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
return a != "" && b != "" && site(a) == site(b)
|
||||
}
|
||||
|
||||
// YuanPriced are the ids of the providers that PricesInYuan, for the
|
||||
// window to show their costs in yuan; nil when none do.
|
||||
func YuanPriced() []string {
|
||||
var out []string
|
||||
for _, p := range sharedAll() {
|
||||
if p.PricesInYuan() {
|
||||
out = append(out, p.ID)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// YuanPricedSet is YuanPriced as a set, for a table of rows looked up one by
|
||||
// one (the TUI's and the CLI's).
|
||||
func YuanPricedSet() map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, id := range YuanPriced() {
|
||||
out[id] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// Settings' currency "By provider" shows a provider's costs in yuan when
|
||||
// it sells in yuan (onkashiko on X: DeepSeek, Kimi CN, Zhipu, StepFun CN in
|
||||
// CNY, the rest in USD). A twin abroad sharing a yuan seller's catalog
|
||||
// (Z.ai's zhipuai, Kimi's moonshotai), or a relay made from a yuan preset
|
||||
// at another site, stays in dollars.
|
||||
func TestPricesInYuan(t *testing.T) {
|
||||
// models.dev's own names and API URLs for these ids, as of 2026-11-13,
|
||||
// in a cache of this test's own
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
b, err := os.ReadFile(filepath.Join("..", "catalog", "testdata", "models.dev-yuan-2026-11-13.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(catalog.CachePath(), b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
p Provider
|
||||
want bool
|
||||
}{
|
||||
{"deepseek", Provider{ID: "deepseek", Preset: "deepseek", Chat: "https://api.deepseek.com/v1"}, true},
|
||||
{"deepseek, endpoints left to the preset", Provider{ID: "ds", Preset: "deepseek"}, true},
|
||||
{"a relay made from deepseek's preset", Provider{ID: "deepseek", Preset: "deepseek", Chat: "https://relay.example/v1"}, false},
|
||||
{"zhipu", Provider{ID: "zhipu", Preset: "zhipu", Chat: "https://open.bigmodel.cn/api/paas/v4", Catalog: "zhipuai"}, true},
|
||||
{"z.ai shares zhipu's catalog", Provider{ID: "zai", Preset: "zai", Chat: "https://api.z.ai/api/paas/v4", Catalog: "zhipuai"}, false},
|
||||
{"kimi china", Provider{ID: "moonshot-cn", Preset: "moonshot-cn", Chat: "https://api.moonshot.cn/v1", Catalog: "moonshotai"}, true},
|
||||
{"kimi", Provider{ID: "moonshot", Preset: "moonshot", Chat: "https://api.moonshot.ai/v1", Catalog: "moonshotai"}, false},
|
||||
{"kimi code china", Provider{ID: "kimi-code-cn", Preset: "kimi-code-cn", Chat: "https://api.kimi.com/coding/v1", Catalog: "kimi-code-plan-cn"}, true},
|
||||
{"stepfun china", Provider{ID: "stepfun-cn", Preset: "stepfun-cn", Chat: "https://api.stepfun.com/step_plan/v1"}, true},
|
||||
{"stepfun", Provider{ID: "stepfun", Preset: "stepfun", Chat: "https://api.stepfun.ai/step_plan/v1"}, false},
|
||||
{"minimax china", Provider{ID: "minimax-cn", Preset: "minimax-cn", Chat: "https://api.minimaxi.com/v1", Catalog: "minimax"}, true},
|
||||
{"xiaomi's china plan", Provider{ID: "xiaomi", Preset: "xiaomi", Chat: "https://token-plan-cn.xiaomimimo.com/v1", Catalog: "xiaomi-token-plan-cn, xiaomi"}, true},
|
||||
{"xiaomi's singapore plan", Provider{ID: "xiaomi", Preset: "xiaomi", Chat: "https://token-plan-sgp.xiaomimimo.com/v1", Catalog: "xiaomi-token-plan-sgp, xiaomi"}, false},
|
||||
{"volcengine", Provider{ID: "ark", Preset: "volcengine", Chat: "https://ark.cn-beijing.volces.com/api/v3"}, true},
|
||||
{"anthropic", Provider{ID: "anthropic", Preset: "anthropic", Anthropic: "https://api.anthropic.com"}, false},
|
||||
{"openai", Provider{ID: "openai", Preset: "openai", Chat: "https://api.openai.com/v1", Catalog: "openai"}, false},
|
||||
{"openrouter", Provider{ID: "openrouter", Preset: "openrouter", Chat: "https://openrouter.ai/api/v1", Catalog: "openrouter"}, false},
|
||||
{"a .cn relay of its own", Provider{ID: "mine", Chat: "https://api.example.cn/v1"}, true},
|
||||
{"a .cn host with a port", Provider{ID: "mine", Chat: "http://llm.example.cn:8080/v1"}, true},
|
||||
{"its own, at deepseek with deepseek's catalog", Provider{ID: "mine", Chat: "https://api.deepseek.com/v1", Catalog: "deepseek"}, true},
|
||||
{"its own relay given deepseek's catalog", Provider{ID: "mine", Chat: "https://relay.example/v1", Catalog: "deepseek"}, false},
|
||||
{"a plugin's china id", Provider{ID: "qoder-cn"}, true},
|
||||
{"its own, nothing said", Provider{ID: "mine", Chat: "https://relay.example/v1"}, false},
|
||||
} {
|
||||
if got := c.p.PricesInYuan(); got != c.want {
|
||||
t.Errorf("%s: PricesInYuan() = %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package settings
|
||||
|
||||
import "testing"
|
||||
|
||||
// "By provider" (onkashiko on X): a provider's costs in what it sells in,
|
||||
// a sum of several in the currency picked for totals.
|
||||
func TestCostInByProvider(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
s Settings
|
||||
yuan, dollars, totals string
|
||||
}{
|
||||
{Settings{Currency: "usd"}, "usd", "usd", "usd"},
|
||||
{Settings{Currency: ""}, "usd", "usd", "usd"},
|
||||
{Settings{Currency: "cny"}, "cny", "cny", "cny"},
|
||||
{Settings{Currency: "cny", TotalCurrency: "usd"}, "cny", "cny", "cny"}, // only By provider reads it
|
||||
{Settings{Currency: CurrencyByProvider}, "cny", "usd", "usd"},
|
||||
{Settings{Currency: CurrencyByProvider, TotalCurrency: "cny"}, "cny", "usd", "cny"},
|
||||
{Settings{Currency: CurrencyByProvider, TotalCurrency: "usd"}, "cny", "usd", "usd"},
|
||||
} {
|
||||
if got := c.s.CostIn(true); got != c.yuan {
|
||||
t.Errorf("currency %q, totals %q: CostIn(yuan) = %s, want %s", c.s.Currency, c.s.TotalCurrency, got, c.yuan)
|
||||
}
|
||||
if got := c.s.CostIn(false); got != c.dollars {
|
||||
t.Errorf("currency %q, totals %q: CostIn(dollars) = %s, want %s", c.s.Currency, c.s.TotalCurrency, got, c.dollars)
|
||||
}
|
||||
if got := c.s.TotalCostIn(); got != c.totals {
|
||||
t.Errorf("currency %q, totals %q: TotalCostIn() = %s, want %s", c.s.Currency, c.s.TotalCurrency, got, c.totals)
|
||||
}
|
||||
}
|
||||
if err := Save(Settings{Currency: CurrencyByProvider, TotalCurrency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := Load(); s.Currency != CurrencyByProvider || s.TotalCurrency != "cny" {
|
||||
t.Fatalf("saved: currency %q, totals %q", s.Currency, s.TotalCurrency)
|
||||
}
|
||||
if Save(Settings{Currency: CurrencyByProvider, TotalCurrency: "provider"}) == nil {
|
||||
t.Fatal("totals by provider accepted: a sum of several has no one provider")
|
||||
}
|
||||
if Save(Settings{TotalCurrency: "eur"}) == nil {
|
||||
t.Fatal("bad total currency accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// The menu bar's currency is set apart from the totals' (onkashiko on X):
|
||||
// unset it follows them, set it is its own, and it stays on this computer.
|
||||
func TestTrayCostIn(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
s Settings
|
||||
want string
|
||||
}{
|
||||
{Settings{}, "usd"},
|
||||
{Settings{Currency: "cny"}, "cny"},
|
||||
{Settings{Currency: CurrencyByProvider, TotalCurrency: "cny"}, "cny"},
|
||||
{Settings{Currency: "cny", TrayCurrency: "usd"}, "usd"},
|
||||
{Settings{Currency: "usd", TrayCurrency: "cny"}, "cny"},
|
||||
{Settings{Currency: CurrencyByProvider, TotalCurrency: "usd", TrayCurrency: "cny"}, "cny"},
|
||||
} {
|
||||
if got := c.s.TrayCostIn(); got != c.want {
|
||||
t.Errorf("currency %q, totals %q, menu bar %q: TrayCostIn() = %s, want %s", c.s.Currency, c.s.TotalCurrency, c.s.TrayCurrency, got, c.want)
|
||||
}
|
||||
}
|
||||
if Save(Settings{TrayCurrency: "eur"}) == nil {
|
||||
t.Fatal("bad menu bar currency accepted")
|
||||
}
|
||||
if Save(Settings{TrayCurrency: "provider"}) == nil {
|
||||
t.Fatal("menu bar by provider accepted: its total has no one provider")
|
||||
}
|
||||
from := Settings{TrayCurrency: "usd"}
|
||||
from.KeepOwn(Settings{TrayCurrency: "cny"})
|
||||
if from.TrayCurrency != "cny" {
|
||||
t.Fatalf("a synced file's menu bar currency replaced this computer's: %q", from.TrayCurrency)
|
||||
}
|
||||
}
|
||||
@@ -102,8 +102,21 @@ type Settings struct {
|
||||
// TUI's and the CLI's — is shown converted to: usd (its native
|
||||
// currency, list prices being in dollars) or cny, at a live exchange
|
||||
// rate (see internal/fx). A vendor's own balance, already in its own
|
||||
// currency (a Chinese relay's ¥), is never touched by this.
|
||||
// currency (a Chinese relay's ¥), is never touched by this. "provider"
|
||||
// shows each provider's costs in the currency it prices in (yuan for
|
||||
// one that sells in China's, provider.PricesInYuan; dollars for the
|
||||
// rest), and a sum of several providers' in TotalCurrency (CostIn,
|
||||
// TotalCostIn; onkashiko on X).
|
||||
Currency string `json:"currency,omitempty"`
|
||||
// TotalCurrency is what a sum of several providers' costs — a total, an
|
||||
// agent's, a chart's — is shown in when Currency is "provider": usd or
|
||||
// cny, "" being usd. It means nothing with another Currency.
|
||||
TotalCurrency string `json:"totalCurrency,omitempty"`
|
||||
// TrayCurrency is what the menu bar's and the tray tooltip's cost of
|
||||
// magpie's totals is in: usd or cny, "" following the totals'
|
||||
// (TrayCostIn; onkashiko on X, who wanted the bar and the totals set
|
||||
// apart). Every sum is still made in dollars and changed once.
|
||||
TrayCurrency string `json:"trayCurrency,omitempty"`
|
||||
// ChineseUnits shortens a large count in 万 and 亿 when magpie speaks
|
||||
// Chinese (8000 万 rather than 80M); otherwise it is in K, M and B, as
|
||||
// prices per million tokens and context windows (200K, 1M) are, in
|
||||
@@ -1491,12 +1504,53 @@ func (s Settings) ClassifyWait() time.Duration {
|
||||
return time.Duration(min(n, ClassifyTimeoutMost)) * time.Second
|
||||
}
|
||||
|
||||
// CurrencyByProvider is Currency's choice of each provider's own currency.
|
||||
const CurrencyByProvider = "provider"
|
||||
|
||||
// CostIn is the currency, usd or cny, a cost of one provider's calls is
|
||||
// shown in: with Currency "provider", the one it prices in (yuan: whether
|
||||
// it sells in China's yuan, provider.PricesInYuan), else Currency.
|
||||
func (s Settings) CostIn(yuan bool) string {
|
||||
if s.Currency == CurrencyByProvider {
|
||||
if yuan {
|
||||
return "cny"
|
||||
}
|
||||
return "usd"
|
||||
}
|
||||
return s.TotalCostIn()
|
||||
}
|
||||
|
||||
// TotalCostIn is the currency, usd or cny, a sum of several providers'
|
||||
// costs is shown in: TotalCurrency with Currency "provider", else
|
||||
// Currency.
|
||||
func (s Settings) TotalCostIn() string {
|
||||
c := s.Currency
|
||||
if c == CurrencyByProvider {
|
||||
c = s.TotalCurrency
|
||||
}
|
||||
if c == "cny" {
|
||||
return "cny"
|
||||
}
|
||||
return "usd"
|
||||
}
|
||||
|
||||
// TrayCostIn is the currency, usd or cny, the menu bar's and the tray
|
||||
// tooltip's totals are shown in: TrayCurrency, else TotalCostIn.
|
||||
func (s Settings) TrayCostIn() string {
|
||||
if s.TrayCurrency == "usd" || s.TrayCurrency == "cny" {
|
||||
return s.TrayCurrency
|
||||
}
|
||||
return s.TotalCostIn()
|
||||
}
|
||||
|
||||
// Themes and Langs are the accepted values, in the order the UI offers them.
|
||||
var (
|
||||
Themes = []string{"system", "light", "dark"}
|
||||
Langs = []string{"system", "en", "zh", "zh-TW", "ja", "de"}
|
||||
Trays = []string{"panel", "window"}
|
||||
Currencies = []string{"usd", "cny"}
|
||||
Currencies = []string{"usd", "cny", CurrencyByProvider}
|
||||
// TotalCurrencies are TotalCurrency's values, "" being usd.
|
||||
TotalCurrencies = []string{"usd", "cny"}
|
||||
// Warmups are CodexWarmup's and ClaudeWarmup's values, off as "".
|
||||
Warmups = []string{"", "week", "all"}
|
||||
// TrayEvery are TrayUsageEvery's values, in minutes.
|
||||
@@ -1705,7 +1759,7 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay
|
||||
s.WindowAt = cur.WindowAt
|
||||
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird, s.TrayPace, s.TrayNoCost = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird, cur.TrayPace, cur.TrayNoCost
|
||||
s.TrayWindows, s.TrayNoNumber = cur.TrayWindows, cur.TrayNoNumber
|
||||
s.TrayWindows, s.TrayNoNumber, s.TrayCurrency = cur.TrayWindows, cur.TrayNoNumber, cur.TrayCurrency
|
||||
s.GatewayMode = cur.GatewayMode
|
||||
s.NoWSLAgents = cur.NoWSLAgents
|
||||
s.QuotaReads = cur.QuotaReads
|
||||
@@ -2477,6 +2531,12 @@ func saveOwn(s Settings, recording, reads bool) error {
|
||||
if !slices.Contains(Currencies, s.Currency) {
|
||||
return fmt.Errorf("currency must be one of %v, not %q", Currencies, s.Currency)
|
||||
}
|
||||
if s.TotalCurrency != "" && !slices.Contains(TotalCurrencies, s.TotalCurrency) {
|
||||
return fmt.Errorf("total currency must be usd or cny, not %q", s.TotalCurrency)
|
||||
}
|
||||
if s.TrayCurrency != "" && !slices.Contains(TotalCurrencies, s.TrayCurrency) {
|
||||
return fmt.Errorf("menu bar currency must be usd or cny, not %q", s.TrayCurrency)
|
||||
}
|
||||
if !slices.Contains(Warmups, s.CodexWarmup) {
|
||||
return fmt.Errorf("codex warm-up must be off, week or all, not %q", s.CodexWarmup)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ var Keys = []string{
|
||||
// the menu bar's allowance cards
|
||||
"trayUsages", "trayUsage", "trayUsageEvery", "trayNoLogos", "trayNoBird", "trayNoNumber", "trayPace", "trayNoCost", "trayWindows",
|
||||
// usage and alerts
|
||||
"currency", "chineseUnits", "dayStart", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert",
|
||||
"currency", "totalCurrency", "trayCurrency", "chineseUnits", "dayStart", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert",
|
||||
// network
|
||||
"proxy", "pluginProxy", "updateProxy", "updateSource",
|
||||
// privacy
|
||||
@@ -63,6 +63,8 @@ var Choices = map[string][]string{
|
||||
"lang": settings.Langs,
|
||||
"tray": settings.Trays,
|
||||
"currency": settings.Currencies,
|
||||
"totalCurrency": settings.TotalCurrencies,
|
||||
"trayCurrency": settings.TotalCurrencies,
|
||||
"codexWarmup": {"off", "week", "all"},
|
||||
"claudeWarmup": {"off", "week", "all"},
|
||||
"trayUsageEvery": ints(settings.TrayEvery),
|
||||
|
||||
+29
-14
@@ -1201,39 +1201,54 @@ func fmtTokens(n int) string {
|
||||
return fmt.Sprint(n)
|
||||
}
|
||||
|
||||
// costCurrency is Settings' currency choice and, for cny, the CNY-per-USD
|
||||
// rate to show costs at (internal/fx), refreshed at most once a second so
|
||||
// a page redrawn on every keypress doesn't reread the settings file or
|
||||
// touch the rate's own cache for each row fmtCost renders.
|
||||
// costCurrency is Settings' currency choice and the CNY-per-USD rate to
|
||||
// show costs at when one is in yuan (internal/fx), with, for the choice
|
||||
// "provider", the providers that sell in yuan, refreshed at most once a
|
||||
// second so a page redrawn on every keypress doesn't reread the settings
|
||||
// file or touch the rate's own cache for each row fmtCost renders.
|
||||
var (
|
||||
costMu sync.Mutex
|
||||
costAt time.Time
|
||||
costCncy string
|
||||
costSet settings.Settings
|
||||
costRateVal float64
|
||||
costYuan map[string]bool
|
||||
)
|
||||
|
||||
func costCurrency() (string, float64) {
|
||||
func costCurrency() (settings.Settings, float64, map[string]bool) {
|
||||
costMu.Lock()
|
||||
defer costMu.Unlock()
|
||||
if time.Since(costAt) < time.Second {
|
||||
return costCncy, costRateVal
|
||||
return costSet, costRateVal, costYuan
|
||||
}
|
||||
costCncy = settings.Load().Currency
|
||||
costRateVal = 0
|
||||
if costCncy == "cny" {
|
||||
costSet = settings.Load()
|
||||
costRateVal, costYuan = 0, nil
|
||||
if costSet.Currency == settings.CurrencyByProvider {
|
||||
costYuan = provider.YuanPricedSet()
|
||||
}
|
||||
if costSet.Currency != "usd" && costSet.Currency != "" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
costRateVal = fx.Get(ctx).CNYPerUSD
|
||||
cancel()
|
||||
}
|
||||
costAt = time.Now()
|
||||
return costCncy, costRateVal
|
||||
return costSet, costRateVal, costYuan
|
||||
}
|
||||
|
||||
func fmtCost(t usage.Totals) string {
|
||||
// fmtCost is a sum of several providers' costs, in the currency Settings
|
||||
// shows a total in.
|
||||
func fmtCost(t usage.Totals) string { return fmtCostOf(t, "") }
|
||||
|
||||
// fmtCostOf is one provider's cost, in the currency Settings shows it in
|
||||
// (its own, with the choice "provider"); "" is a sum of several.
|
||||
func fmtCostOf(t usage.Totals, providerID string) string {
|
||||
if t.Cost == 0 && t.Unpriced > 0 {
|
||||
return "no price"
|
||||
}
|
||||
cncy, rate := costCurrency()
|
||||
st, rate, yuan := costCurrency()
|
||||
cncy := st.TotalCostIn()
|
||||
if providerID != "" && providerID != usage.UnknownProvider {
|
||||
cncy = st.CostIn(yuan[providerID])
|
||||
}
|
||||
s := usage.FormatCost(t.Cost, cncy, rate)
|
||||
if t.Unpriced > 0 {
|
||||
s += "+"
|
||||
@@ -1347,7 +1362,7 @@ func (m model) usageBlock(b *strings.Builder, s usage.Summary, room int, names m
|
||||
break
|
||||
}
|
||||
share := fmt.Sprintf("%3.0f%%", 100*float64(g.Tokens())/float64(max(1, s.Tokens())))
|
||||
b.WriteString(pad + " " + sText.Render(padRight(name(g), w)) + " " + sMuted.Render(share) + " " + sText.Render(padRight(fmtTokens(g.Tokens()), 7)) + " " + sFaint.Render(padRight(fmt.Sprintf("%d call%s", g.Calls, plural(g.Calls)), 10)) + " " + sOK.Render(fmtCost(g.Totals)) + sMuted.Render(credits(g.Totals)) + "\n")
|
||||
b.WriteString(pad + " " + sText.Render(padRight(name(g), w)) + " " + sMuted.Render(share) + " " + sText.Render(padRight(fmtTokens(g.Tokens()), 7)) + " " + sFaint.Render(padRight(fmt.Sprintf("%d call%s", g.Calls, plural(g.Calls)), 10)) + " " + sOK.Render(fmtCostOf(g.Totals, g.Provider)) + sMuted.Render(credits(g.Totals)) + "\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
@@ -111,6 +111,36 @@ func TestFmtCostShowsChosenCurrency(t *testing.T) {
|
||||
if got := fmtCost(usage.Totals{Cost: 0, Unpriced: 1}); got != "no price" {
|
||||
t.Fatalf("unpriced: %q", got)
|
||||
}
|
||||
|
||||
// By provider (onkashiko on X): DeepSeek's row in yuan, OpenAI's in
|
||||
// dollars, a total in the currency picked for totals
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "deepseek", Name: "DeepSeek", Preset: "deepseek", Key: "k", Chat: "https://api.deepseek.com/v1"},
|
||||
{ID: "openai", Name: "OpenAI", Preset: "openai", Key: "k", Chat: "https://api.openai.com/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Currency: settings.CurrencyByProvider, TotalCurrency: "usd"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
costAt = time.Time{}
|
||||
for _, c := range []struct{ id, want string }{{"deepseek", "≈¥8.86"}, {"openai", "≈$1.23"}, {"", "≈$1.23"}, {usage.UnknownProvider, "≈$1.23"}} {
|
||||
if got := fmtCostOf(usage.Totals{Cost: 1.23}, c.id); got != c.want {
|
||||
t.Errorf("by provider, %q: %q, want %q", c.id, got, c.want)
|
||||
}
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Currency: settings.CurrencyByProvider, TotalCurrency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
costAt = time.Time{}
|
||||
if got := fmtCost(usage.Totals{Cost: 1.23}); got != "≈¥8.86" {
|
||||
t.Errorf("by provider, the total in cny: %q", got)
|
||||
}
|
||||
if got := fmtCostOf(usage.Totals{Cost: 1.23}, "openai"); got != "≈$1.23" {
|
||||
t.Errorf("by provider, openai with totals in cny: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlimitedQuotaCell(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user