diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 11471e46e..1cb56e81b 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -94,6 +94,11 @@ type Price struct { CacheWrite float64 `json:"cache_write"` } +// Times is the price at r times each of its parts. +func (p Price) Times(r float64) Price { + return Price{Input: p.Input * r, Output: p.Output * r, CacheRead: p.CacheRead * r, CacheWrite: p.CacheWrite * r} +} + // Cost of a call at this price. Reasoning tokens are billed as output by // every vendor, and are already inside the output count. func (p Price) Cost(input, output, cacheRead, cacheWrite int) float64 { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index e9d4faa32..f58c430bf 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -819,6 +819,17 @@ body.window .field.solo { grid-column: auto; } /* the table scrolls sideways in its own box, never the page */ .led-wrap { max-width: 100%; overflow-x: auto; overscroll-behavior-x: contain; background: var(--card); border: 1px solid var(--line); border-radius: 12px; } .led-wrap.none { overflow: visible; } +/* its own scrollbar is at the table's foot, fifty rows down and out of + sight (#799): this one stands in for it, held at the bottom of the window + while the table is in it, and drawn always, the Mac's overlay one too */ +.led-wrap::-webkit-scrollbar { height: 0; } +.led-hscroll { position: sticky; bottom: 0; z-index: 2; overflow-x: auto; overflow-y: hidden; height: 12px; margin-top: 2px; background: var(--bg); } +.led-hscroll[hidden] { display: none; } +.led-hscroll > div { height: 1px; } +.led-hscroll::-webkit-scrollbar { height: 10px; background: transparent; } +.led-hscroll::-webkit-scrollbar-thumb { background: var(--faint); border: 2px solid transparent; border-radius: 10px; background-clip: padding-box; } +.led-hscroll::-webkit-scrollbar-thumb:hover { background-color: var(--muted); } +.led-hscroll::-webkit-scrollbar-button, .led-hscroll::-webkit-scrollbar-corner { display: none; } .led-none { padding: 18px 16px; color: var(--muted); text-align: center; line-height: 1.5; } .led-sk { padding: 11px 14px; } .led-sk + .led-sk { border-top: 1px solid var(--line-2); } @@ -875,6 +886,7 @@ body.window .field.solo { grid-column: auto; } .led-dl dd.bad { color: var(--red); font-weight: 600; } .led-dl dd.said { color: var(--fg); white-space: pre-wrap; } .led-dl dd.muted { color: var(--muted); } +.led-dl .led-route-link { padding: 0; font: inherit; text-decoration: underline; text-decoration-style: dotted; text-underline-offset: 3px; } /* what was said in a request, in its details */ .led-cx { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--line-2); } .cx-sec + .cx-sec { margin-top: 10px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9d2cc30d5..680a81044 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5901,8 +5901,35 @@ function concurrencyField(p) { box.oninput = () => { draft.concurrency = box.value; }; return field(t("Concurrency"), box, plugin ? t("Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit", { n: plugin }) : t("Over it, requests queue and go out in order; 0 or empty is no limit")); } +// priceRateField: what the provider charges against the official price +// (ITea312, #819), as a relay bills 0.8× or 1.5× of it: the Usage page's +// costs are its list price, else its maker's, times this. Empty is the +// price as listed; steps of 0.001. +function priceRateField() { + const box = input(draft.priceRate ?? "", t("1, the official price"), "number"); + box.classList.add("price-rate"); + box.min = "0"; + box.max = "1000"; + box.step = "0.001"; + box.inputMode = "decimal"; + box.oninput = () => { draft.priceRate = box.value; }; + return field(t("Price rate"), box, t("Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set")); +} +// priceRateOfDraft is the draft's rate as it is saved — null for none, +// else the number — or undefined when what is typed isn't one. +function priceRateOfDraft() { + const v = String(draft.priceRate ?? "").trim(); + if (!v) return null; + const n = Number(v); + if (!/^\d*\.?\d+$|^\d+\.$/.test(v) || !(n >= 0 && n <= 1000) || Math.abs(n * 1000 - Math.round(n * 1000)) > 1e-6) return undefined; + return n; +} +function priceRateError(ed) { + ed.querySelector("input.price-rate")?.focus({ preventScroll: true }); + return editorError(t("Price rate: a number from 0 to 1000, at most three decimals"), "warn"); +} function concurrencyDraft(p) { - return { concurrency: p?.maxConcurrency == null ? "" : String(p.maxConcurrency) }; + return { concurrency: p?.maxConcurrency == null ? "" : String(p.maxConcurrency), priceRate: p?.priceRate ? String(p.priceRate) : "" }; } // concurrencyOfDraft is the draft's limit as it is saved — null for none // set, else the number — or undefined when what is typed isn't one. @@ -6655,6 +6682,7 @@ function drawEditor(p, presetID) { if (perAccount) proxies.append(perAccount); ed.append(...field(t("Proxy"), proxies)); ed.append(...concurrencyField(p)); + ed.append(...priceRateField()); // a plugin's provider is reached inside magpie: its plugin:// URLs go // nowhere to show or test const urls = [p.chat, p.responses, p.anthropic].filter(Boolean); @@ -6683,7 +6711,9 @@ function drawEditor(p, presetID) { } const maxConcurrency = concurrencyOfDraft(); if (maxConcurrency === undefined) return concurrencyError(ed); - saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: chosenIds(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, proxy, accountProxies: own.map, maxConcurrency, modelPrefs: modelPrefsOfDraft(), ...routingOfDraft(p) }, t("{name} saved", { name: p.name })); }; + const priceRate = priceRateOfDraft(); + if (priceRate === undefined) return priceRateError(ed); + saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: chosenIds(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, proxy, accountProxies: own.map, maxConcurrency, priceRate, modelPrefs: modelPrefsOfDraft(), ...routingOfDraft(p) }, t("{name} saved", { name: p.name })); }; bar.append(cancel, saveBtn); ed.append(bar); return ed; @@ -6748,6 +6778,7 @@ function drawEditor(p, presetID) { } ed.append(...field(t("Proxy"), proxyPicker())); ed.append(...concurrencyField(p)); + ed.append(...priceRateField()); // a relay in front of Anthropic's or OpenAI's API searches the web as // they do, which magpie can't tell from its host (#359): a client's web @@ -7013,6 +7044,8 @@ function drawEditor(p, presetID) { if (body.proxy === null) { ed.querySelector(".proxy-url")?.focus(); return editorError(t("Proxy: type its address, like http://127.0.0.1:7890"), "warn"); } body.maxConcurrency = concurrencyOfDraft(); if (body.maxConcurrency === undefined) return concurrencyError(ed); + body.priceRate = priceRateOfDraft(); + if (body.priceRate === undefined) return priceRateError(ed); if (draft.balanceToken) body.balanceToken = draft.balanceToken; else if (draft.clearBalanceToken) body.clearBalanceToken = true; if (team) { @@ -12327,6 +12360,7 @@ function renderLedgerLoading() { const wrap = $("#ledWrap"); wrap.classList.remove("none"); wrap.replaceChildren(); + $("#ledHScroll").hidden = true; for (let i = 0; i < 5; i++) { const r = el("div", "led-sk"); r.append(el("span", "skeleton sk-line")); @@ -12376,6 +12410,20 @@ function ledDetail(r, cols) { add("Status", r.status ? String(r.status) : "—", "bad"); add("Error type", r.err_type, "bad"); add(r.source === "log" ? "Error" : "Upstream said", r.err, "said"); + } else { + // how it went, here as well as in the row's last column, which a narrow + // window leaves out of sight (#799) + add("Status", r.status ? String(r.status) : r.source === "log" ? t("Succeeded") : ""); + } + if (Number.isFinite(r.ms) && r.ms > 0) add("Duration", (r.source === "log" ? "≈" : "") + ledTook(r.ms)); + // the way it was routed: the row's time links there too, which reads as + // a time rather than a link (#799) + if (r.route_id) { + const go = el("button", "text led-route-link", t("View routing")); + go.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; + const dd = el("dd"); + dd.append(go); + dl.append(el("dt", "", t("Routing")), dd); } if (r.computerName) add("Computer", r.computerName); add("Request ID", r.rid); @@ -12869,8 +12917,20 @@ function drawLedTrend() { loadLedger().catch((e) => status(e.message, "err")); }, false); } +// the table's scrollbar, kept in view at the window's foot (#799): as wide +// as the table can go sideways, and moving it as the table moves it +function ledHScroll() { + const wrap = $("#ledWrap"), bar = $("#ledHScroll"); + const over = !!wrap.querySelector("table") && wrap.scrollWidth > wrap.clientWidth + 1; + bar.hidden = !over; + if (!over) return; + bar.firstElementChild.style.width = wrap.scrollWidth - wrap.clientWidth + bar.clientWidth + "px"; + bar.scrollLeft = wrap.scrollLeft; +} +$("#ledWrap").addEventListener("scroll", () => { const bar = $("#ledHScroll"); if (bar.scrollLeft !== $("#ledWrap").scrollLeft) bar.scrollLeft = $("#ledWrap").scrollLeft; }, { passive: true }); +$("#ledHScroll").addEventListener("scroll", () => { const wrap = $("#ledWrap"); if (wrap.scrollLeft !== $("#ledHScroll").scrollLeft) wrap.scrollLeft = $("#ledHScroll").scrollLeft; }, { passive: true }); // a window that changes size redraws the chart at its new width -new ResizeObserver(() => $("#ledWrap").style.setProperty("--ledw", $("#ledWrap").clientWidth + "px")).observe($("#ledWrap")); +new ResizeObserver(() => { $("#ledWrap").style.setProperty("--ledw", $("#ledWrap").clientWidth + "px"); ledHScroll(); }).observe($("#ledWrap")); new ResizeObserver(() => { if (!ledger || usageTab !== "requests" || view !== "usage" || $("#ledDash").hidden) return; drawLedColumns($("#ledChart"), ledger, ledSplit, ledMetric, false); @@ -12972,6 +13032,7 @@ function renderLedger() { const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledFailed || ledQuery.trim(); const none = { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[period]; wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none))); + ledHScroll(); pager.hidden = true; $("#ledNote").textContent = ""; return; @@ -13078,6 +13139,7 @@ function renderLedger() { } wrap.replaceChildren(table); wrap.style.setProperty("--ledw", wrap.clientWidth + "px"); + ledHScroll(); // a page at a time: the newest first pager.hidden = l.total <= LED_PAGE; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5bd632c97..990e0e638 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1131,6 +1131,10 @@ const I18N = { "Proxy of {user}: type its address, like http://127.0.0.1:7890": "{user} 的代理:请填写地址,例如 http://127.0.0.1:7890", "Concurrency": "并发上限", "No limit": "不限制", + "Price rate": "价格倍率", + "1, the official price": "1,即官方价格", + "Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "费用按官方价格乘以此倍率计算,同中转站计费方式,例如 0.8 或 1.5;你为某个模型单独设置的价格保持不变", + "Price rate: a number from 0 to 1000, at most three decimals": "价格倍率:0 到 1000 之间的数字,最多三位小数", "{n}, as its plugin says": "{n}(插件的默认值)", "Over it, requests queue and go out in order; 0 or empty is no limit": "超出时排队,按顺序发出;0 或留空为不限制", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "超出时排队,按顺序发出;留空则用插件的默认值 {n},0 为不限制", @@ -4127,6 +4131,10 @@ const I18N = { "Proxy of {user}: type its address, like http://127.0.0.1:7890": "{user} のプロキシ:アドレスを入力してください(例:http://127.0.0.1:7890)", "Concurrency": "同時実行数", "No limit": "上限なし", + "Price rate": "価格倍率", + "1, the official price": "1(公式価格)", + "Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "費用は公式価格にこの倍率を掛けて計算します(中継サービスの課金方式、例: 0.8 や 1.5)。モデルごとに設定した価格はそのままです", + "Price rate: a number from 0 to 1000, at most three decimals": "価格倍率: 0〜1000 の数値、小数点以下 3 桁まで", "{n}, as its plugin says": "{n}(プラグインの既定値)", "Over it, requests queue and go out in order; 0 or empty is no limit": "超えたリクエストはキューに入り、順番に送られます。0 または空欄で上限なし", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "超えたリクエストはキューに入り、順番に送られます。空欄ならプラグインの {n}、0 で上限なし", @@ -7118,6 +7126,10 @@ const I18N = { "Proxy of {user}: type its address, like http://127.0.0.1:7890": "Proxy von {user}: Adresse eingeben, z. B. http://127.0.0.1:7890", "Concurrency": "Parallelität", "No limit": "Kein Limit", + "Price rate": "Preisfaktor", + "1, the official price": "1, der offizielle Preis", + "Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "Kosten werden zum offiziellen Preis mal diesem Faktor gezählt, wie ein Relay abrechnet, etwa 0.8 oder 1.5; ein für ein Modell gesetzter Preis bleibt", + "Price rate: a number from 0 to 1000, at most three decimals": "Preisfaktor: eine Zahl von 0 bis 1000, höchstens drei Nachkommastellen", "{n}, as its plugin says": "{n}, laut Erweiterung", "Over it, requests queue and go out in order; 0 or empty is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; 0 oder leer heißt kein Limit", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; leer übernimmt den Wert {n} der Erweiterung, 0 heißt kein Limit", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 072b017ac..1ab71206f 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -179,6 +179,7 @@

+

diff --git a/internal/gui/price_rate_test.go b/internal/gui/price_rate_test.go new file mode 100644 index 000000000..c616d0350 --- /dev/null +++ b/internal/gui/price_rate_test.go @@ -0,0 +1,31 @@ +package gui + +import ( + "encoding/json" + "testing" +) + +// A save's priceRate (#819): left out keeps the rate, null clears it, a +// number in range is taken and anything else is refused. +func TestPriceRateOf(t *testing.T) { + for _, c := range []struct { + raw string + r float64 + keep bool + bad bool + }{ + {"", 0, true, false}, + {"null", 0, false, false}, + {"0.8", 0.8, false, false}, + {"1.5", 1.5, false, false}, + {"0.1234", 0, false, true}, + {"-1", 0, false, true}, + {"1001", 0, false, true}, + {`"x"`, 0, false, true}, + } { + r, keep, err := priceRateOf(json.RawMessage(c.raw)) + if (err != nil) != c.bad || r != c.r || keep != c.keep { + t.Errorf("%q: %v %v %v", c.raw, r, keep, err) + } + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 454c0a2b3..5dfb47645 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -121,13 +121,15 @@ type providerJSON struct { // how many requests each of its keys or accounts has out at once, the // rest queued: the user's (null: not set), and what its plugin says // when the user set none (provider.Concurrency) - MaxConcurrency *int `json:"maxConcurrency"` - PluginConcurrency int `json:"pluginConcurrency,omitempty"` - Models []modelJSON `json:"models"` // everything the vendor lists, exposed ones flagged - Exposed int `json:"exposed"` // how many reach the agents - Draws int `json:"draws,omitempty"` // how many of its models draw images (gateway.Drawers) - DrawIDs []string `json:"drawIds,omitempty"` // those models' ids, listed apart in its editor - Unlisted bool `json:"unlisted"` // its models serve only through routing groups + MaxConcurrency *int `json:"maxConcurrency"` + PluginConcurrency int `json:"pluginConcurrency,omitempty"` + // what it charges against the official price, 0 for that (#819) + PriceRate float64 `json:"priceRate,omitempty"` + Models []modelJSON `json:"models"` // everything the vendor lists, exposed ones flagged + Exposed int `json:"exposed"` // how many reach the agents + Draws int `json:"draws,omitempty"` // how many of its models draw images (gateway.Drawers) + DrawIDs []string `json:"drawIds,omitempty"` // those models' ids, listed apart in its editor + Unlisted bool `json:"unlisted"` // its models serve only through routing groups // Groups are the routing groups ("group/") each of its models is // in, by model id: what an unlisted one is still used through, and the // editor names those in none @@ -365,7 +367,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, Headers: p.Headers, Searches: p.Searches, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.Models, Models: []modelJSON{}, Agents: []providerAgent{}, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, Unlisted: p.Unlisted, Off: p.Off, Contexts: p.Contexts, - MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), + MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate, Outputs: provider.OutputsOf(p.ID), } if out.Fallback == nil { @@ -707,7 +709,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // accounts has out at once: a number (0 none), null for what // its plugin says or none; a save that leaves it out keeps it MaxConcurrency json.RawMessage `json:"maxConcurrency"` - AccountOrder []string `json:"accountOrder"` + // PriceRate is what it charges against the official price + // (#819): a number, null or 0 for none; left out, it is kept + PriceRate json.RawMessage `json:"priceRate"` + AccountOrder []string `json:"accountOrder"` // New is set by the editor's Add: the provider is one more, never // one replacing the provider that has its id or name New bool `json:"new"` @@ -864,6 +869,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } in.MaxConcurrency = cc + rate, keepRate, err := priceRateOf(req.PriceRate) + if err != nil { + fail(rw, err) + return + } + in.PriceRate = rate var old *provider.Provider if req.New { // a second one of a preset, or a name already in use, is @@ -901,6 +912,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if keepCC && old != nil { in.MaxConcurrency = old.MaxConcurrency } + if keepRate && old != nil { + in.PriceRate = old.PriceRate + } // each account's own proxy likewise: {} clears them if in.AccountProxies == nil && old != nil { in.AccountProxies = old.AccountProxies @@ -1515,6 +1529,25 @@ func typed(p, in provider.Provider, proxy *string) provider.Provider { return p } +// priceRateOf is a save's priceRate: keep when the save left it out, 0 +// for null, else the rate. +func priceRateOf(raw json.RawMessage) (r float64, keep bool, err error) { + if len(raw) == 0 { + return 0, true, nil + } + var n *float64 + if err := json.Unmarshal(raw, &n); err != nil { + return 0, false, fmt.Errorf("a price rate is a number, like 0.8, not %s", raw) + } + if n == nil { + return 0, false, nil + } + if bad := provider.PriceRateOK(*n); bad != "" { + return 0, false, fmt.Errorf("%s, not %v", bad, *n) + } + return *n, false, nil +} + // concurrencyOf is a save's maxConcurrency: keep when the save left it // out, nil for null (the plugin's, or none), else the number, 0 for none. func concurrencyOf(raw json.RawMessage) (n *int, keep bool, err error) { diff --git a/internal/gui/tests/ledger-hscroll.test.cjs b/internal/gui/tests/ledger-hscroll.test.cjs new file mode 100644 index 000000000..206a85e01 --- /dev/null +++ b/internal/gui/tests/ledger-hscroll.test.cjs @@ -0,0 +1,121 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Usage page's Requests table is wider than a narrow window, and its own +// scrollbar is at its foot, fifty rows down (mintonight, #799): a scrollbar +// stands in for it at the bottom of the window while the table is in sight, +// moves the table sideways and follows it, and is gone when the table fits. +// A row's details say how it went and how long it took, and link to its +// routing, so neither needs the columns out of sight. English and Chinese; +// no backend, the API is faked. +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 reader = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); + +const ROWS = Array.from({ length: 40 }, (_, i) => ({ + route_id: 500 + i, t: new Date(now - (i + 1) * 60e3).toISOString(), agent: "trae", agentName: "Trae CN", icon: "generic", + provider: "deepseek", providerName: "DeepSeek Harness", req: "group/auto-deepseek-v4-1-flash", model: "deepseek-v4-1-flash", served: "deepseek-v4-1-flash", + in: 1200 + i, out: 80, ms: 2400, ttft_ms: 600, status: 200, rid: "req_" + i, ep: "/v1/chat/completions", cost: 0.001, priced: true, +})); + +function server(lang, asked) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data, status) => route.fulfill({ json: data, status }); + 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" }, fx: { rate: 7.2, at: new Date().toISOString() } }); + if (url.pathname === "/api/usage/requests") return json({ period: url.searchParams.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: ROWS.length, errors: 0, input: 1, output: 1, cost: 0.04, unpriced: 0, agents: [{ id: "trae", name: "Trae CN", icon: "generic" }] }); + if (url.pathname === "/api/gateway/route") { asked.push(url.searchParams.get("id")); return json({ error: "gone" }, 404); } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 40, errors: 0, input: 1, output: 1, reasoning: 0, unpriced: 0, cost: 0.04, bucket: "day", series: [], agents: [], models: [], path: "" }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + 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 L = { + en: { labels: ["Status", "Duration", "Routing"], values: ["200", "2.4 s", "View routing"] }, + zh: { labels: ["状态", "耗时", "路由"], values: ["200", "2.4 秒", "查看路由"] }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Requests table's scrollbar and a row's status", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh"]) { + const w = L[lang]; + await t.test(lang, async () => { + const errors = [], asked = []; + const ctx = await browser.newContext({ viewport: { width: 900, height: 640 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, asked)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + await p.locator("#usageTab .opt").nth(1).click(); + await p.locator("#ledWrap .led tbody tr").first().waitFor(); + await p.waitForTimeout(200); + + const wrap = p.locator("#ledWrap"), bar = p.locator("#ledHScroll"); + assert(await wrap.evaluate((e) => e.scrollWidth > e.clientWidth + 50), "the table is wider than the window"); + // the table's top rows are in sight, its foot is not, and the bar is + // at the bottom of the window, under the rows in sight + await reader.inView(p, p.locator(".led tbody tr.led-row").nth(2)); + const view = await p.locator("#view-usage").boundingBox(); + const wb = await wrap.boundingBox(); + assert(wb.y + wb.height > view.y + view.height + 100, "the table's foot is out of sight"); + assert(await bar.isVisible(), "no scrollbar in sight"); + const bb = await bar.boundingBox(); + assert(bb.y + bb.height <= view.y + view.height + 1 && bb.y + bb.height >= view.y + view.height - 20, "the bar is at the window's foot: " + JSON.stringify({ bb, view })); + assert(Math.abs(bb.width - wb.width) <= 2, "the bar is as wide as the table's box"); + // it draws a thumb: wider content than itself + assert(await bar.evaluate((e) => e.scrollWidth > e.clientWidth && e.offsetHeight > e.clientHeight), "the bar draws a scrollbar"); + + // dragged to the end, the table shows its last column, Status + await bar.evaluate((e) => { e.scrollLeft = e.scrollWidth; }); + await p.waitForTimeout(150); + assert.equal(await wrap.evaluate((e) => Math.round(e.scrollLeft)), await wrap.evaluate((e) => e.scrollWidth - e.clientWidth), "the table followed the bar"); + const st = await p.locator(".led tbody tr.led-row").nth(2).locator(".st").boundingBox(); + assert(st.x + st.width <= wb.x + wb.width + 1 && st.x >= wb.x, "Status is in sight"); + // the table scrolled itself (a trackpad's swipe): the bar follows + await wrap.evaluate((e) => { e.scrollLeft = 30; }); + await p.waitForTimeout(150); + assert.equal(await bar.evaluate((e) => Math.round(e.scrollLeft)), 30, "the bar followed the table"); + + // a row's details: how it went, how long, and its routing + await reader.click(p, p.locator(".led tbody tr.led-row").nth(2).locator("td").nth(2)); + const d = p.locator(".led tbody tr.led-detail"); + assert.deepEqual((await d.locator("dt").allTextContents()).slice(0, 3), w.labels); + assert.deepEqual((await d.locator("dd").allTextContents()).slice(0, 3), w.values); + // brought above the bar, which covers the window's last few pixels + await reader.inView(p, d.locator(".led-route-link")); + await p.mouse.wheel(0, 80); + await p.waitForTimeout(300); + await d.locator(".led-route-link").click(); + for (let i = 0; i < 40 && !asked.length; i++) await p.waitForTimeout(25); + assert.deepEqual(asked, ["502"], "the link asks for the row's route"); + assert.equal(await p.locator(".led tbody tr.led-detail").count(), 1, "the link didn't close the row"); + + // a window wide enough for the table has no bar + await p.setViewportSize({ width: 2200, height: 640 }); + await p.waitForTimeout(250); + assert(await wrap.evaluate((e) => e.scrollWidth <= e.clientWidth + 1), "the table fits"); + assert.equal(await bar.isVisible(), false, "a bar with nothing to scroll"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/gui/tests/provider-price-rate.test.cjs b/internal/gui/tests/provider-price-rate.test.cjs new file mode 100644 index 000000000..fc5155190 --- /dev/null +++ b/internal/gui/tests/provider-price-rate.test.cjs @@ -0,0 +1,125 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider's price rate (ITea312, #819): its editor has the field, empty +// for the official price; Save posts the number typed, null when it is +// empty, and refuses one out of range or with more than three decimals +// before anything is posted. A signed-in account opens on what it has. In +// English and Chinese. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", maxConcurrency: null, +}; +const codex = { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] }, + proxy: "", maxConcurrency: null, priceRate: 0.8, +}; + +function serve(lang, posts) { + const providers = { providers: [relay, codex], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().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:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + 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 words = { + en: { label: "Price rate", save: "Save", none: "1, the official price", bad: "Price rate: a number from 0 to 1000, at most three decimals" }, + zh: { label: "价格倍率", save: "保存" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + const open = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor input.price-rate").waitFor(); + await page.waitForTimeout(300); + return { page, errors, posts }; + }; + const box = (page) => page.locator(".editor input.price-rate"); + const save = async (page, posts) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + test(`${engine} ${lang}: a provider's price rate is typed and saved`, async (t) => { + const { page, errors, posts } = await open(t, "Relay"); + const zh = await page.evaluate(() => ({ + none: I18N.zh["1, the official price"], bad: I18N.zh["Price rate: a number from 0 to 1000, at most three decimals"], + hint: I18N.zh["Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set"], + label: I18N.zh["Price rate"], + })); + assert(zh.none && zh.bad && zh.hint && zh.label, "every string has its Chinese"); + if (lang === "zh") Object.assign(w, { none: zh.none, bad: zh.bad }); + assert.equal(await page.locator(".editor label", { hasText: w.label }).count(), 1); + assert.equal(await box(page).inputValue(), "", "none set"); + assert.equal(await box(page).getAttribute("placeholder"), w.none); + + for (const bad of ["0.1234", "1001", "-1"]) { + await box(page).fill(bad); + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + await page.locator(".editor .editor-error").waitFor(); + assert.equal(await page.locator(".editor .editor-error").textContent(), w.bad, bad); + assert.equal(posts.length, 0, `${bad} is not posted`); + } + + await box(page).fill("0.85"); + let saved = await save(page, posts); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "relay"); + assert.equal(saved.body.priceRate, 0.85); + + await page.locator(".row.provider", { hasText: "Relay" }).click(); + await box(page).fill(""); + saved = await save(page, posts); + assert(Object.hasOwn(saved.body, "priceRate"), "an empty field is saved as none, not left out"); + assert.equal(saved.body.priceRate, null); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: a signed-in account's rate opens as it is and is saved`, async (t) => { + const { page, errors, posts } = await open(t, "Codex"); + assert.equal(await box(page).inputValue(), "0.8"); + await box(page).fill("1.5"); + const saved = await save(page, posts); + assert.equal(saved.body.id, "codex"); + assert.equal(saved.body.priceRate, 1.5); + assert.deepEqual(saved.body.models, ["gpt-6"], "its picks go with it"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/usage-ledger-detail.test.cjs b/internal/gui/tests/usage-ledger-detail.test.cjs index adef71f3b..42c661a97 100644 --- a/internal/gui/tests/usage-ledger-detail.test.cjs +++ b/internal/gui/tests/usage-ledger-detail.test.cjs @@ -63,13 +63,13 @@ function server(lang, refreshed) { const L = { en: { statuses: ["429 · rate_limit_error", "200", "Succeeded", "rate_limit"], badge: "Local session", - labels: { fail: ["Status", "Error type", "Upstream said", "Request ID", "Endpoint", "Session ID"], ok: ["Request ID", "Endpoint", "Called for", "First token", "In magpie", "Vendor's first token"], log: ["Request ID", "Session ID", "Data source"], logFail: ["Status", "Error type", "Error", "Request ID", "Session ID", "Data source"] }, + labels: { fail: ["Status", "Error type", "Upstream said", "Duration", "Request ID", "Endpoint", "Session ID"], ok: ["Status", "Duration", "Request ID", "Endpoint", "Called for", "First token", "In magpie", "Vendor's first token"], log: ["Request ID", "Session ID", "Data source"], logFail: ["Status", "Error type", "Error", "Request ID", "Session ID", "Data source"] }, subagent: "Subagent", noStatus: "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.", }, zh: { statuses: ["429 · rate_limit_error", "200", "成功", "rate_limit"], badge: "本地会话", - labels: { fail: ["状态", "错误类型", "上游返回", "请求 ID", "终结点", "会话 ID"], ok: ["请求 ID", "终结点", "用途", "首响", "magpie 内耗时", "厂商首字等待"], log: ["请求 ID", "会话 ID", "数据来源"], logFail: ["状态", "错误类型", "错误", "请求 ID", "会话 ID", "数据来源"] }, + labels: { fail: ["状态", "错误类型", "上游返回", "耗时", "请求 ID", "终结点", "会话 ID"], ok: ["状态", "耗时", "请求 ID", "终结点", "用途", "首响", "magpie 内耗时", "厂商首字等待"], log: ["请求 ID", "会话 ID", "数据来源"], logFail: ["状态", "错误类型", "错误", "请求 ID", "会话 ID", "数据来源"] }, subagent: "子代理", noStatus: "读自 Agent 的会话文件;仅在本地元数据能够明确识别时显示账号,不推断供应商。", }, @@ -136,8 +136,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(v[0], "429"); assert.equal(v[1], "rate_limit_error"); assert.equal(v[2], "Relay: slow down, please"); - assert.equal(v[3], "req_011abc"); - assert.equal(v[4], "/v1/responses"); + assert.equal(v[4], "req_011abc"); + assert.equal(v[5], "/v1/responses"); assert.equal(await rows.nth(0).getAttribute("aria-expanded"), "true"); assert.equal(await top(), before, "the click moved the page"); // the details sit under their row, and no row is pushed out of the table @@ -151,9 +151,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await top(), before); await reader.click(p, rows.nth(1)); assert.deepEqual(await labels(), w.labels.ok); - assert.deepEqual((await values()).slice(0, 3), ["chatcmpl-77", "/v1/messages → /v1/chat/completions", w.subagent]); + // how it went and how long, which the row says only in its last columns (#799) + assert.deepEqual((await values()).slice(0, 2).map((v) => v.replace(/[^\d.]/g, "")), ["200", "2.4"]); + assert.deepEqual((await values()).slice(2, 5), ["chatcmpl-77", "/v1/messages → /v1/chat/completions", w.subagent]); // the first token split: magpie's own 40 ms, the vendor's 660 ms - assert.deepEqual((await values()).slice(4, 6).map((v) => v.match(/^\d+/)?.[0]), ["40", "660"]); + assert.deepEqual((await values()).slice(6, 8).map((v) => v.match(/^\d+/)?.[0]), ["40", "660"]); await reader.click(p, rows.nth(2)); assert.deepEqual(await p.locator(".led tbody tr.led-detail").count(), 2); assert(!(await p.locator(".led-detail").nth(1).locator("dd.bad").count()), "a session file's success has nothing in red"); diff --git a/internal/gui/tests/usage-ledger.test.cjs b/internal/gui/tests/usage-ledger.test.cjs index 68f018aa3..e50844c5f 100644 --- a/internal/gui/tests/usage-ledger.test.cjs +++ b/internal/gui/tests/usage-ledger.test.cjs @@ -432,10 +432,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the window at its narrowest (MinWidth in app.go) await page.setViewportSize({ width: 560, height: 700 }); await page.waitForTimeout(200); - // the table scrolls in its box; the page never sideways + // the table scrolls in its box, and its scrollbar in its own; the page never sideways const sideways = () => page.evaluate(() => { const v = document.querySelector("#view-usage"), w = document.querySelector("#ledWrap"); - const wide = [...v.querySelectorAll("*")].filter((e) => !w.contains(e) && e.offsetParent && e.getBoundingClientRect().right > v.getBoundingClientRect().right + 1).map((e) => e.id || e.className).slice(0, 8); + const wide = [...v.querySelectorAll("*")].filter((e) => !w.contains(e) && e.parentElement?.id !== "ledHScroll" && e.offsetParent && e.getBoundingClientRect().right > v.getBoundingClientRect().right + 1).map((e) => e.id || e.className).slice(0, 8); return [document.documentElement.scrollWidth > document.documentElement.clientWidth || v.scrollWidth > v.clientWidth, wide, [w.scrollWidth, w.clientWidth]]; }); const [wider, wide, wrap] = await sideways(); diff --git a/internal/provider/models.go b/internal/provider/models.go index 47e3438a3..ec83afe97 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "math" "regexp" "slices" "sort" @@ -864,7 +865,7 @@ func MakerPrice(model string) (catalog.Price, bool) { // EffectivePrice is what a call to a provider's model costs the user: the // price they set for that model, or for every model of that provider, or for // that model from any provider (settings' ModelPrices), else the provider's own list price, else its -// maker's. The second return is false only when no price is known at all, +// maker's, either at the provider's price rate (PriceRate). The second return is false only when no price is known at all, // which is not the same as a price of zero: that one is set, deliberately. // // A price here is the provider's tariff, not the model's: the same model @@ -899,12 +900,30 @@ func EffectivePriceIn(s settings.Settings, providerID, model string) (catalog.Pr } } } - if known { - if pr, ok := p.ListPrice(model); ok { - return pr, true - } + if !known { + return MakerPrice(model) } - return MakerPrice(model) + pr, ok := p.ListPrice(model) + if !ok { + pr, ok = MakerPrice(model) + } + // what the provider bills against it (#819) + if ok && p.PriceRate > 0 { + pr = pr.Times(p.PriceRate) + } + return pr, ok +} + +// PriceRateOK says what is wrong with a provider's price rate, "" when +// nothing: from 0 (none) to 1000, in steps of 0.001. +func PriceRateOK(r float64) string { + if math.IsNaN(r) || r < 0 || r > 1000 { + return "a price rate is from 0 to 1000" + } + if math.Abs(r*1000-math.Round(r*1000)) > 1e-6 { + return "a price rate has at most three decimals, like 0.125" + } + return "" } // byIDOrWas is the provider with that id, else the one it was renamed from. diff --git a/internal/provider/price_rate_test.go b/internal/provider/price_rate_test.go new file mode 100644 index 000000000..eda0cc2ac --- /dev/null +++ b/internal/provider/price_rate_test.go @@ -0,0 +1,41 @@ +package provider + +import ( + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// A provider's price rate (#819) scales the list price a call is counted +// at, as a relay charging 0.8 of the official price bills; a price the user +// set for a model is what they said it costs, and stays as set. +func TestPriceRateScalesListPrice(t *testing.T) { + priceHome(t) + priceCatalog(t) + if err := Save(Provider{ID: "openai", Name: "OpenAI", Chat: "https://api.openai.com/v1", Key: "k", Models: []string{"sol"}, PriceRate: 0.5}); err != nil { + t.Fatal(err) + } + pr, ok := EffectivePrice("openai", "sol") + if !ok || pr.Input != 1 || pr.Output != 5 || pr.CacheRead != 0.125 || pr.CacheWrite != 1.25 { + t.Fatalf("at half the list price: %+v %v", pr, ok) + } + if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{"openai/sol": statePrice(3)}}); err != nil { + t.Fatal(err) + } + if pr, ok := EffectivePrice("openai", "sol"); !ok || pr.Input != 3 || pr.Output != 3 { + t.Fatalf("a price set for the model is not scaled: %+v %v", pr, ok) + } +} + +func TestPriceRateOK(t *testing.T) { + for _, r := range []float64{0, 0.8, 1.5, 0.125, 1000} { + if bad := PriceRateOK(r); bad != "" { + t.Errorf("%v: %s", r, bad) + } + } + for _, r := range []float64{-1, 1000.5, 0.1234} { + if PriceRateOK(r) == "" { + t.Errorf("%v taken", r) + } + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index b0c8785ae..400db9ba5 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -120,6 +120,13 @@ type Provider struct { // plugin's provider says it takes, else none; 0 is no limit. MaxConcurrency *int `json:"maxConcurrency,omitempty"` + // PriceRate is what the provider charges against the official price + // (ITea312, #819): a relay that bills 0.8× or 1.5× of it. It scales the + // provider's list price, else its maker's, wherever a cost is counted; + // a price the user set for one of its models stands as set. 0 is the + // price as listed; at most three decimals (PriceRateOK). + PriceRate float64 `json:"priceRate,omitempty"` + // Headers are extra HTTP request headers sent to the vendor, exactly as // the user typed them. They ride on every request magpie makes to a plain // key+URL provider — forwarded calls, connectivity tests, and model-list