diff --git a/internal/gui/api.go b/internal/gui/api.go index 3d80f5870..e5dd95d7c 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2887,6 +2887,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { }) agentModelsAPI(mux) speedsAPI(mux) + modelPriceRoutes(mux) devListen(mux) return noFramedAPI(held(mux)) } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 1726958eb..170accd9f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3733,6 +3733,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .mname .mprice > span { flex: none; } .mname .mpart { display: flex; align-items: center; gap: 4px; flex: none; } .mname .mpart input { width: 72px; height: 25px; font-size: 11.5px; } +.price-ask-parts { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px 10px; margin: 4px 0 8px; } +.price-ask-unit { grid-column: 1 / -1; font-size: 12px; color: var(--muted); } +.price-ask-parts .mpart { display: flex; flex-direction: column; align-items: stretch; gap: 3px; font-size: 12px; color: var(--muted); } +.price-ask-parts .mpart input { width: 100%; min-width: 0; } +.price-ask-bad { color: var(--red); margin: 0 0 6px; } .mname .mtier { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; flex: 1 1 100%; min-width: 0; } .mname .mtier[hidden], .mname .mtier-add[hidden] { display: none; } .mname .mtier-add { font-size: 11.5px; padding: 0; } diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 190bd2587..a4bb25d70 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -2,6 +2,11 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Set price…": "设置价格…", + "Price of {model}": "{model} 的价格", + "What {model} costs from every provider that has no price of its own for it. The Usage and Sessions pages count its calls at it, past ones too.": "{model} 在每个没有单独为它设价格的供应商处的价格。用量和会话页按它计算这个模型的调用,过去的也一样。", + "{model} is counted at the price you set": "{model} 已按你设置的价格计算", + "{model} is counted at its list price again": "{model} 已恢复按标价计算", "Saved by image files": "图片文件省下", "{n} saved by image files": "图片文件省下 {n}", "{n}/s": "{n}/s", @@ -251,6 +256,11 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", }, "zh-TW": { + "Set price…": "設定價格…", + "Price of {model}": "{model} 的價格", + "What {model} costs from every provider that has no price of its own for it. The Usage and Sessions pages count its calls at it, past ones too.": "{model} 在每個沒有單獨為它設價格的供應商處的價格。用量和會話頁依它計算這個模型的呼叫,過去的也一樣。", + "{model} is counted at the price you set": "{model} 已依你設定的價格計算", + "{model} is counted at its list price again": "{model} 已恢復依標價計算", "Saved by image files": "圖片檔案省下", "{n} saved by image files": "圖片檔案省下 {n}", "{n}/s": "{n}/s", @@ -500,6 +510,11 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", }, ja: { + "Set price…": "価格を設定…", + "Price of {model}": "{model} の価格", + "What {model} costs from every provider that has no price of its own for it. The Usage and Sessions pages count its calls at it, past ones too.": "{model} 用の価格を持たないすべてのプロバイダでの {model} の価格です。使用量とセッションのページは、過去の呼び出しも含めてこの価格で計算します。", + "{model} is counted at the price you set": "{model} は設定した価格で計算されます", + "{model} is counted at its list price again": "{model} は再び定価で計算されます", "Saved by image files": "画像ファイルで節約", "{n} saved by image files": "画像ファイルで {n} 節約", "{n}/s": "{n}/s", @@ -749,6 +764,11 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", }, de: { + "Set price…": "Preis festlegen…", + "Price of {model}": "Preis von {model}", + "What {model} costs from every provider that has no price of its own for it. The Usage and Sessions pages count its calls at it, past ones too.": "Was {model} bei jedem Anbieter kostet, der keinen eigenen Preis dafür hat. Die Seiten Nutzung und Sitzungen rechnen seine Aufrufe damit, auch frühere.", + "{model} is counted at the price you set": "{model} wird zu deinem Preis gerechnet", + "{model} is counted at its list price again": "{model} wird wieder zum Listenpreis gerechnet", "Saved by image files": "Durch Bilddateien gespart", "{n} saved by image files": "{n} durch Bilddateien gespart", "{n}/s": "{n}/s", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index d48cef661..a58001555 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -929,7 +929,7 @@ function renderUsage() { const again = agentMenu?.anchor === b; closeAgentMenu(); if (again) return; - openRowMenu(b, [{ name: "Clear usage…", icon: USAGE_CLEAR, run: () => clearUsage(g) }]); + openRowMenu(b, [{ name: "Set price…", icon: PRICE_TAG, run: () => setModelPrice(g.model) }, { name: "Clear usage…", icon: USAGE_CLEAR, run: () => clearUsage(g) }]); }; b.onclick = (e) => { e.stopPropagation(); menu(); }; r.oncontextmenu = (e) => { e.preventDefault(); menu(); }; @@ -973,6 +973,77 @@ async function clearUsage(g) { } } +// setModelPrice: a model's price from any provider (*/model), from its row +// on the Usage page (soilzhu80 on X): a model an agent ran is often in no +// provider's list, so no provider's Model settings can price it. Empty +// boxes take the maker's list price, shown greyed; Restore default takes +// the set price away. The pages count past calls at it too. +const PRICE_TAG = "M8.5 2.5H13.5V7.5L7.5 13.5L2.5 8.5ZM10.8 5.2h.01"; +async function setModelPrice(model) { + let now; + try { now = await api("model-price?model=" + encodeURIComponent(model)); } catch (e) { return status(e.message, "err"); } + const shown = (n) => String(Math.round(n * 1e6) / 1e6); + const ed = el("div", "editor price-ask"); + const head = el("div", "ehead"); + head.append(el("b", "", t("Price of {model}", { model }))); + ed.append(head, el("p", "lib-confirm", t("What {model} costs from every provider that has no price of its own for it. The Usage and Sessions pages count its calls at it, past ones too.", { model }))); + const box = el("div", "price-ask-parts"); + box.append(el("span", "price-ask-unit", t("Price, $ / 1M tokens"))); + const cells = [["input", "Input"], ["output", "Output"], ["cache_read", "Cache read"], ["cache_write", "Cache write"]].map(([k, l]) => { + const part = el("label", "mpart"); + const i = input(now.price ? shown(now.price[k]) : "", now.maker ? shown(now.maker[k]) : ""); + i.inputMode = "decimal"; + i.dataset.part = k; + part.append(el("span", "", t(l)), i); + box.append(part); + return i; + }); + const bad = el("p", "hint price-ask-bad"); + bad.hidden = true; + ed.append(box, bad); + const send = async (price, said) => { + try { + await api("model-price", { model, price }); + closeConfirmAsk(); + status(said, "ok"); + ledger = null; + loadUsage(); + } catch (e) { bad.textContent = e.message; bad.hidden = false; } + }; + const go = el("button", "text primary", t("Save")); + go.onclick = (e) => { + e.stopPropagation(); + const typed = cells.map((i) => i.value.trim()); + if (typed.every((v) => !v)) return now.price ? send(null, t("{model} is counted at its list price again", { model })) : closeConfirmAsk(); + const price = {}; + for (const [n, i] of cells.entries()) { + const k = i.dataset.part, v = typed[n] ? decimalOf(typed[n]) : now.maker ? now.maker[k] : n < 2 ? NaN : 0; + if (!(v >= 0)) { + bad.textContent = typed[n] || now.maker ? t("A price is a number of dollars, 0 or more") : t("{id} has no list price: give its input and output prices", { id: model }); + bad.hidden = false; + return i.focus(NO_SCROLL); + } + price[k] = v; + } + send(price, t("{model} is counted at the price you set", { model })); + }; + for (const i of cells) i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go.click(); else if (e.key === "Escape") closeConfirmAsk(); }; + const bar = el("div", "bar"); + if (now.price) { + const back = el("button", "text", t("Restore default")); + back.onclick = (e) => { e.stopPropagation(); send(null, t("{model} is counted at its list price again", { model })); }; + bar.append(back); + } + const cancel = el("button", "text", t("Cancel")); + cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; + bar.append(el("span", "grow"), cancel, go); + ed.append(bar); + confirmAsk = ed; + openModal(ed); + $("#modal").classList.add("lib"); + cells[0].focus(NO_SCROLL); +} + // countable is whether the Usage page's Agents list offers to count a // client as an agent: one magpie doesn't know, not magpie's own (#1839) // nor the calls that named no client. @@ -3689,7 +3760,7 @@ function renderSessions() { grid.hidden = false; // the folders and models to pick from, as the pickers offer them sessBars($("#sessProjects"), "Projects", sessSums(rows.filter((r) => byAgent(r) && byModel(r)), "cwd"), sessFolder, (v) => { sessFolder = v; renderSessions(); }, baseName); - sessBars($("#sessModels"), "Models", sessSums(rows.filter((r) => byAgent(r) && byFolder(r)), "model"), sessModel, (v) => { sessModel = v; renderSessions(); }, (v) => v); + sessBars($("#sessModels"), "Models", sessSums(rows.filter((r) => byAgent(r) && byFolder(r)), "model"), sessModel, (v) => { sessModel = v; renderSessions(); }, (v) => v, (r, v) => openRowMenu(r, [{ name: "Set price…", icon: PRICE_TAG, run: () => setModelPrice(v.slice(v.lastIndexOf("/") + 1)) }])); renderSessHours($("#sessHours"), actsIn); renderSessTop(); renderSessShape(); @@ -4321,7 +4392,7 @@ function sessLineUp(box) { // sessBars is a card of folders or models as bars of the tokens each took; // a click shows that one alone, and a click on it again every one const SESS_BARS = 6; -function sessBars(box, title, items, cur, choose, name) { +function sessBars(box, title, items, cur, choose, name, menu) { box.replaceChildren(); box.append(sessCardHead(title)); const body = el("div", "sess-bars"); @@ -4340,6 +4411,8 @@ function sessBars(box, title, items, cur, choose, name) { const fc = x.cost ? fmtCost(x) : ""; r.append(el("span", "n", name(x.v)), track, el("span", "v", fmtN(x.n)), el("span", "c", fc ? "≈" + fc : "")); r.onclick = () => choose(x.v === cur ? "" : x.v); + // a model's bar: its price, on a right-click + if (menu) r.oncontextmenu = (e) => { e.preventDefault(); menu(r, x.v); }; body.append(r); } if (!items.length) body.append(el("div", "sess-none", t("Nothing in this range."))); diff --git a/internal/gui/modelprice.go b/internal/gui/modelprice.go new file mode 100644 index 000000000..81b20100a --- /dev/null +++ b/internal/gui/modelprice.go @@ -0,0 +1,87 @@ +package gui + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// modelPriceJSON is a model's price from any provider (*/model), the one +// `magpie model price '*/model'` sets: what the user said it costs, if +// anything, and its maker's list price on models.dev, which is what the +// sheet shows greyed while nothing is typed. +type modelPriceJSON struct { + Model string `json:"model"` + Price *catalog.Price `json:"price"` + Maker *catalog.Price `json:"maker,omitempty"` +} + +func anyModelPrice(model string) modelPriceJSON { + out := modelPriceJSON{Model: model} + if m, ok := settings.Load().ModelPrices[provider.AnyPriceKey(model)]; ok { + if p, bad := m.Price(); bad == "" { + out.Price = &p + } + } + if p, ok := provider.MakerPrice(model); ok { + out.Maker = &p + } + return out +} + +// pricedModel is the model a price is asked for, or "" when it names none: +// one id, not every model ("*") nor a provider's ("*/…"). +func pricedModel(s string) string { + s = strings.TrimSpace(s) + if s == "" || s == "*" || len(s) > 200 || strings.HasPrefix(s, settings.AnyProvider) { + return "" + } + return s +} + +// modelPriceRoutes: the Usage page's Set price… on a model's row +// (soilzhu80 on X). A model an agent ran is often not in any provider's +// list, so the provider editor's Model settings can't price it; this sets +// what it costs from any provider not priced for it, the price a session's +// model is counted at. GET ?model= reads it; POST {"model","price"} sets +// it, a null price takes it away. +func modelPriceRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/model-price", func(rw http.ResponseWriter, r *http.Request) { + model := pricedModel(r.URL.Query().Get("model")) + if model == "" { + http.Error(rw, "name one model", http.StatusBadRequest) + return + } + writeJSON(rw, anyModelPrice(model)) + }) + mux.HandleFunc("POST /api/model-price", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Model string `json:"model"` + Price *catalog.Price `json:"price"` + } + if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 16<<10)).Decode(&in); err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + model := pricedModel(in.Model) + if model == "" { + http.Error(rw, "name one model", http.StatusBadRequest) + return + } + if in.Price != nil { + // a price typed in the sheet has no tiers or peak hours + in.Price.Tiers, in.Price.Peak = nil, "" + } + if err := provider.SetModelPrice(provider.AnyPriceKey(model), in.Price); err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + // the Sessions tab's stats are priced when they are read + forgetStats() + writeJSON(rw, anyModelPrice(model)) + }) +} diff --git a/internal/gui/modelprice_test.go b/internal/gui/modelprice_test.go new file mode 100644 index 000000000..d77408bfa --- /dev/null +++ b/internal/gui/modelprice_test.go @@ -0,0 +1,66 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +func modelPriceAsk(t *testing.T, mux *http.ServeMux, method, target, body string) (int, modelPriceJSON) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, target, strings.NewReader(body))) + var out modelPriceJSON + if w.Code == 200 { + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + } + return w.Code, out +} + +// The Usage page's Set price… (soilzhu80 on X) prices a model no provider +// lists: it is kept as the model's price from any provider (*/model), the +// key `magpie model price '*/model'` writes and a session's model is +// counted at, and a null price takes it away again. +func TestModelPriceFromAnyProvider(t *testing.T) { + sandboxHome(t) + mux := http.NewServeMux() + modelPriceRoutes(mux) + + code, got := modelPriceAsk(t, mux, "GET", "/api/model-price?model=Agent-Only-9", "") + if code != 200 || got.Price != nil || got.Model != "Agent-Only-9" { + t.Fatalf("before: %d %+v", code, got) + } + code, got = modelPriceAsk(t, mux, "POST", "/api/model-price", `{"model":"Agent-Only-9","price":{"input":1.5,"output":6,"cache_read":0.15,"cache_write":0}}`) + if code != 200 || got.Price == nil || got.Price.Input != 1.5 || got.Price.Output != 6 || got.Price.CacheRead != 0.15 { + t.Fatalf("set: %d %+v", code, got) + } + m, ok := settings.Load().ModelPrices["*/agent-only-9"] + if !ok || m.Input == nil || *m.Input != 1.5 { + t.Fatalf("not kept under */agent-only-9: %v", settings.Load().ModelPrices) + } + if _, got = modelPriceAsk(t, mux, "GET", "/api/model-price?model=agent-only-9", ""); got.Price == nil || got.Price.Output != 6 { + t.Fatalf("read back: %+v", got) + } + // a price no vendor could charge, and no one model, are refused + for _, body := range []string{`{"model":"agent-only-9","price":{"input":-1,"output":6}}`, `{"model":"*","price":{"input":1,"output":6}}`, `{"model":"*/x","price":{"input":1,"output":6}}`, `{"model":" ","price":null}`} { + if code, _ := modelPriceAsk(t, mux, "POST", "/api/model-price", body); code != 400 { + t.Errorf("%s: %d, want 400", body, code) + } + } + if m := settings.Load().ModelPrices["*/agent-only-9"]; m.Input == nil || *m.Input != 1.5 { + t.Fatalf("a refused price changed the kept one: %+v", m) + } + code, got = modelPriceAsk(t, mux, "POST", "/api/model-price", `{"model":"Agent-Only-9","price":null}`) + if code != 200 || got.Price != nil { + t.Fatalf("take away: %d %+v", code, got) + } + if _, ok := settings.Load().ModelPrices["*/agent-only-9"]; ok { + t.Fatal("still kept after a null price") + } +} diff --git a/internal/gui/tests/usage-clear.test.cjs b/internal/gui/tests/usage-clear.test.cjs index 068ea86e8..2c137b547 100644 --- a/internal/gui/tests/usage-clear.test.cjs +++ b/internal/gui/tests/usage-clear.test.cjs @@ -99,8 +99,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const more = row.locator(".us-more"); await more.click(); const item = p.locator(".row-menu .rm-item"); - assert.deepEqual((await item.allTextContents()).map((s) => s.trim()), [w.item]); - await item.click(); + // Set price… above it (usage-model-price.test.cjs) + assert.deepEqual((await item.allTextContents()).map((s) => s.trim()).slice(1), [w.item]); + await item.nth(1).click(); const dialog = p.locator("dialog.action-confirm"); await dialog.waitFor(); assert.equal(await dialog.getAttribute("role"), "alertdialog"); diff --git a/internal/gui/tests/usage-model-price.test.cjs b/internal/gui/tests/usage-model-price.test.cjs new file mode 100644 index 000000000..b6d705efe --- /dev/null +++ b/internal/gui/tests/usage-model-price.test.cjs @@ -0,0 +1,204 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// soilzhu80 on X: a model an agent runs is often in no provider's list, so +// no provider's Model settings can price it. A model's row on the Usage +// page (its "…", or a right-click) and its bar on the Sessions tab (a +// right-click) offer "Set price…": a sheet of four prices in $ / 1M tokens, +// the maker's list price greyed in empty boxes, that POSTs the model's +// price from any provider (/api/model-price) and reads the page again. A +// typed comma is a decimal point, a price that is no number is refused in +// the sheet, a model with no list price needs its input and output, and +// Restore default takes a set price away. The Sessions bar asks for the +// model's bare id, the one a session's model is priced at. Narrow window, +// both engines, every language; 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 assets = path.resolve(__dirname, "../assets"); + +const G = (id, name, tokens, extra) => ({ id, name, icon: "generic", calls: 10, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0, ...extra }); +const KNOWN = G("relay/sol-7", "sol-7", 900000, { provider: "relay", model: "sol-7", sub: "Relay" }); +const AGENT = G("relay/agent-only-9", "agent-only-9", 300000, { provider: "relay", model: "agent-only-9", sub: "Relay" }); +const usage = { + calls: 20, errors: 0, input: 1199800, output: 200, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 10, cost: 0, bucket: "day", + series: [], path: "~/.config/magpie/usage.jsonl", agents: [G("pi", "Pi", 1200000)], models: [KNOWN, AGENT], +}; +const MAKER = { input: 0.5, output: 2, cache_read: 0.05, cache_write: 0.625 }; +const today = new Date(); +const iso = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const days = [{ date: iso(today), usage: [{ agent: "claude", cwd: "/work/a", model: "relay/agent-only-9", input: 30000, output: 4000, cache_read: 0, cache_write: 0, cost: 0, priced: false }], active: [] }]; + +function serve(lang, saved, asks) { + return async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + const settings = () => ({ lang, theme: "light" }); + 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: [], clients: [{ id: "pi", name: "Pi", icon: "pi" }], profiles: [], settings: settings() }); + if (url.pathname === "/api/model-price") { + const model = req.method() === "POST" ? JSON.parse(req.postData()).model : url.searchParams.get("model"); + const maker = model === "sol-7" ? MAKER : undefined; + if (req.method() === "POST") { + const body = JSON.parse(req.postData()); + asks.posts.push(body); + if (body.price) saved[model] = body.price; else delete saved[model]; + } else asks.gets.push(model); + return json({ model, price: saved[model] || null, maker }); + } + if (url.pathname === "/api/usage") { asks.usage++; return json(usage); } + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/sessions/progress") return json({ indexing: false }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: ["/test/sessions"] }); + if (url.pathname === "/api/sessions/stats") { asks.stats++; return json({ from: days[0].date, to: days[0].date, days, agents: { claude: "Claude Code" } }); } + 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)]; + const body = await fs.readFile(file).catch(() => null); + await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" })); + }; +} + +const L = { + en: { item: "Set price…", clear: "Clear usage…", title: "Price of sol-7", save: "Save", back: "Restore default", bad: "A price is a number of dollars, 0 or more", none: "agent-only-9 has no list price: give its input and output prices", set: "sol-7 is counted at the price you set", list: "sol-7 is counted at its list price again" }, + zh: { item: "设置价格…", clear: "清除用量…", title: "sol-7 的价格", save: "保存", back: "恢复默认", bad: null, none: null, set: "sol-7 已按你设置的价格计算", list: "sol-7 已恢复按标价计算" }, + "zh-TW": { item: "設定價格…", clear: "清除用量…", title: "sol-7 的價格", save: null, back: null, bad: null, none: null, set: "sol-7 已依你設定的價格計算", list: "sol-7 已恢復依標價計算" }, + ja: { item: "価格を設定…", clear: "使用量を消去…", title: "sol-7 の価格", save: null, back: null, bad: null, none: null, set: "sol-7 は設定した価格で計算されます", list: "sol-7 は再び定価で計算されます" }, + de: { item: "Preis festlegen…", clear: "Nutzung löschen…", title: "Preis von sol-7", save: null, back: null, bad: null, none: null, set: "sol-7 wird zu deinem Preis gerechnet", list: "sol-7 wird wieder zum Listenpreis gerechnet" }, +}; + +// the sheet fits the window: nothing in it wider than the dialog +const fits = (p) => p.evaluate(() => { + const ed = document.querySelector(".price-ask"), r = ed.getBoundingClientRect(); + const out = [...ed.querySelectorAll("input, button, b, p")].filter((n) => !n.hidden && n.getBoundingClientRect().right > r.right + 1).map((n) => n.outerHTML.slice(0, 80)); + return { out, wide: document.documentElement.scrollWidth <= innerWidth + 1, inside: r.left >= 0 && r.right <= innerWidth }; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a model's price is set from its Usage row and its Sessions bar", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(L)) { + const w = L[lang]; + await t.test(lang, async () => { + const errors = []; + const saved = {}, asks = { posts: [], gets: [], usage: 0, stats: 0 }; + const ctx = await browser.newContext({ viewport: { width: 420, height: 760 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", serve(lang, saved, asks)); + await p.goto("http://magpie.test/?view=usage"); + const row = p.locator(`#usageModels .row.stat[data-id="${KNOWN.id}"]`); + await row.waitFor(); + await row.scrollIntoViewIfNeeded(); + + // the row's "…": Set price… above Clear usage… + await row.locator(".us-more").click(); + const items = p.locator(".row-menu .rm-item"); + assert.deepEqual((await items.allTextContents()).map((s) => s.trim()), [w.item, w.clear]); + await items.first().click(); + const sheet = p.locator("#modal .price-ask"); + await sheet.waitFor(); + assert.deepEqual(asks.gets, ["sol-7"]); + assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w.title); + const box = (k) => sheet.locator(`input[data-part="${k}"]`); + // empty, the maker's price greyed in each box; the first one focused + assert.deepEqual(await sheet.locator("input").evaluateAll((is) => is.map((i) => [i.value, i.placeholder])), [["", "0.5"], ["", "2"], ["", "0.05"], ["", "0.625"]]); + assert.equal(await box("input").evaluate((i) => i === document.activeElement), true); + assert.equal(await sheet.locator("button", { hasText: w.back || "Restore default" }).count(), 0, "nothing set: nothing to restore"); + const f = await fits(p); + assert.deepEqual(f.out, []); + assert.ok(f.wide && f.inside, JSON.stringify(f)); + if (w.save) assert.equal((await sheet.locator(".bar .primary").textContent()).trim(), w.save); + + // no number: said in the sheet, nothing sent + await box("input").fill("abc"); + await sheet.locator(".bar .primary").click(); + const bad = sheet.locator(".price-ask-bad"); + await bad.waitFor(); + if (w.bad) assert.equal((await bad.textContent()).trim(), w.bad); + assert.deepEqual(asks.posts, []); + + // a comma for the decimal point; the boxes left empty take the maker's + const before = asks.usage; + await box("input").fill("1,5"); + await box("output").fill("6"); + await box("output").press("Enter"); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(asks.posts, [{ model: "sol-7", price: { input: 1.5, output: 6, cache_read: 0.05, cache_write: 0.625 } }]); + await p.locator("#status", { hasText: w.set }).waitFor(); + for (let i = 0; i < 50 && asks.usage === before; i++) await p.waitForTimeout(20); + assert.ok(asks.usage > before, "the page is read again"); + + // opened again: the price set, and Restore default takes it away + await row.click({ button: "right" }); + await p.locator(".row-menu .rm-item", { hasText: w.item }).click(); + await sheet.waitFor(); + assert.deepEqual(await sheet.locator("input").evaluateAll((is) => is.map((i) => i.value)), ["1.5", "6", "0.05", "0.625"]); + const back = sheet.locator(".bar button").first(); + if (w.back) assert.equal((await back.textContent()).trim(), w.back); + await back.click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(asks.posts.at(-1), { model: "sol-7", price: null }); + await p.locator("#status", { hasText: w.list }).waitFor(); + + // a model with no list price needs its input and output + const other = p.locator(`#usageModels .row.stat[data-id="${AGENT.id}"]`); + await other.click({ button: "right" }); + await p.locator(".row-menu .rm-item", { hasText: w.item }).click(); + await sheet.waitFor(); + assert.deepEqual(await sheet.locator("input").evaluateAll((is) => is.map((i) => i.placeholder)), ["", "", "", ""]); + await box("input").fill("2"); + await sheet.locator(".bar .primary").click(); + await bad.waitFor(); + if (w.none) assert.equal((await bad.textContent()).trim(), w.none); + assert.equal(asks.posts.length, 2); + await box("output").fill("8"); + await sheet.locator(".bar .primary").click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(asks.posts.at(-1), { model: "agent-only-9", price: { input: 2, output: 8, cache_read: 0, cache_write: 0 } }); + + // Sessions: a model's bar, right-clicked, prices its bare id + await p.evaluate(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); }); + await p.goto("http://magpie.test/?view=usage"); + const bar = p.locator("#sessModels .sess-bar").first(); + await bar.waitFor(); + await bar.scrollIntoViewIfNeeded(); + await bar.click({ button: "right" }); + const only = p.locator(".row-menu .rm-item"); + assert.deepEqual((await only.allTextContents()).map((s) => s.trim()), [w.item]); + await only.click(); + await sheet.waitFor(); + assert.equal(asks.gets.at(-1), "agent-only-9"); + assert.deepEqual(await sheet.locator("input").evaluateAll((is) => is.map((i) => i.value)), ["2", "8", "0", "0"]); + const stats = asks.stats; + await box("input").fill("3"); + await sheet.locator(".bar .primary").click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(asks.posts.at(-1), { model: "agent-only-9", price: { input: 3, output: 8, cache_read: 0, cache_write: 0 } }); + for (let i = 0; i < 50 && asks.stats === stats; i++) await p.waitForTimeout(20); + assert.ok(asks.stats > stats, "the Sessions tab is read again"); + // Escape closes it, sending nothing + await bar.click({ button: "right" }); + await only.click(); + await sheet.waitFor(); + const sent = asks.posts.length; + await box("input").press("Escape"); + await sheet.waitFor({ state: "detached" }); + assert.equal(asks.posts.length, sent); + + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +}