Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

TokenDance leads the models page, and its promoted rows show what they cost (#531)

Yaowei Zheng3e0f174e922d
diff --git a/.agents/skills/penguin-harness-dev/SKILL.md b/.agents/skills/penguin-harness-dev/SKILL.md
index cb21f0f5..c31b31a4 100644
--- a/.agents/skills/penguin-harness-dev/SKILL.md
+++ b/.agents/skills/penguin-harness-dev/SKILL.md
@@ -59,6 +59,8 @@ The local server suite drops a few tests under full parallel load — they time
Once the evidence you chose passes, commit and push to the current branch without asking. Force-pushes and reverting someone else's commits still need confirmation.
+**On a conflicting PR, waiting for CI is waiting for nothing.** The workflows run against the merge commit GitHub builds from the branch and `main`, and it does not build one while the two conflict — the checks never start, so polling `statusCheckRollup` returns the same pending or empty list forever. Read the state before the checks: `gh pr view <n> --json mergeable,mergeStateStatus` answers `CONFLICTING` / `DIRTY`. Merge `origin/main` into the branch, resolve, push, and only then expect checks. Two more things that pass silently and are worth checking in the same pass: an auto-merged file is not a correct file, so read the merged result where two PRs touched one region; and a test constant pinned to a count the other PR changed fails for a reason that has nothing to do with either change — derive the count instead of re-pinning it.
+
## Record and ship
Every change ships a changelog entry, in both languages, in `changelog/unreleased/`:
@@ -97,6 +99,8 @@ Release screenshots are captured, not mocked up: drive the app through the Playw
- Pricing is three buckets in USD per million tokens: `cache_read` (the vendor's cache-hit price), `cache_write` (the vendor's cache-write price, or the standard input price where the vendor charges no write premium), `output`. `cny(...)` converts official CNY list prices at the 7:1 display convention.
- A vendor with **tiered** pricing gets its base tier recorded, and the tier boundary noted in the section comment — OpenAI above 272K input, Gemini 3.1 Pro above 200K, MiniMax M3 above 512K. Long-context use is then knowingly under-costed; that is the convention, not an oversight.
+- A **promotion** is a `discount` fraction beside the list `pricing`, never a discounted number written into `pricing`: `effectivePricing()` derives the billed rate, and a lapsed promotion is one field to delete with the rate to return to still on the row. `presetModelEntries()` writes the effective rate, so what a Project stores is what the gateway charges.
+- A **time-based** tier is an `offPeakDiscount` schedule instead, and it is never baked into a Project. The row stores its peak price, and the cost center decides the tier from each usage record's own `ts` — the aggregation splits by tier before pricing. Deciding it at read time instead would move a finished week's cost every time the boundary passed.
- Uniqueness is the `(provider, model_id)` pair, never the bare id — gateways resell vendor models under their upstream ids.
- Set `client_type` only when the id cannot be auto-routed or a protocol must be pinned, and inline `baseUrl` with it. Everything else is auto-routed by AgentHub.
- A provider group is split only when the vendor genuinely has separate endpoints or billing paths (Qwen Token Plan vs Pay-As-You-Go). One endpoint serving several key types is one group.
diff --git a/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.md b/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.md
new file mode 100644
index 00000000..7cf5229d
--- /dev/null
+++ b/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.md
@@ -0,0 +1,159 @@
+# TokenDance leads the models page, and its promoted rows show what they actually cost
+
+- **Date:** 2026-08-28
+- **Type:** feature
+- **Scope:** `model-catalog`, `server`, `web`, `cli`, `docs`
+- **PR:** [#531](https://github.com/Prism-Shadow/penguin-harness/pull/531)
+
+[中文版](2026-08-28-catalog-tokendance-discounts.zh.md)
+
+Tencent's Hy4 preview joined the catalog through both of its sellers, six TokenDance rows
+gained a declared discount that the models page now shows and the cost center now bills at,
+TokenDance became the recommended provider group and leads the page by default, the model card
+was rebuilt around three fixed rows and now says what each model has spent, and the Chinese UI
+renamed the three price buckets.
+
+## The catalog
+
+- Added `tencent/hy4-preview` to the OpenRouter group: a 1,048,576-token context window,
+ text-only, at $0.834 input / $2.501 output / $0.042 cache read per million tokens.
+- Added `hy4-preview` to the TokenDance group: the same upstream model reached through a
+ second seller, at that gateway's own CNY 6 / 18 / 0.3 (input / output / cache hit) over a
+ 1,024,000-token window. Each row records what its own seller charges, so the pair is kept
+ apart the same way the two `qwen3.8-flash` rows are.
+- Catalog entries gained a `discount` field: the rate a seller is running off its list price.
+ `pricing` stays the list price whatever promotion is live, and the new `effectivePricing()`
+ applies the discount. Six TokenDance rows declare one — `deepseek-v4-flash-0731`,
+ `deepseek-v4-pro-0813` and `glm-5.3-flash` at 50% off, `kimi-k3` at 20%, `glm-5.3` and
+ `qwen3.8-max` at 10%.
+- Corrected the list prices of `deepseek-v4-flash-0731` and `deepseek-v4-pro-0813` in the
+ TokenDance group, which had recorded the promotional rate as the list price: they doubled,
+ to CNY 0.1 / 3 / 9 and CNY 0.3 / 9 / 27 (cache hit / input / output), so that 50% off
+ reproduces the rate TokenDance bills.
+- `presetModelEntries()` now writes the effective price into a Project rather than the list
+ price, so a promoted row is costed at the rate it is billed at.
+- **DeepSeek's direct rows follow its peak/off-peak tiers.** They recorded the off-peak tier
+ and treated peak usage as costing the same, which under-counted it by half. They now record
+ the **peak** price — CNY 0.1 / 3 / 9 for the two V4 Flash rows, CNY 0.3 / 9 / 27 for V4 Pro —
+ and declare `offPeakDiscount`, a weekly schedule that halves every bucket outside Beijing
+ weekday 09:00–12:00 and 14:00–18:00. The models page marks an off-peak row `-50%` and prints
+ the reduced figure; at peak it prints the stored price and carries no mark; the cost center
+ bills at whichever is in force.
+- Catalog entries gained `offPeakDiscount` alongside `discount`, and the two differ in where
+ the rate is applied. A flat promotion is one rate until it lapses, so `sync presets` bakes it
+ into the Project. A scheduled one changes twice a day, so **nothing is baked in**: the peak
+ price is what goes on disk, and the reduction is applied when a price is read. A number in
+ `.project_config.toml` that meant something different an hour later would be unreadable, and
+ re-syncing would rewrite prices by the clock. `effectivePricing` and `offPeakAt` take the
+ instant to judge, so the answer is the vendor's clock rather than the host's timezone.
+
+## The models page
+
+- TokenDance is marked as the recommended provider group: it leads the default group order,
+ wears a gold "Recommended" pill on its own collapse bar, and is the group the page opens
+ expanded on a first visit. The pill is spelled in gold rather than through `Badge`'s `brand`
+ tone, which is deliberately gray — neutral emphasis outside the status vocabulary — and an
+ endorsement is neither a status nor neutral. Its English label is one word because
+ this is the one group carrying five actions, making its row the most crowded on the page, and
+ the vendor name beside it is what a reader needs first.
+- **The model card is three fixed rows.** Its name, one size down, with what the model has
+ spent on the right edge; then every standing mark on a row of its own — default, vision,
+ vision proxy, fast, free, discount, in that order, so the eye learns where to look; then the
+ price line. The marks had been sharing the title's line, where each was width the model's
+ name had to give up. The mark row renders even when empty, at the tags' own height: most
+ models carry no mark, and cards in one row of a two-column grid stretch to the tallest, so a
+ collapsing row would show as uneven padding rather than as a shorter card.
+- **The upstream id has left the card.** It is a detail you go looking for rather than one you
+ scan by, and it is one click away in the config dialog; the width it was taking now belongs
+ to the name and to the spend figure.
+- **Each card says what that model has cost in Tokens** — `17.7B toks`, grey and a size below
+ the price line, on the title row's right edge. It is a lifetime figure with no date or Agent
+ window, which is why it comes from its own `GET /usage/model-totals` rather than from the
+ cost center's filtered aggregate, and its own request rather than the model list: a stats
+ failure costs the figure, not the page. A model that has never run shows nothing rather than
+ a zero, which would read as a measurement instead of an absence. `humanizeTokens` gained a
+ billions tier for it, in the Web App and in the CLI that shares its conventions. The unit is
+ abbreviated the way the rest of the page already abbreviates it — `tok/s`, `/M tok`.
+- **The page's marks are small unfilled pills** — a hairline border, no fill at all, and the hue
+ surviving only in the text. Six marks filling six coloured chips turned the row into confetti;
+ on a page whose job is scanning names, the marks are meant to be noticed second. Three inks
+ group them rather than enumerate them: what the model is, what it can do, what it costs. They
+ are spelled in the models page rather than in `lib/tone.ts` because they are identities, not
+ judgements — "default", "vision", "free" say what a model *is*, and none ranks above its
+ neighbour; the words carry the identity in every case, so the ink only sorts them at a glance.
+ The group header's recommendation pill is unfilled on the same reasoning.
+- **The config dialog's header is three lines**: the name, the upstream id, then the marks. They
+ had shared the name's line, where a long name wrapped underneath them and left the header
+ ragged. They are the same pills the cards wear, so the list and the dialog agree about what a
+ mark looks like.
+- A discounted model card shows the **billed** price alone. What the row would have cost
+ without the promotion answers no question a reader of this list is asking, and spending the
+ price line's width on it pushes out the figures that do; the rate off list is one of the tags
+ instead. A row whose price has been edited away from the catalog's shows neither.
+- **A narrow group header can no longer overlap its own actions.** The vendor name is the one
+ element that takes the leftover space and the one that truncates; giving it a minimum width
+ was what caused the overlap, since the marks beside it never shrink, so once their widths plus
+ that floor exceeded the button the whole group overflowed and ran under the actions. The floor
+ is gone and the model count and the recommendation drop out on a narrow row instead — the same
+ rule the actions' own labels already followed. Verified with no overflow at nine widths from
+ 1500px down to 400px.
+
+- **A scheduled row's price is re-read on the hour.** Every window a schedule can express is
+ hour-aligned, so the page re-aims a timer at the next hour rather than polling: a card left
+ open at 08:59 would otherwise still promise half price at 09:05.
+
+## Three fixes the card work turned up
+
+- **A model's display name can be cleared again.** Only provider and model id are required, and
+ the field says it defaults to the model id — but for a model the built-in catalog names, an
+ absent `display_name` on disk means "inherit the catalog's", so clearing the field wrote
+ nothing and the deleted name came back on the next load. The empty string now records the
+ deletion, and the read tells it apart from an absent field. A model the catalog does not name
+ keeps writing nothing, since absence already says "no name" there.
+- **A save confirmation names the model it is about.** It read `确定保存对「」的配置修改?`
+ after the name was cleared, because the label fell back to the id only when the name was
+ `undefined` — and clearing a field leaves `""`. The dialog header had the same gap, printing
+ an empty title and then repeating the id underneath.
+- **Re-saving a model no longer edits its price.** The form rounds the stored USD to four
+ decimals so it is typeable, and submitting re-encoded that rounding as the new price — so
+ opening a promoted row and pressing confirm without touching anything moved it off the figure
+ its seller bills and dropped the discount mark. A bucket still holding exactly what was loaded
+ into it is now written back unchanged; editing the field is what makes the typed value
+ authoritative.
+
+## On-disk configuration
+
+Clearing a display name writes `display_name = ""` into `.project_config.toml`, a value nothing
+wrote before. No migration is needed and nothing has to be done to an existing Project: a config
+without the field behaves exactly as it did. An older build reading a newer config treats the
+empty string as absent and shows the catalog's name again — the cleared name reappears, and
+nothing else changes.
+
+## How a scheduled row is billed
+
+A row on a peak/off-peak schedule stores its peak price, and the cost center decides the tier
+from **each usage record's own timestamp** rather than from the hour the page is opened. The
+aggregation splits by tier before it prices anything, so a range that straddles a boundary is
+billed at the rate each request actually ran at, and a finished week reports the same number
+whenever it is read.
+
+## Chinese price labels
+
+The three price buckets read `缓存命中` / `缓存未命中` / `输出` in the Chinese UI — on the
+models page's price fields, in the cost center's token buckets and chart legends, and in the
+CLI's `penguin config model add` price options. English labels are unchanged, as are the
+field, type and wire names.
+
+## Existing Projects
+
+Presets are copied into `.project_config.toml` when a Project is created and nothing rewrites
+them afterwards, so none of the price changes above reach an existing Project on their own.
+They arrive only through the models page's **sync presets**, which lowers the six promoted
+TokenDance rows to the rate they are billed at; the corrected DeepSeek list prices likewise
+reach an existing Project only if it syncs. Because the prices moved, every Project holding
+catalog rows sees the preset-update badge and its page notice until it either syncs or dismisses
+them, and accepting the sync changes the cost the cost center reports for usage that already
+happened — those figures have always been priced against current pricing rather than against the
+rate in force when each request ran. The default group order and the first-visit
+expanded group are defaults: a Project that has ever dragged a group header, or toggled a
+group open, keeps its own arrangement untouched.
diff --git a/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.zh.md b/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.zh.md
new file mode 100644
index 00000000..dbd63b63
--- /dev/null
+++ b/changelog/unreleased/2026-08-28-catalog-tokendance-discounts.zh.md
@@ -0,0 +1,119 @@
+# TokenDance 排在模型页首位,促销条目显示实际价格
+
+- **Date:** 2026-08-28
+- **Type:** feature
+- **Scope:** `model-catalog`, `server`, `web`, `cli`, `docs`
+- **PR:** [#531](https://github.com/Prism-Shadow/penguin-harness/pull/531)
+
+[English](2026-08-28-catalog-tokendance-discounts.md)
+
+腾讯 Hy4 preview 经两个卖家一并收录进目录;六个 TokenDance 条目声明了折扣,模型页据此展示、
+成本中心据此计价;TokenDance 成为官方推荐分组并默认排在首位;模型卡片按三行重建,并会说出每个模型
+花掉了多少 Token;中文界面重命名了三个价格档位。
+
+## 模型目录
+
+- OpenRouter 分组新增 `tencent/hy4-preview`:1,048,576 Token 上下文,纯文本,每百万 Token
+ $0.834 输入 / $2.501 输出 / $0.042 缓存命中。
+- TokenDance 分组新增 `hy4-preview`:同一个上游模型经第二个卖家提供,按该网关自己的 CNY
+ 6 / 18 / 0.3(输入 / 输出 / 缓存命中)计价,上下文 1,024,000 Token。每条记录各自卖家的
+ 收费,因此这一对与两条 `qwen3.8-flash` 一样必须保持分开。
+- 目录条目新增 `discount` 字段:卖家在牌价基础上正在执行的折扣率。无论促销是否进行,
+ `pricing` 始终是牌价,由新增的 `effectivePricing()` 应用折扣。六个 TokenDance 条目声明了
+ 折扣——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813` 与 `glm-5.3-flash` 五折,
+ `kimi-k3` 八折,`glm-5.3` 与 `qwen3.8-max` 九折。
+- 修正 TokenDance 分组中 `deepseek-v4-flash-0731` 与 `deepseek-v4-pro-0813` 的牌价——此前把
+ 促销价当作了牌价:两者各翻一倍,改为 CNY 0.1 / 3 / 9 与 CNY 0.3 / 9 / 27
+ (缓存命中 / 输入 / 输出),使五折后正好等于 TokenDance 的实际收费。
+- `presetModelEntries()` 现在向 Project 写入折后价而非牌价,促销条目因此按实际计费价核算成本。
+- **DeepSeek 直连条目改为跟随其峰谷计价。** 此前它们记录空闲档,并把高峰用量按同一价格计算,令高峰
+ 成本少算一半。现在记录**高峰价**——两条 V4 Flash 为 CNY 0.1 / 3 / 9,V4 Pro 为 CNY 0.3 / 9 / 27
+ ——并声明 `offPeakDiscount`:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半。
+ 模型页在空闲时段标记 `-50%` 并显示减半后的数字;高峰时段显示存盘价、不带任何标记;成本中心按当下
+ 生效的那一档计价。
+- 目录条目在 `discount` 之外新增 `offPeakDiscount`,两者的区别在于折扣**在哪一步生效**。固定促销是
+ 一个持续到结束的价格,因此「同步预置」会把它写进 Project。而按时段的折扣一天变两次,因此**什么都不
+ 预先写死**:落盘的是高峰价,减免在读取价格时应用。`.project_config.toml` 里一个「一小时后含义就变了」
+ 的数字是无法阅读的,而且会让重新同步按时钟改写价格。`effectivePricing` 与 `offPeakAt` 都接收判定
+ 时刻,因此答案取决于厂商的时钟,而不是宿主机的时区。
+
+## 模型页
+
+- TokenDance 被标记为官方推荐分组:默认排在分组顺序首位,在自己的折叠栏上佩戴一枚金色的「官方推荐」
+ 胶囊,并且是首次访问时默认展开的分组。该胶囊直接写成金色,而不是取用 `Badge` 的 `brand` 语义色
+ ——后者刻意是灰的(状态词汇之外的中性强调),而「推荐」既不是状态、也不中性。英文标签只用一个
+ 词:这是唯一带五个操作的分组,其所在行是整页最拥挤的一行,而旁边的厂商名才是读者最先需要的。
+- **模型卡片改为固定三行。** 第一行是名称(字号小一号),右端是该模型的累计花费;第二行是全部常驻
+ 标记独占一行——默认、视觉、视觉代理、快速、免费、折扣,顺序固定,好让视线学会去哪里找;第三行是
+ 价格行。这些标记此前挤在标题那一行,每一枚都是模型**名字**让出来的宽度。标记行即使为空也会渲染,
+ 高度就是标记自身的高度:多数模型一枚标记也没有,而两列网格中同一行的卡片会被撑到最高者,因此一个
+ 会塌陷的行表现出来是参差的留白,而不是一张更矮的卡片。
+- **上游 id 从卡片上撤下。** 它是需要时才去查的细节,而不是用来扫读的信息,而且在配置对话框里只有
+ 一次点击之遥;它此前占用的宽度现在归还给名称与花费数字。
+- **每张卡片会说出该模型消耗了多少 Token**——形如 `17.7B toks`,灰色,字号比价格行再小一档,落在
+ 标题行的右端。这是一个不限时间、不限 Agent 的累计值,因此它来自专用的 `GET /usage/model-totals`
+ 而非成本中心那份带筛选的聚合,并且是独立的一次请求而不是塞进模型列表:统计取不到时代价是这个数字
+ 消失,而不是整页失败。从未跑过的模型显示空白而不是 0——0 读起来像是一次测量结果,而不是「没有」。
+ 为此 `humanizeTokens` 增加了十亿档,Web 端与共用同一套约定的 CLI 一并调整;单位沿用页面上已有的
+ 缩写方式——`tok/s`、`/M tok`。
+- **页面上的标记是一枚枚无填充的小圆角胶囊**:只有一道细描边,完全不铺底色,色相只留在文字上。六枚
+ 标记配六块彩色底会把这一行变成花花绿绿的碎纸;在一个以扫读名称为本职的页面上,这些标记本就该是第二
+ 眼才看到的东西。三种墨色把它们归类而不是逐个点名:模型**是什么**、**能做什么**、**多少钱**。它们写
+ 在模型页而不是 `lib/tone.ts`:它们是身份而不是判断——「默认」「视觉」「免费」说的是模型**是什么**,
+ 彼此之间没有高下;而且每一枚的身份都由文字承担,墨色只负责让视线一眼分堆。分组标题上的「官方推荐」
+ 胶囊同理,也不再铺底色。
+- **模型配置对话框的头部改为三行**:名称、上游 id,然后是标记。此前标记与名称挤在同一行,长名称会折行
+ 钻到它们下面,把头部撑得参差不齐。这些标记与卡片上的是同一种胶囊,使列表与对话框对「标记长什么样」
+ 保持一致。
+- 折扣中的模型卡片只显示**实际计费价**。这一行在没有促销时会是多少钱,并不回答浏览这份列表的人
+ 正在问的任何问题,而为它花掉价格行的宽度,会把真正该显示的数字挤出去;折扣率改为标记行里的一枚
+ 标签。价格已被改成与目录不同的条目两者都不显示。
+- **窄屏下的分组标题不会再压到自己的按钮上。** 厂商名是这一行里唯一占用剩余空间、也是唯一会截断的元素;
+ 给它设最小宽度正是重叠的成因——它旁边那些标记从不收缩,一旦它们的宽度加上这个下限超过按钮,整组内容
+ 就溢出盒子、钻到操作按钮底下。现在下限去掉了,改为在窄行时让模型数量与推荐标记先行退场——这正是那些
+ 操作按钮的文字标签早就遵循的规则。已在 1500px 至 400px 的九个宽度上验证无溢出。
+
+- **按时段的价格会在整点重新读取。** 目录能表达的窗口边界都对齐整点,因此页面把定时器瞄准下一个整点
+ 而不是轮询:否则 08:59 打开的页面到 09:05 还在承诺半价。
+
+## 卡片改造中发现的三个问题
+
+- **模型的显示名称又可以清空了。** 必填的只有 provider 与 model id,输入框也写着「留空则使用 model
+ ID」——但对内建目录收录的模型来说,磁盘上没有 `display_name` 的含义是「继承目录里的名字」,因此清空
+ 等于什么都没写,刚删掉的名字下次加载又回来了。现在用空字符串记录这次删除,读取时把它与「字段缺失」
+ 区分开。目录里没有的模型仍然什么都不写——那里「缺失」本身已经表示「没有名字」。
+- **保存确认会说出它在问哪个模型。** 名称清空后它读作 `确定保存对「」的配置修改?`:回退到 id 的判断
+ 只认 `undefined`,而清空输入框留下的是 `""`。对话框标题栏也有同样的缺口——标题印成空白,下面又把
+ id 重复了一遍。
+- **重新保存不再改动模型的价格。** 表单会把存储的美元价四舍五入到四位小数以便输入,而提交时又把这个
+ 舍入后的值当作新价格写回——于是打开一个促销条目、什么都不动直接确认,它就偏离了卖家实际计费的数字,
+ 标示这一点的折扣标记也随之消失。现在仍然保持着加载值的价格档位会被原样写回;只有真正编辑过该输入框,
+ 键入的值才具有权威性。
+
+## 磁盘上的配置
+
+清空显示名称会往 `.project_config.toml` 写入 `display_name = ""`,这是此前没有任何代码会写的值。不需要
+迁移,存量 Project 也不需要做任何事:没有该字段的配置行为与从前完全一致。旧版本读到新配置时会把空字符串
+当作缺失、重新显示目录里的名字——被清空的名字会重新出现,除此之外没有别的变化。
+
+## 分时段计费的行怎么算
+
+带高峰/空闲时段的行在磁盘上存的是高峰价,而成本中心按**每条用量记录自己的时间戳**判定它属于哪一档,
+而不是按打开页面的那一刻。聚合在计价之前先按档位拆分,因此跨越分界的时间范围会按每次请求真正运行时
+的价格计费,一个已经结束的星期无论什么时候查看都报同一个数。
+
+## 中文价格标签
+
+中文界面中三个价格档位显示为 `缓存命中` / `缓存未命中` / `输出`——包括模型页的价格字段、
+成本中心的 Token 档位与图例,以及 CLI `penguin config model add` 的价格选项。英文标签不变,
+字段名、类型名与协议键名同样不变。
+
+## 存量 Project
+
+预置模型在 Project 创建时复制进 `.project_config.toml`,此后不会被改写,因此上述价格改动
+不会自行到达存量 Project,只能通过模型页的**同步预置**获得:同步会把六个促销中的
+TokenDance 条目下调到实际计费价;修正后的 DeepSeek 牌价同样只有在同步后才会到达存量
+Project。由于价格发生了变化,任何持有目录条目的 Project 都会看到预置更新角标与页面提示,直到它
+同步或忽略为止;而接受这次同步,会改变成本中心为**已经发生的**用量所报告的花费——这些数字一向按
+当前价格计价,而不是按每次请求当时生效的价格计价。默认分组顺序与首次访问展开的分组都只是默认值:拖动过分组标题、或展开/折叠过分组的
+Project 保持自己的排列不变。
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index b0da734d..442f36fa 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -1139,8 +1139,8 @@ const zh: Messages = {
addNoFastMode: "关闭快速模式(缺省即关闭);两者都不给则保留原值",
fastModeUnsupported: (ref: string): string =>
`警告:${ref} 不支持快速模式——AgentHub 为它选用的 client 会拒绝该参数,其请求都会失败。请用 --no-fast-mode 重新执行以关闭。`,
- addPriceCacheRead: "每百万 token 价格:缓存读取(USD)",
- addPriceCacheWrite: "每百万 token 价格:缓存写入(USD)",
+ addPriceCacheRead: "每百万 token 价格:缓存命中(USD)",
+ addPriceCacheWrite: "每百万 token 价格:缓存未命中(USD)",
addPriceOutput: "每百万 token 价格:输出(USD)",
addSetDefault: "同时设为该 Project 的默认模型",
defaultDesc: "设置 Project 的默认模型",
diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.ts
index 5be3b327..a2fb0cc0 100644
--- a/packages/cli/src/render.ts
+++ b/packages/cli/src/render.ts
@@ -151,7 +151,7 @@ function callTag(toolCallId: string, origin?: readonly MessageOrigin[]): string
return origin && origin.length > 0 ? `agent-${shortId(origin[origin.length - 1]!)}-${tid}` : tid;
}
-/** Converts a token count to a human-readable abbreviation: 1234->1.2k, 1500000->1.5M, <1000 unchanged. */
+/** Converts a token count to a human-readable abbreviation: 1234->1.2k, 1500000->1.5M, 2e9->2B, <1000 unchanged. */
export function humanizeTokens(n: number): string {
const abs = Math.abs(n);
if (abs < 1000) return `${n}`;
@@ -159,8 +159,12 @@ export function humanizeTokens(n: number): string {
const v = n / 1000;
return `${trimZero(v)}k`;
}
- const v = n / 1_000_000;
- return `${trimZero(v)}M`;
+ if (abs < 1_000_000_000) {
+ const v = n / 1_000_000;
+ return `${trimZero(v)}M`;
+ }
+ const v = n / 1_000_000_000;
+ return `${trimZero(v)}B`;
}
/** Keeps one decimal place but drops a trailing `.0`. */
diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.ts
index bfae8af5..f5945402 100644
--- a/packages/cli/test/render.test.ts
+++ b/packages/cli/test/render.test.ts
@@ -68,13 +68,17 @@ function usage(req: number, sess: number) {
}
describe("humanizeTokens", () => {
- it("abbreviates with k / M and trims .0", () => {
+ it("abbreviates with k / M / B and trims .0", () => {
expect(humanizeTokens(0)).toBe("0");
expect(humanizeTokens(999)).toBe("999");
expect(humanizeTokens(1000)).toBe("1k");
expect(humanizeTokens(1234)).toBe("1.2k");
expect(humanizeTokens(32000)).toBe("32k");
expect(humanizeTokens(1_500_000)).toBe("1.5M");
+ // A lifetime total reaches this tier; the web formatter it is meant to match already had it.
+ expect(humanizeTokens(999_999_999)).toBe("1000M");
+ expect(humanizeTokens(2_000_000_000)).toBe("2B");
+ expect(humanizeTokens(2_500_000_000)).toBe("2.5B");
});
});
diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.ts
index dc85080b..3d500e7b 100644
--- a/packages/core/src/state/model-catalog.ts
+++ b/packages/core/src/state/model-catalog.ts
@@ -4,9 +4,10 @@
* Data verified as of 2026-07-10 (Qwen Token Plan entries: 2026-07-20; MiniMax: 2026-08-03;
* DeepSeek, Gemini 3.7, GLM-5.3 and the whole OpenAI line-up (direct + OpenRouter):
* 2026-08-18; the direct Anthropic group: 2026-08-20; the DeepSeek V4 Flash Vision Exp rows:
- * 2026-08-21; the TokenDance group: 2026-08-25, its glm-5.3-flash row: 2026-08-26 and its
- * qwen3.8-flash row: 2026-08-27; the GLM-5.3 Flash rows (direct + OpenRouter) and the
- * direct qwen3.8-flash: 2026-08-26 — per each provider's docs).
+ * 2026-08-21; the TokenDance group: 2026-08-25, its glm-5.3-flash row: 2026-08-26, its
+ * qwen3.8-flash row: 2026-08-27 and its running promotions plus the hy4-preview rows
+ * (TokenDance + OpenRouter): 2026-08-28; the GLM-5.3 Flash rows (direct + OpenRouter) and
+ * the direct qwen3.8-flash: 2026-08-26 — per each provider's docs).
* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the
* provider groups and credential resolution described here.
*
@@ -91,6 +92,12 @@ export interface ModelProviderInfo {
* every provider whose keys are only obtainable from its console.
*/
oauth?: ModelProviderOAuth;
+ /**
+ * The group the product recommends, captioned as such on the models page. It marks the
+ * GROUP, not a position: a user who drags the group elsewhere keeps the caption with it,
+ * and the default sequence below is what places it first for everyone else.
+ */
+ recommended?: boolean;
}
/** A single built-in model's catalog entry (`modelId` is the upstream id; paired with `provider` it forms the catalog's unique key). */
@@ -101,6 +108,26 @@ export interface ModelCatalogEntry {
provider: string;
contextWindow?: number;
pricing?: ModelPricing;
+ /**
+ * Fraction off the list price the seller is currently running (0.5 = 50% off), applied to
+ * every bucket. `pricing` stays the LIST price whatever promotion is live, so a lapsed
+ * promotion is one field to delete rather than three numbers to reconstruct;
+ * effectivePricing is the rate actually billed, and presetModelEntries writes THAT into a
+ * Project so the cost center charges what the seller charges.
+ */
+ discount?: number;
+ /**
+ * A discount that is only live outside a weekly set of peak windows — a vendor billing
+ * cheaper off-hours. `pricing` holds the PEAK price, the one billed inside the windows, and
+ * the rate applies everywhere else.
+ *
+ * Unlike `discount`, this one changes twice a day, so it is never baked into a Project:
+ * `presetModelEntries` writes the peak price and the rate is applied when a price is read.
+ * A number on disk that silently meant something different at 09:00 than at 08:00 would be
+ * unreadable, and re-syncing presets would rewrite prices by the clock. Mutually exclusive
+ * with `discount`; an entry declaring both is a catalog error.
+ */
+ offPeakDiscount?: OffPeakDiscount;
/** Whether image input (vision modality) is supported. */
supportsVision: boolean;
/** AgentHub client protocol: required when an id cannot be auto-routed or a shared protocol must be pinned. */
@@ -120,10 +147,14 @@ const TOKENDANCE_BASE_URL = "https://tokendance.space/gateway/v1";
const MINIMAX_BASE_URL = "https://api.minimax.io/v1";
/**
- * Provider list (web model page groups in this order). The sequence is a hand-curated
- * display order: DeepSeek leads as the default model's provider and custom (custom
- * OpenAI-protocol models) is always last; in between, gateways and first-party vendors are
- * interleaved by expected use rather than sorted by kind.
+ * Provider list (web model page groups in this order BY DEFAULT — a user's dragged
+ * arrangement is stored per Project and wins over this sequence; see the web's
+ * model-group-order.ts). The sequence is a hand-curated display order: TokenDance leads as
+ * the recommended group, DeepSeek follows as the default model's provider, and custom
+ * (custom OpenAI-protocol models) is always last; in between, gateways and first-party
+ * vendors are interleaved by expected use rather than sorted by kind. Only this default
+ * moves when the curation changes: a Project that has ever reordered its groups has every
+ * key stored already, so it keeps the arrangement its user built.
*
* The six gateway groups — OpenRouter, Fireworks AI, SiliconFlow, TokenDance, Qwen
* Pay-As-You-Go and Qwen Token Plan — reach their models through one of AgentHub's generic
@@ -133,6 +164,22 @@ const MINIMAX_BASE_URL = "https://api.minimax.io/v1";
* the OPENAI_* pair and the env fallback hint the frontend shows is accurate either way.
*/
export const MODEL_PROVIDERS: ModelProviderInfo[] = [
+ {
+ id: "tokendance",
+ label: "TokenDance",
+ envKey: "OPENAI_API_KEY",
+ envBaseUrlKey: "OPENAI_BASE_URL",
+ apiKeyUrl: "https://tokendance.space/keys",
+ modelsUrl: "https://tokendance.space/models",
+ gatewayBaseUrl: TOKENDANCE_BASE_URL,
+ recommended: true,
+ // https://tokendance.space/docs/api-key-oauth
+ oauth: {
+ authorizeUrl: "https://tokendance.space/auth",
+ exchangeUrl: "https://tokendance.space/portal/api/v1/auth/keys",
+ keyName: "PenguinHarness",
+ },
+ },
{
id: "deepseek",
label: "DeepSeek",
@@ -192,21 +239,6 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [
modelsUrl: "https://cloud.siliconflow.cn/models",
gatewayBaseUrl: SILICONFLOW_BASE_URL,
},
- {
- id: "tokendance",
- label: "TokenDance",
- envKey: "OPENAI_API_KEY",
- envBaseUrlKey: "OPENAI_BASE_URL",
- apiKeyUrl: "https://tokendance.space/keys",
- modelsUrl: "https://tokendance.space/models",
- gatewayBaseUrl: TOKENDANCE_BASE_URL,
- // https://tokendance.space/docs/api-key-oauth
- oauth: {
- authorizeUrl: "https://tokendance.space/auth",
- exchangeUrl: "https://tokendance.space/portal/api/v1/auth/keys",
- keyName: "PenguinHarness",
- },
- },
{
id: "zhipu",
label: "Z.AI (GLM)",
@@ -270,25 +302,136 @@ function usd(cacheRead: number, cacheWrite: number, output: number): ModelPricin
return { unit: "usd_per_mtok", cache_read: cacheRead, cache_write: cacheWrite, output };
}
+/**
+ * A weekly peak/off-peak billing schedule, written in a fixed-offset zone.
+ *
+ * Only fixed offsets are expressible, which is the whole of what the catalog needs: the vendors
+ * that bill this way publish their windows in a single national zone that does not observe DST
+ * (Beijing is UTC+8 year round). A vendor on a DST zone would need a real tz database, and the
+ * honest move then is to add one rather than to approximate.
+ */
+export interface OffPeakDiscount {
+ /** Fraction off the peak price outside the windows below (0.5 = half price). */
+ rate: number;
+ /** Minutes east of UTC the windows are written in (Beijing = 480). */
+ utcOffsetMinutes: number;
+ /** Days the windows apply to, ISO numbering: 1 = Monday … 7 = Sunday. Days not listed are off-peak all day. */
+ peakDays: readonly number[];
+ /** Peak windows as [startHour, endHour) in the zone's local hours — end-exclusive, so 12:00 is already off-peak. */
+ peakHours: readonly (readonly [number, number])[];
+}
+
+/**
+ * Whether `now` falls outside every peak window, i.e. whether the discount is live.
+ *
+ * Computed in UTC arithmetic rather than through the host's local time: the schedule belongs to
+ * the vendor's zone, and a server in Los Angeles must reach the same answer as one in Shanghai.
+ */
+export function offPeakAt(schedule: OffPeakDiscount, now: Date): boolean {
+ const local = new Date(now.getTime() + schedule.utcOffsetMinutes * 60_000);
+ // getUTCDay is 0 = Sunday; the ISO numbering the schedule uses puts Sunday at 7.
+ const isoDay = local.getUTCDay() === 0 ? 7 : local.getUTCDay();
+ if (!schedule.peakDays.includes(isoDay)) return true;
+ const hour = local.getUTCHours() + local.getUTCMinutes() / 60;
+ return !schedule.peakHours.some(([from, to]) => hour >= from && hour < to);
+}
+
+/** DeepSeek's official off-peak tier: half price outside Beijing weekday 09:00–12:00 and 14:00–18:00. */
+export const DEEPSEEK_OFF_PEAK: OffPeakDiscount = {
+ rate: 0.5,
+ utcOffsetMinutes: 480,
+ peakDays: [1, 2, 3, 4, 5],
+ peakHours: [
+ [9, 12],
+ [14, 18],
+ ],
+};
+
+/**
+ * The catalog's time-based schedules, each with the references that carry it.
+ *
+ * The cost center needs this to split an aggregation by tier before it prices anything: the
+ * rate a request ran at is a fact about when it ran, and only the catalog knows which rows have
+ * two rates at all. Grouped by schedule so a second vendor's windows cost one entry, not a
+ * second query.
+ */
+export function offPeakScheduledRefs(): Array<{
+ schedule: OffPeakDiscount;
+ refs: Array<{ provider: string; modelId: string }>;
+}> {
+ const bySchedule = new Map<
+ OffPeakDiscount,
+ { schedule: OffPeakDiscount; refs: Array<{ provider: string; modelId: string }> }
+ >();
+ for (const entry of MODEL_CATALOG) {
+ const schedule = entry.offPeakDiscount;
+ if (schedule === undefined) continue;
+ const group = bySchedule.get(schedule) ?? { schedule, refs: [] };
+ group.refs.push({ provider: entry.provider, modelId: entry.modelId });
+ bySchedule.set(schedule, group);
+ }
+ return [...bySchedule.values()];
+}
+
+/**
+ * What the seller actually bills for an entry: its list `pricing` less any running `discount`,
+ * on every bucket. Rounded to the six decimals cny() already stores at, so a promotional rate is
+ * written into a Project as a price rather than as a float artifact. An entry with no discount
+ * (or no pricing at all) is returned untouched.
+ *
+ * A row on a SCHEDULE is a deliberate exception: `presetModelEntries` writes its peak price,
+ * because which tier a request ran in is decided from that request's own timestamp when the
+ * usage is aggregated, not from what a Project happened to store.
+ */
+export function effectivePricing(
+ entry: ModelCatalogEntry,
+ now: Date = new Date(),
+): ModelPricing | undefined {
+ const { pricing } = entry;
+ if (pricing === undefined) return pricing;
+ // A scheduled discount bills the list price during its peak windows and the reduced rate
+ // outside them; a flat one always bills the reduced rate.
+ const rate =
+ entry.offPeakDiscount !== undefined
+ ? offPeakAt(entry.offPeakDiscount, now)
+ ? entry.offPeakDiscount.rate
+ : 0
+ : entry.discount;
+ if (rate === undefined || rate === 0) return pricing;
+ const off = (v: number): number => Math.round(v * (1 - rate) * 1e6) / 1e6;
+ return {
+ unit: pricing.unit,
+ cache_read: off(pricing.cache_read),
+ cache_write: off(pricing.cache_write),
+ output: off(pricing.output),
+ };
+}
+
/**
* Built-in model catalog, clustered by provider. Within each provider, entries are in
* dictionary order by model id, except that newer versions of the same series come first
* (e.g. gpt-5.6-* before gpt-5.5, claude-opus-4.8 before 4.7, glm-5.2 before glm-5). The
* order is precomputed by hand right here — no runtime sorting anywhere.
+ *
+ * The clusters run in their own sequence, which is the row order a new Project's
+ * `[[models]]` table is written in. It is not MODEL_PROVIDERS' display order and does not
+ * have to track it: nothing renders a catalog row outside its provider group, and the page
+ * takes the group sequence from MODEL_PROVIDERS.
*/
export const MODEL_CATALOG: ModelCatalogEntry[] = [
// -- DeepSeek (official CNY pricing: cache hit / cache miss / output). Re-read 2026-08-18
// from api-docs.deepseek.com/quick_start/pricing after the official price increase
- // introduced time-based tiers: the rows store the OFF-PEAK tier (the lower published
- // price, issue #313's display choice); peak hours (Beijing 9:00-12:00 and 14:00-18:00)
- // bill exactly double every bucket, so peak usage is underestimated 2x (same single-rate
- // limitation as the long-context surcharges in the file header). --
+ // introduced time-based tiers. The rows store the PEAK tier and declare
+ // DEEPSEEK_OFF_PEAK, which halves every bucket outside Beijing weekday 09:00-12:00 and
+ // 14:00-18:00 — so both tiers are billed at the rate actually in force, rather than one of
+ // them being approximated by the other. --
{
modelId: "deepseek-v4-flash",
displayName: "DeepSeek V4 Flash",
provider: "deepseek",
contextWindow: 1000000,
- pricing: cny(0.05, 1.5, 4.5),
+ pricing: cny(0.1, 3, 9),
+ offPeakDiscount: DEEPSEEK_OFF_PEAK,
supportsVision: false,
},
{
@@ -298,7 +441,8 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
displayName: "DeepSeek V4 Flash Vision Exp",
provider: "deepseek",
contextWindow: 1000000,
- pricing: cny(0.05, 1.5, 4.5),
+ pricing: cny(0.1, 3, 9),
+ offPeakDiscount: DEEPSEEK_OFF_PEAK,
supportsVision: true,
},
{
@@ -306,7 +450,8 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
displayName: "DeepSeek V4 Pro",
provider: "deepseek",
contextWindow: 1000000,
- pricing: cny(0.15, 4.5, 13.5),
+ pricing: cny(0.3, 9, 27),
+ offPeakDiscount: DEEPSEEK_OFF_PEAK,
supportsVision: false,
},
// -- OpenRouter (gateway: OpenAI-compatible protocol, preset base URL). Prices re-read in
@@ -692,6 +837,21 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
clientType: "openai-chat",
baseUrl: OPENROUTER_BASE_URL,
},
+ {
+ // Tencent's Hy4 preview, read 2026-08-28 from its OpenRouter page and the models API:
+ // $0.834 input / $2.501 output with a published $0.042 input_cache_read, a 1,048,576
+ // context window, and text-only modalities in and out. The same upstream model is sold
+ // in the TokenDance group at that gateway's own CNY rate; the two rows are priced by
+ // their sellers and are not copies of one another.
+ modelId: "tencent/hy4-preview",
+ displayName: "Hy4 preview",
+ provider: "openrouter",
+ contextWindow: 1048576,
+ pricing: usd(0.042, 0.834, 2.501),
+ supportsVision: false,
+ clientType: "openai-chat",
+ baseUrl: OPENROUTER_BASE_URL,
+ },
{
modelId: "tencent/hy3",
displayName: "Hy3",
@@ -945,28 +1105,35 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
clientType: "openai-chat",
baseUrl: SILICONFLOW_BASE_URL,
},
- // -- TokenDance (gateway: OpenAI-compatible protocol, preset base URL). Context windows and
- // vision flags from the public catalog API (GET https://tokendance.space/gateway/v1/models,
- // no credential required); prices are the gateway's own CNY rates from each model's detail
- // page, read 2026-08-25 (the detail pages need a signed-in session, so they cannot be
- // re-read anonymously). TokenDance publishes an input price and a cache-hit price with no
- // separate cache-write fee, so cache_write carries the input price.
+ // -- TokenDance (gateway: OpenAI-compatible protocol, preset base URL). Context windows,
+ // vision flags and supported protocols from the public catalog API (GET
+ // https://tokendance.space/gateway/v1/models, no credential required; re-read 2026-08-28);
+ // prices are the gateway's own CNY rates from each model's detail page, read 2026-08-25
+ // (the detail pages need a signed-in session, so they cannot be re-read anonymously).
+ // TokenDance publishes an input price and a cache-hit price with no separate cache-write
+ // fee, so cache_write carries the input price.
//
// Discounts: every row here stores the official LIST price, the convention of the two Qwen
- // groups below. Two promotions are running, so the group currently over-states what those
- // two rows really cost: glm-5.3-flash is on a 2-week 50% off (running at the 2026-08-26
- // read, so it ends by 2026-09-09 at the latest — 2x the billed rate until then), and
- // qwen3.8-max on a limited-time 20% off with no published end date (1.25x). Both are
- // machine-checkable without a credential: the catalog API opens a discounted model's
- // `description` with a bracketed 限时 ("limited-time") tag naming the rate, so the same
- // anonymous request the context windows come from also says which promotions still run.
- // No other row is discounted, so list price and billed rate coincide for the rest. --
+ // groups below, and a promoted row declares its rate in `discount` rather than having its
+ // price rewritten — a promotion that lapses is then one field to delete, with the rate to
+ // return to still on the row. effectivePricing() applies it and presetModelEntries writes
+ // that billed rate into a Project, so the cost center charges what the gateway charges.
+ // Six rows are promoted: deepseek-v4-flash-0731, deepseek-v4-pro-0813 and glm-5.3-flash at
+ // 50% off, kimi-k3 at 20%, glm-5.3 and qwen3.8-max at 10%. The rest carry no discount, so
+ // for them list price and billed rate coincide.
+ //
+ // A running promotion usually also shows up without a credential: the catalog API opens
+ // such a model's `description` with a bracketed 限时 ("limited-time") tag, so the same
+ // anonymous request the context windows come from is a cheap first check on whether one is
+ // still live. It is neither exhaustive nor authoritative on the rate — the rates above are
+ // the ones the seller confirmed. --
{
modelId: "deepseek-v4-flash-0731",
displayName: "DeepSeek V4 Flash 0731",
provider: "tokendance",
contextWindow: 1048576,
- pricing: cny(0.05, 1.5, 4.5),
+ pricing: cny(0.1, 3, 9),
+ discount: 0.5,
supportsVision: false,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
@@ -986,7 +1153,8 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
displayName: "DeepSeek V4 Pro 0813",
provider: "tokendance",
contextWindow: 1000000,
- pricing: cny(0.15, 4.5, 13.5),
+ pricing: cny(0.3, 9, 27),
+ discount: 0.5,
supportsVision: false,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
@@ -997,6 +1165,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
provider: "tokendance",
contextWindow: 1000000,
pricing: cny(2, 8, 28),
+ discount: 0.1,
supportsVision: false,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
@@ -1011,16 +1180,38 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
provider: "tokendance",
contextWindow: 1000000,
pricing: cny(0.23, 0.8, 2.8),
+ discount: 0.5,
supportsVision: true,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
},
+ {
+ // The same upstream model as the OpenRouter `tencent/hy4-preview` row above, reached
+ // through a second seller: each row records what its own seller charges, so the two must
+ // not be made to agree (the qwen3.8-flash pair below states the same rule). TokenDance
+ // sells it at CNY 6 input / 18 output / 0.3 cache hit, undiscounted, over a 1,024,000
+ // context window — both figures its own, neither copied from the OpenRouter listing.
+ //
+ // Text-only: the catalog entry advertises no image modality, matching the OpenRouter
+ // listing's text-in/text-out. Its supported_protocols are openai:chat-completions and
+ // openai:responses, so the openai-chat pin is this group's convention rather than the
+ // only shape the id serves — unlike glm-5.3-flash above, where it is forced.
+ modelId: "hy4-preview",
+ displayName: "Hy4 preview",
+ provider: "tokendance",
+ contextWindow: 1024000,
+ pricing: cny(0.3, 6, 18),
+ supportsVision: false,
+ clientType: "openai-chat",
+ baseUrl: TOKENDANCE_BASE_URL,
+ },
{
modelId: "kimi-k3",
displayName: "Kimi K3",
provider: "tokendance",
contextWindow: 1048576,
pricing: cny(2, 20, 100),
+ discount: 0.2,
supportsVision: true,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
@@ -1036,8 +1227,8 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
// it is forced. Natively multimodal per the catalog entry, and this group's openai-chat
// client forwards image_url parts, so image input works on this path.
//
- // Not discounted: unlike qwen3.8-max below, its catalog `description` carries no
- // bracketed 限时 tag, so list price and billed rate coincide.
+ // Undiscounted, so its list price and its billed rate coincide — unlike the
+ // qwen3.8-max row below, which is on 10% off.
modelId: "qwen3.8-flash",
displayName: "Qwen 3.8 Flash",
provider: "tokendance",
@@ -1053,6 +1244,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
provider: "tokendance",
contextWindow: 1000000,
pricing: cny(1.5, 12, 36),
+ discount: 0.1,
supportsVision: true,
clientType: "openai-chat",
baseUrl: TOKENDANCE_BASE_URL,
@@ -1636,20 +1828,32 @@ export function fastModeProtocol(
* always pin a client_type — openai-chat, or openai-responses for the OpenRouter openai/*
* rows — and inline a preset base_url. The direct MiniMax M3 entry also pins its protocol and
* endpoint. No secrets are included, so only an API key is needed.
+ *
+ * Pricing is written as the EFFECTIVE rate (effectivePricing: list less any running
+ * discount), not the list price the catalog records. A Project's stored pricing is the only
+ * thing the cost center ever prices against, so writing anything but what the seller bills
+ * would report a cost nobody was charged; the list price and the promotion that produced the
+ * difference stay in the catalog, where they can be read and restored.
*/
export function presetModelEntries(): ModelEntry[] {
- return MODEL_CATALOG.map((m) => ({
- provider: m.provider,
- model_id: m.modelId,
- ...(m.contextWindow !== undefined ? { context_window: m.contextWindow } : {}),
- ...(m.clientType !== undefined ? { client_type: m.clientType } : {}),
- ...(m.pricing ? { pricing: { ...m.pricing } } : {}),
- // ModelEntry.vision defaults to supported: only models that don't support images
- // explicitly persist false (drives the read_image / describe_image choice and input
- // image hand-off, see project-config.ts).
- ...(m.supportsVision ? {} : { vision: false }),
- ...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),
- }));
+ return MODEL_CATALOG.map((m) => {
+ // A scheduled discount writes the PEAK price, which is the same number whatever hour the
+ // Project is created or re-synced in. What is on disk has to be stable: the off-peak rate
+ // is applied when the price is read, by the models page and by the cost center alike.
+ const pricing = m.offPeakDiscount !== undefined ? m.pricing : effectivePricing(m);
+ return {
+ provider: m.provider,
+ model_id: m.modelId,
+ ...(m.contextWindow !== undefined ? { context_window: m.contextWindow } : {}),
+ ...(m.clientType !== undefined ? { client_type: m.clientType } : {}),
+ ...(pricing ? { pricing: { ...pricing } } : {}),
+ // ModelEntry.vision defaults to supported: only models that don't support images
+ // explicitly persist false (drives the read_image / describe_image choice and input
+ // image hand-off, see project-config.ts).
+ ...(m.supportsVision ? {} : { vision: false }),
+ ...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),
+ };
+ });
}
/**
diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.ts
index 6e6925ec..610eb88a 100644
--- a/packages/core/test/model-catalog.test.ts
+++ b/packages/core/test/model-catalog.test.ts
@@ -11,6 +11,9 @@ import {
modelHomepageUrl,
catalogEntryFor,
attributionHeaders,
+ effectivePricing,
+ offPeakAt,
+ DEEPSEEK_OFF_PEAK,
presetModelEntries,
providerInfo,
fastModeProtocol,
@@ -26,9 +29,12 @@ describe("model-catalog", () => {
expect(new Set(pairs).size).toBe(pairs.length);
const ids = MODEL_CATALOG.map((m) => m.modelId);
expect(MODEL_CATALOG[0]!.provider).toBe("deepseek");
- // Group order is hand-curated, interleaving gateways and first-party vendors: DeepSeek
- // first (the default model's provider) and custom always last.
+ // Group order is hand-curated, interleaving gateways and first-party vendors: TokenDance
+ // first (the recommended group), DeepSeek next (the default model's provider) and custom
+ // always last. This is the page's DEFAULT only — a Project that has reordered its groups
+ // stores every key and keeps its own arrangement (web's model-group-order.ts).
expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual([
+ "tokendance",
"deepseek",
"openrouter",
"fireworks",
@@ -36,7 +42,6 @@ describe("model-catalog", () => {
"openai",
"anthropic",
"siliconflow",
- "tokendance",
"zhipu",
"moonshot",
"minimax",
@@ -44,6 +49,10 @@ describe("model-catalog", () => {
"qwen-token-plan",
"custom",
]);
+ // Exactly one group is marked recommended, and it is the one that leads the default
+ // order: the caption and the placement are two statements of the same curation.
+ expect(MODEL_PROVIDERS.filter((p) => p.recommended).map((p) => p.id)).toEqual(["tokendance"]);
+ expect(MODEL_PROVIDERS[0]!.recommended).toBe(true);
expect(providerInfo("siliconflow")!.label).toBe("SiliconFlow");
expect(providerInfo("minimax")!.label).toBe("MiniMax");
expect(providerInfo("minimax")!.envKey).toBe("MINIMAX_API_KEY");
@@ -170,7 +179,14 @@ describe("model-catalog", () => {
expect(entry.provider).toBe(cat.provider);
expect(entry.model_id).toBe(cat.modelId);
expect(entry.context_window).toBe(cat.contextWindow);
- expect(entry.pricing).toEqual(cat.pricing);
+ // A Project stores the BILLED rate, not the catalog's list price: the cost center
+ // prices only against what is written here, so a promoted row must arrive discounted.
+ // The exception is a row on a peak/off-peak schedule, which stores the PEAK price: the
+ // rate changes twice a day, so baking one in would make the number on disk depend on the
+ // hour the Project happened to be created or re-synced in.
+ expect(entry.pricing, entry.model_id).toEqual(
+ cat.offPeakDiscount !== undefined ? cat.pricing : effectivePricing(cat),
+ );
expect(entry.vision).toBe(cat.supportsVision ? undefined : false);
// Gateway and direct MiniMax presets pin a client protocol; other direct models auto-route.
expect(entry.client_type).toBe(cat.clientType);
@@ -218,6 +234,7 @@ describe("model-catalog", () => {
"qwen/qwen3.8-max",
"qwen/qwen3.6-35b-a3b",
"stepfun/step-3.7-flash",
+ "tencent/hy4-preview",
"tencent/hy3",
"thinkingmachines/inkling",
"x-ai/grok-4.6",
@@ -302,6 +319,7 @@ describe("model-catalog", () => {
["deepseek-v4-pro-0813", 1000000, false],
["glm-5.3", 1000000, false],
["glm-5.3-flash", 1000000, true],
+ ["hy4-preview", 1024000, false],
["kimi-k3", 1048576, true],
["qwen3.8-flash", 1000000, true],
["qwen3.8-max", 1000000, true],
@@ -310,15 +328,54 @@ describe("model-catalog", () => {
expect(m.clientType).toBe("openai-chat");
expect(m.baseUrl).toBe("https://tokendance.space/gateway/v1");
}
- // The gateway's own CNY LIST rates throughout, promotion or not: qwen3.8-max at
- // 1.5 / 12 / 36 CNY while a 20% off runs, glm-5.3-flash at 0.23 / 0.8 / 2.8 CNY while a
- // 50% off runs; no other row carries a promotion, so list price and billed rate coincide
- // for the rest.
+ // The gateway's own CNY LIST rates throughout, promotion or not; a promoted row carries
+ // its rate in `discount` and the billed price is DERIVED from the two, never pasted
+ // beside them. Reading the CNY prices back out of effectivePricing is what pins that:
+ // change a list price or a discount alone and the recovered rate stops matching what
+ // TokenDance publishes. cache_write carries the input price (no separate cache-write fee
+ // on this gateway), so the published input / output / cache-hit triple is NOT in the
+ // catalog's cny(cacheRead, cacheWrite, output) argument order.
+ const CNY_PER_USD = 7;
+ const billedCny = (modelId: string): [number, number, number] => {
+ const billed = effectivePricing(td.find((m) => m.modelId === modelId)!)!;
+ // input, output, cache hit — the order TokenDance's own price list uses.
+ return [
+ billed.cache_write * CNY_PER_USD,
+ billed.output * CNY_PER_USD,
+ billed.cache_read * CNY_PER_USD,
+ ];
+ };
+ const discounted: Array<[string, number, [number, number, number]]> = [
+ ["glm-5.3-flash", 0.5, [0.4, 1.4, 0.115]],
+ ["glm-5.3", 0.1, [7.2, 25.2, 1.8]],
+ ["deepseek-v4-pro-0813", 0.5, [4.5, 13.5, 0.15]],
+ ["deepseek-v4-flash-0731", 0.5, [1.5, 4.5, 0.05]],
+ ["kimi-k3", 0.2, [16, 80, 1.6]],
+ ["qwen3.8-max", 0.1, [10.8, 32.4, 1.35]],
+ ];
+ for (const [modelId, discount, cnyBilled] of discounted) {
+ const entry = td.find((m) => m.modelId === modelId)!;
+ expect(entry.discount, modelId).toBe(discount);
+ const [input, output, cacheHit] = billedCny(modelId);
+ expect(input, `${modelId} input`).toBeCloseTo(cnyBilled[0], 4);
+ expect(output, `${modelId} output`).toBeCloseTo(cnyBilled[1], 4);
+ expect(cacheHit, `${modelId} cache hit`).toBeCloseTo(cnyBilled[2], 4);
+ }
+ // Exactly those six are promoted; every other row bills its list price unchanged.
+ expect(
+ td
+ .filter((m) => m.discount !== undefined)
+ .map((m) => m.modelId)
+ .sort(),
+ ).toEqual(discounted.map(([id]) => id).sort());
+ for (const m of td.filter((x) => x.discount === undefined)) {
+ expect(effectivePricing(m), m.modelId).toEqual(m.pricing);
+ }
+ // The stored list prices themselves, in the catalog's own argument order.
const tdQwen = td.find((m) => m.modelId === "qwen3.8-max")!.pricing!;
expect([tdQwen.cache_read, tdQwen.cache_write, tdQwen.output]).toEqual([
0.214286, 1.714286, 5.142857,
]);
- // cache_write carries the input price: TokenDance charges no separate cache-write fee.
const tdFlash = td.find((m) => m.modelId === "glm-5.3-flash")!.pricing!;
expect([tdFlash.cache_read, tdFlash.cache_write, tdFlash.output]).toEqual([
0.032857, 0.114286, 0.4,
@@ -337,6 +394,25 @@ describe("model-catalog", () => {
expect(payggFlash.cache_write).toBeGreaterThan(tdQwenFlash.cache_write);
expect(payggFlash.output).toBeGreaterThan(tdQwenFlash.output);
expect(payggFlash.cache_read).toEqual(tdQwenFlash.cache_read);
+ // hy4-preview is the same upstream model as OpenRouter's tencent/hy4-preview, sold twice.
+ // Same rule as the qwen3.8-flash pair: each row carries its own seller's price and its own
+ // published context window, so the two must stay apart rather than converge on one number.
+ const tdHy4 = td.find((m) => m.modelId === "hy4-preview")!;
+ expect(tdHy4.discount).toBeUndefined();
+ expect(billedCny("hy4-preview")[0]).toBeCloseTo(6, 4);
+ expect(billedCny("hy4-preview")[1]).toBeCloseTo(18, 4);
+ expect(billedCny("hy4-preview")[2]).toBeCloseTo(0.3, 4);
+ const orHy4 = catalogEntryFor("openrouter", "tencent/hy4-preview")!;
+ expect([orHy4.pricing!.cache_read, orHy4.pricing!.cache_write, orHy4.pricing!.output]).toEqual([
+ 0.042, 0.834, 2.501,
+ ]);
+ expect(tdHy4.pricing!.cache_write).toBeGreaterThan(orHy4.pricing!.cache_write);
+ expect(tdHy4.pricing!.output).toBeGreaterThan(orHy4.pricing!.output);
+ expect(tdHy4.pricing!.cache_read).toBeGreaterThan(orHy4.pricing!.cache_read);
+ expect(tdHy4.contextWindow).not.toBe(orHy4.contextWindow);
+ // Text-only on both sellers, and neither is on a promotion.
+ expect([tdHy4.supportsVision, orHy4.supportsVision]).toEqual([false, false]);
+ expect(orHy4.discount).toBeUndefined();
const qpayg = MODEL_CATALOG.filter((m) => m.provider === "qwen-pay-as-you-go");
expect(qpayg.map((m) => [m.modelId, m.supportsVision])).toEqual([
["deepseek-v4-flash-0731", false],
@@ -621,15 +697,16 @@ describe("model-catalog", () => {
it("DeepSeek and Kimi are initialized from official CNY prices (stored in USD; x7 recovers the official price)", () => {
const cnyOf = (usdV: number) => Math.round(usdV * 7 * 1000) / 1000;
- // DeepSeek rows carry the official OFF-PEAK tier (the lower published price; peak hours
- // bill double) — re-read 2026-08-18 after the official price increase (issue #313).
+ // DeepSeek rows carry the official PEAK tier — re-read 2026-08-18 after the official price
+ // increase introduced time-based tiers. The off-peak tier is exactly half, and is applied
+ // from the row's schedule rather than stored (see the off-peak schedules block below).
const flash = catalogEntryFor("deepseek", "deepseek-v4-flash")!.pricing!;
expect([cnyOf(flash.cache_read), cnyOf(flash.cache_write), cnyOf(flash.output)]).toEqual([
- 0.05, 1.5, 4.5,
+ 0.1, 3, 9,
]);
const pro = catalogEntryFor("deepseek", "deepseek-v4-pro")!.pricing!;
expect([cnyOf(pro.cache_read), cnyOf(pro.cache_write), cnyOf(pro.output)]).toEqual([
- 0.15, 4.5, 13.5,
+ 0.3, 9, 27,
]);
const k3 = MODEL_CATALOG.find(
(m) => m.provider === "moonshot" && m.modelId === "kimi-k3",
@@ -1015,3 +1092,82 @@ describe("attributionHeaders (how the harness names itself to the gateways that
}
});
});
+
+describe("off-peak schedules", () => {
+ const S = DEEPSEEK_OFF_PEAK;
+ /** Beijing is UTC+8 with no DST, so a Beijing wall clock is the UTC one minus 8 hours. */
+ const beijing = (iso: string): Date => new Date(`${iso}+08:00`);
+
+ it("the DeepSeek rows store the peak price and declare the schedule", () => {
+ const rows = MODEL_CATALOG.filter((m) => m.provider === "deepseek");
+ expect(rows.length).toBeGreaterThan(0);
+ for (const m of rows) {
+ expect(m.offPeakDiscount, m.modelId).toBe(S);
+ // Peak is exactly double the off-peak tier DeepSeek publishes. Compared at 1e-5: both
+ // sides round to six decimals independently, so the last digit can differ by one.
+ expect(effectivePricing(m, beijing("2026-08-31T22:00"))!.output * 2).toBeCloseTo(
+ m.pricing!.output,
+ 5,
+ );
+ }
+ // The published peak figures themselves: CNY 0.1 / 3 / 9 per million, at the catalog's 7:1
+ // display convention, which is DeepSeek's off-peak 0.05 / 1.5 / 4.5 doubled.
+ const flash = MODEL_CATALOG.find((m) => m.modelId === "deepseek-v4-flash")!.pricing!;
+ expect([flash.cache_read, flash.cache_write, flash.output]).toEqual([
+ 0.014286, 0.428571, 1.285714,
+ ]);
+ });
+
+ it("peak is Monday to Friday, 09:00-12:00 and 14:00-18:00 Beijing", () => {
+ // 2026-08-31 is a Monday.
+ expect(offPeakAt(S, beijing("2026-08-31T09:00"))).toBe(false);
+ expect(offPeakAt(S, beijing("2026-08-31T11:59"))).toBe(false);
+ expect(offPeakAt(S, beijing("2026-08-31T14:00"))).toBe(false);
+ expect(offPeakAt(S, beijing("2026-08-31T17:59"))).toBe(false);
+ // Outside them, including the lunch gap and both ends of the day.
+ expect(offPeakAt(S, beijing("2026-08-31T08:59"))).toBe(true);
+ expect(offPeakAt(S, beijing("2026-08-31T13:00"))).toBe(true);
+ expect(offPeakAt(S, beijing("2026-08-31T18:00"))).toBe(true);
+ expect(offPeakAt(S, beijing("2026-08-31T03:00"))).toBe(true);
+ // The window ends are exclusive, so noon and 18:00 are already off-peak.
+ expect(offPeakAt(S, beijing("2026-08-31T12:00"))).toBe(true);
+ });
+
+ it("weekends are off-peak all day", () => {
+ // 2026-09-05 is a Saturday, 2026-09-06 a Sunday — the ISO day 7 the schedule must not
+ // confuse with getUTCDay's 0.
+ expect(offPeakAt(S, beijing("2026-09-05T10:00"))).toBe(true);
+ expect(offPeakAt(S, beijing("2026-09-06T10:00"))).toBe(true);
+ expect(offPeakAt(S, beijing("2026-09-07T10:00"))).toBe(false);
+ });
+
+ it("the answer is the vendor's clock, not the host's", () => {
+ // One instant, asked in two ways: 01:30 UTC is 09:30 in Beijing, i.e. peak, whatever zone
+ // the server runs in. The Date is absolute, so this pins that no local-time call is used.
+ expect(offPeakAt(S, new Date("2026-08-31T01:30:00Z"))).toBe(false);
+ expect(offPeakAt(S, new Date("2026-08-31T16:30:00Z"))).toBe(true);
+ });
+
+ it("effectivePricing halves every bucket off-peak and leaves them at peak", () => {
+ const m = MODEL_CATALOG.find((x) => x.modelId === "deepseek-v4-pro")!;
+ expect(effectivePricing(m, beijing("2026-08-31T10:00"))).toEqual(m.pricing);
+ const off = effectivePricing(m, beijing("2026-08-31T20:00"))!;
+ for (const k of ["cache_read", "cache_write", "output"] as const) {
+ expect(off[k], k).toBeCloseTo(m.pricing![k] / 2, 5);
+ }
+ // And the concrete off-peak figures, which are DeepSeek's published CNY 0.15 / 4.5 / 13.5.
+ const cnyOf = (usdV: number): number => Math.round(usdV * 7 * 1000) / 1000;
+ expect([cnyOf(off.cache_read), cnyOf(off.cache_write), cnyOf(off.output)]).toEqual([
+ 0.15, 4.5, 13.5,
+ ]);
+ });
+ it("no entry declares both a flat discount and a schedule", () => {
+ // effectivePricing, discountedPrice and presetModelEntries all silently prefer the schedule,
+ // so a row declaring both would be billed at its list price during peak with nothing failing.
+ // The rule is stated in the field's doc; this is what makes it true.
+ const both = MODEL_CATALOG.filter(
+ (m) => m.discount !== undefined && m.offPeakDiscount !== undefined,
+ ).map((m) => `${m.provider}/${m.modelId}`);
+ expect(both).toEqual([]);
+ });
+});
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index a6a7c10d..d4958d63 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -55,10 +55,11 @@ For a model tagged `vision = false` (e.g. `deepseek-v4-flash`, the text-only sib
## Built-in provider groups
-Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/state/model-catalog.ts`); each group also has a `_BASE_URL` variant (e.g. `ANTHROPIC_BASE_URL`):
+Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/state/model-catalog.ts`); each group also has a `_BASE_URL` variant (e.g. `ANTHROPIC_BASE_URL`). The models page lists the groups in this order by default and opens the first one; drag a group header to arrange them yourself, and that arrangement is stored per Project and is what you see from then on.
| Provider | API key env var | Notes |
| --- | --- | --- |
+| tokendance | `OPENAI_API_KEY` | The recommended group, listed first by default. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |
| deepseek | `DEEPSEEK_API_KEY` | Group of the default model |
| openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` |
| fireworks | `OPENAI_API_KEY` | Fireworks AI (OpenAI-compatible), preset base URL `https://api.fireworks.ai/inference/v1`; API model ids look like `accounts/fireworks/models/<slug>` |
@@ -66,7 +67,6 @@ Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/
| openai | `OPENAI_API_KEY` | |
| anthropic | `ANTHROPIC_API_KEY` | |
| siliconflow | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://api.siliconflow.cn/v1` |
-| tokendance | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates |
| zhipu | `ZAI_API_KEY` | |
| moonshot | `MOONSHOT_API_KEY` | |
| minimax | `MINIMAX_API_KEY` | Direct MiniMax M3 Responses client (`client_type = "minimax-m3"`): `MiniMax-M3` with a 1,000,000-token context window and vision; preset base URL `https://api.minimax.io/v1`; accepts a Token Plan Subscription Key or pay-as-you-go API key |
@@ -78,7 +78,9 @@ The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay
The preset catalog also carries OpenRouter's free tier: the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but are subject to OpenRouter's free-tier rate limits and data policy.
-Some models in the preset catalog: deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (the DeepSeek group's only vision-capable model), MiniMax-M3, gemini-3.7-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group prices record the official off-peak tier (peak hours, Beijing 9:00–12:00 and 14:00–18:00, bill double). `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price — the direct row records Z.AI's list price, the TokenDance row TokenDance's, and the OpenRouter row the discounted rate that gateway bills, so they disagree while a promotion is running.
+Some models in the preset catalog: deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (the DeepSeek group's only vision-capable model), MiniMax-M3, gemini-3.7-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `-50%` tag and the cost center bills at. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.
+
+TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Six models are discounted today — `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813` and `glm-5.3-flash` at 50% off, `kimi-k3` at 20%, `glm-5.3` and `qwen3.8-max` at 10%. Their model cards show the price being billed right now, with the rate as a badge, and a Project is preset with the **discounted** price, so the cost center charges what the gateway charges. Prices you edit yourself keep the discount decoration off the card: the figure is then yours, not the gateway's.
## App attribution
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index dae98d6b..aca4dec8 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -55,10 +55,11 @@ api_key = "sk-..."
## 内置 Provider 分组
-内置分组及其环境变量回退(目录源:`packages/core/src/state/model-catalog.ts`);每个分组同时存在 `_BASE_URL` 变体(如 `ANTHROPIC_BASE_URL`):
+内置分组及其环境变量回退(目录源:`packages/core/src/state/model-catalog.ts`);每个分组同时存在 `_BASE_URL` 变体(如 `ANTHROPIC_BASE_URL`)。模型页默认按此顺序排列分组并展开第一个;拖动分组标题即可自行调整,该排列按 Project 保存,此后一直生效。
| Provider | API Key 环境变量 | 说明 |
| --- | --- | --- |
+| tokendance | `OPENAI_API_KEY` | 官方推荐分组,默认排在首位。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价,其中若干条目当前处于折扣中 |
| deepseek | `DEEPSEEK_API_KEY` | 默认模型所在分组 |
| openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` |
| fireworks | `OPENAI_API_KEY` | Fireworks AI(OpenAI 兼容),预置 base URL `https://api.fireworks.ai/inference/v1`;API 模型 id 形如 `accounts/fireworks/models/<slug>` |
@@ -66,7 +67,6 @@ api_key = "sk-..."
| openai | `OPENAI_API_KEY` | |
| anthropic | `ANTHROPIC_API_KEY` | |
| siliconflow | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://api.siliconflow.cn/v1` |
-| tokendance | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价 |
| zhipu | `ZAI_API_KEY` | |
| moonshot | `MOONSHOT_API_KEY` | |
| minimax | `MINIMAX_API_KEY` | 直连 MiniMax M3 Responses 客户端(`client_type = "minimax-m3"`):`MiniMax-M3` 支持 1,000,000 Token 上下文和视觉输入;预置 base URL `https://api.minimax.io/v1`;接受 Token Plan Subscription Key 或按量付费 API Key |
@@ -78,7 +78,9 @@ api_key = "sk-..."
预置目录还收录了 OpenRouter 的免费档:`:free` 模型变体 `nvidia/nemotron-3-ultra-550b-a55b:free` 与统一路由 `openrouter/free`(Free Models Router),零成本可用,但受 OpenRouter 免费档速率限制与数据政策约束。
-预置目录中的部分模型:deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(DeepSeek 分组中唯一支持图像输入的模型)、MiniMax-M3、gemini-3.7-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的价格记录官方低谷时段档(高峰时段——北京时间 9:00–12:00、14:00–18:00——按双倍计费)。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格——直连条目记 Z.AI 牌价,TokenDance 条目记 TokenDance 牌价,OpenRouter 条目记该网关实际计费的折后价,因此促销期间三者不同。
+预置目录中的部分模型:deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(DeepSeek 分组中唯一支持图像输入的模型)、MiniMax-M3、gemini-3.7-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以 `-50%` 标记,成本中心按此计价。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间三者不同。
+
+TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有六个模型处于折扣中——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813` 与 `glm-5.3-flash` 五折,`kimi-k3` 八折,`glm-5.3` 与 `qwen3.8-max` 九折。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率;新建 Project 预置的是**折后价**,因此成本中心按网关实际收费计价。自行修改过价格的条目不再显示折扣标记:此时那个数字属于你,而不是网关。
## 应用归因
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index ca62f286..8c1d23f4 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2740,6 +2740,25 @@ export interface UsageModelSeries extends UsageEntitySeriesCounts {
modelId: string;
}
+/**
+ * Lifetime Token total for one Model, keyed by the (provider, modelId) pair. Deliberately
+ * unfiltered — no date range, no Agent: it answers "how much has this model been used", a
+ * question with no window attached, and the models page that shows it carries no filters of its
+ * own to honour. Models never used are absent rather than zero.
+ */
+export interface UsageModelTotal {
+ provider: string;
+ modelId: string;
+ /** The three buckets summed (cache read + cache write + output), matching the cost center's Token figure. */
+ tokens: number;
+ requests: number;
+}
+
+/** Response of `GET /usage/model-totals`. */
+export interface UsageModelTotals {
+ totals: UsageModelTotal[];
+}
+
/**
* The two categories an error record is filed under: `unexpected` is a 500 or an unforeseen
* runtime exception, `expected` an HttpError / business 4xx. The panel separates them by
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 3ced2e75..55f90bf4 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -772,6 +772,8 @@ export function buildAppDeps(
const usageService = new UsageService(
usageRepo,
errorsRepo,
+ // No clock here: a scheduled row's two rates come back together and each aggregation half
+ // is priced at the tier its own records ran in, which the query decides from their `ts`.
(projectId, provider, modelId) => projectConfigService.getPricing(projectId, provider, modelId),
overrides.now ?? (() => new Date()),
);
diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.ts
index 506fba95..a468ff7c 100644
--- a/packages/server/src/db/repos/usage.ts
+++ b/packages/server/src/db/repos/usage.ts
@@ -49,6 +49,26 @@ export interface UsageModelSums {
output: number;
total: number;
requests: number;
+ /**
+ * Which tier of a time-based price these Tokens ran in, decided from each record's own `ts`.
+ *
+ * A model with no schedule has one price and every row reports `true`. A scheduled one is
+ * summed into two rows per reference, so a week that straddles the boundary is priced at the
+ * rate each request actually ran at — rather than at whichever tier happens to be in force
+ * when someone opens the page, which would move a finished week's cost twice a day.
+ */
+ peak: boolean;
+}
+
+/** A time-based price to split an aggregation by: which references carry it, and when it is peak. */
+export interface PeakTier {
+ refs: ReadonlyArray<{ provider: string; modelId: string }>;
+ /** Minutes east of UTC the schedule's local hours are written in. */
+ utcOffsetMinutes: number;
+ /** ISO weekday numbers the windows apply to; a day not listed is off-peak throughout. */
+ peakDays: readonly number[];
+ /** `[startHour, endHour)` in the schedule's own local hours. */
+ peakHours: readonly (readonly [number, number])[];
}
/** Raw Token sums by group key x Model. */
@@ -107,6 +127,41 @@ const GROUP_COLUMNS: Record<UsageGroupBy, string> = {
session: "session_id",
};
+/**
+ * A `1`/`0` expression naming the tier a row's own `ts` fell in, for the references that have
+ * one; every other row is `1`, the single price it has.
+ *
+ * Written from the schedule rather than hardcoded so a second vendor's windows cost one more
+ * entry and no more SQL. The hours compare as integers because a window boundary is a whole
+ * hour in every schedule the catalog can express; a half-hour boundary would need the minutes.
+ * Literals only — the numbers come from the catalog and the references are bound.
+ */
+function peakExpr(tiers: readonly PeakTier[]): { sql: string; params: Record<string, string> } {
+ if (tiers.length === 0) return { sql: "1", params: {} };
+ const params: Record<string, string> = {};
+ const branches: string[] = [];
+ tiers.forEach((tier, ti) => {
+ if (tier.refs.length === 0 || tier.peakDays.length === 0) return;
+ const shift = `'${tier.utcOffsetMinutes >= 0 ? "+" : "-"}${Math.abs(tier.utcOffsetMinutes)} minutes'`;
+ const refs = tier.refs.map((ref, ri) => {
+ const p = `t${ti}p${ri}`;
+ const m = `t${ti}m${ri}`;
+ params[p] = ref.provider;
+ params[m] = ref.modelId;
+ return `(provider = :${p} AND model_id = :${m})`;
+ });
+ // `%w` is 0=Sunday; the schedule counts ISO days, so Sunday maps to 7.
+ const day = `CASE CAST(strftime('%w', ts, ${shift}) AS INTEGER) WHEN 0 THEN 7 ELSE CAST(strftime('%w', ts, ${shift}) AS INTEGER) END`;
+ const hour = `CAST(strftime('%H', ts, ${shift}) AS INTEGER)`;
+ const windows = tier.peakHours.map(([from, to]) => `(${hour} >= ${from} AND ${hour} < ${to})`);
+ branches.push(
+ `WHEN (${refs.join(" OR ")}) THEN (CASE WHEN ${day} IN (${tier.peakDays.join(", ")}) AND (${windows.join(" OR ")}) THEN 1 ELSE 0 END)`,
+ );
+ });
+ if (branches.length === 0) return { sql: "1", params: {} };
+ return { sql: `CASE ${branches.join(" ")} ELSE 1 END`, params };
+}
+
const SUM_COLUMNS = `COALESCE(SUM(cache_read), 0) AS cache_read,
COALESCE(SUM(cache_write), 0) AS cache_write,
COALESCE(SUM(output), 0) AS output,
@@ -117,6 +172,7 @@ function toSums(r: Record<string, unknown>): UsageModelSums {
return {
provider: r.provider as string,
modelId: r.model_id as string,
+ peak: r.peak !== 0,
cacheRead: r.cache_read as number,
cacheWrite: r.cache_write as number,
output: r.output as number,
@@ -191,16 +247,24 @@ export class UsageRepo {
return { where: conds.join(" AND "), params };
}
- /** Sums (broken down by paired reference): date range + optional agent/model filter. */
- bucketByModel(projectId: string, f: UsageFilter = {}): UsageModelSums[] {
+ /**
+ * Sums (broken down by paired reference, and by price tier where one applies): date range +
+ * optional agent/model filter.
+ */
+ bucketByModel(
+ projectId: string,
+ f: UsageFilter = {},
+ tiers: readonly PeakTier[] = [],
+ ): UsageModelSums[] {
const { where, params } = this.conds(projectId, f);
+ const peak = peakExpr(tiers);
const rows = this.db
.prepare(
- `SELECT provider, model_id, ${SUM_COLUMNS}
+ `SELECT provider, model_id, ${peak.sql} AS peak, ${SUM_COLUMNS}
FROM usage_records WHERE ${where}
- GROUP BY provider, model_id`,
+ GROUP BY provider, model_id, peak`,
)
- .all(params);
+ .all({ ...params, ...peak.params });
return rows.map(toSums);
}
@@ -209,16 +273,18 @@ export class UsageRepo {
projectId: string,
groupBy: UsageGroupBy,
f: UsageFilter = {},
+ tiers: readonly PeakTier[] = [],
): UsageGroupModelSums[] {
const col = GROUP_COLUMNS[groupBy];
const { where, params } = this.conds(projectId, f);
+ const peak = peakExpr(tiers);
const rows = this.db
.prepare(
- `SELECT ${col} AS key, provider, model_id, ${SUM_COLUMNS}
+ `SELECT ${col} AS key, provider, model_id, ${peak.sql} AS peak, ${SUM_COLUMNS}
FROM usage_records WHERE ${where}
- GROUP BY ${col}, provider, model_id`,
+ GROUP BY ${col}, provider, model_id, peak`,
)
- .all(params);
+ .all({ ...params, ...peak.params });
return rows.map((r) => ({ key: r.key as string, ...toSums(r) }));
}
@@ -232,18 +298,20 @@ export class UsageRepo {
projectId: string,
granularity: UsageSeriesGranularity,
f: UsageFilter = {},
+ tiers: readonly PeakTier[] = [],
): UsageSeriesModelSums[] {
const expr = BUCKET_EXPRS[granularity];
const { where, params } = this.conds(projectId, f);
+ const peak = peakExpr(tiers);
const rows = this.db
.prepare(
- `SELECT ${expr} AS key, provider, model_id, ${SUM_COLUMNS},
+ `SELECT ${expr} AS key, provider, model_id, ${peak.sql} AS peak, ${SUM_COLUMNS},
COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) AS completed,
COALESCE(SUM(CASE WHEN status <> 'aborted' THEN 1 ELSE 0 END), 0) AS denominator
FROM usage_records WHERE ${where}
- GROUP BY key, provider, model_id`,
+ GROUP BY key, provider, model_id, peak`,
)
- .all(params);
+ .all({ ...params, ...peak.params });
return rows.map((r) => ({
key: r.key as string,
...toSums(r),
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index 110121d6..cef1374f 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -8,7 +8,8 @@
* GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId&kind — one page of the error
* detail table, for paging back past the first page the dashboard already returns;
* DELETE /api/projects/:p/usage/errors?from&to&agentId — empties that table for the filter
- * the panel is showing (owner only).
+ * the panel is showing (owner only);
+ * GET /api/projects/:p/usage/model-totals — lifetime Token total per Model, unfiltered.
*/
import { Hono } from "hono";
import type {
@@ -89,6 +90,16 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
);
});
+ // Lifetime Token total per Model, for the models page's per-card figure. Takes no filters at
+ // all: the number answers "how much has this model been used", which has no range, and the
+ // page showing it offers none. One grouped scan, so it stays a cheap second request rather
+ // than a reason to widen the models response with telemetry.
+ app.get("/model-totals", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ return c.json(deps.usageService.modelTotals(projectId));
+ });
+
// One page of the error detail table, newest first. The dashboard response above already
// carries the first page; this serves "show me earlier ones" without refetching the whole
// aggregate. Takes the date/agent filter only — the model filter never applied to errors
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 26ff5f6e..ac3b1b96 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -82,7 +82,7 @@ import {
classifyVisionProbe,
classifyVisionProbeError,
} from "./vision-detect.js";
-import type { PricingRates } from "./usage-service.js";
+import type { PricingRates, TieredRates } from "./usage-service.js";
type RawTable = Record<string, unknown>;
@@ -145,6 +145,43 @@ function optNum(v: unknown): number | undefined {
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
}
+/**
+ * Both tiers of a price read from a Project's config.
+ *
+ * A scheduled row stores its PEAK price — the one number that is true whatever hour it is
+ * written — and the reduced rate is derived here. Both are returned rather than one of them
+ * chosen, because the caller prices a RANGE: a week that straddles a boundary holds Tokens of
+ * both kinds, and each is billed at the rate it actually ran at. Choosing here would mean
+ * pricing a finished week at whichever tier happened to be in force when someone opened the
+ * page, which moves a settled number twice a day.
+ *
+ * The two tiers differ only while the stored price is still exactly the catalog's peak: once
+ * the user has typed their own number, nothing here knows whether it is a peak rate, and
+ * halving it would invent a discount. The models page's badge bails on the same condition, so
+ * the card and the bill always agree about what this row costs.
+ */
+function tieredRates(provider: string, modelId: string, rates: PricingRates): TieredRates {
+ const entry = catalogEntryFor(provider, modelId);
+ const schedule = entry?.offPeakDiscount;
+ if (schedule === undefined || entry?.pricing === undefined)
+ return { peak: rates, offPeak: rates };
+ const peak = entry.pricing;
+ const untouched =
+ rates.cacheRead === peak.cache_read &&
+ rates.cacheWrite === peak.cache_write &&
+ rates.output === peak.output;
+ if (!untouched) return { peak: rates, offPeak: rates };
+ const off = (v: number): number => Math.round(v * (1 - schedule.rate) * 1e6) / 1e6;
+ return {
+ peak: rates,
+ offPeak: {
+ cacheRead: off(rates.cacheRead),
+ cacheWrite: off(rates.cacheWrite),
+ output: off(rates.output),
+ },
+ };
+}
+
function optStr(v: unknown): string | undefined {
return typeof v === "string" && v !== "" ? v : undefined;
}
@@ -499,7 +536,7 @@ export class ProjectConfigService {
projectId: string,
provider: string,
modelId: string,
- ): Promise<PricingRates | undefined> {
+ ): Promise<TieredRates | undefined> {
const raw = await this.readRaw(projectId);
const entry = asArray(raw.models).find((m) => entryMatches(m, provider, modelId));
const pricing = entry ? asTable(entry.pricing) : {};
@@ -509,7 +546,8 @@ export class ProjectConfigService {
if (cacheRead === undefined && cacheWrite === undefined && output === undefined) {
return undefined;
}
- return { cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0, output: output ?? 0 };
+ const rates = { cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0, output: output ?? 0 };
+ return tieredRates(provider, modelId, rates);
}
/**
@@ -801,8 +839,12 @@ export class ProjectConfigService {
const maxTokens = optNum(m.max_tokens);
// Fast mode: TOML annotation only (user-owned); only `true` is reported — absent = off.
const fastMode = m.fast_mode === true ? true : undefined;
- // Display name: the explicit TOML field (user-edited) takes priority, then the built-in catalog.
- const displayName = optStr(m.display_name) ?? cat?.displayName;
+ // Display name: the explicit TOML field (user-edited) takes priority, then the built-in
+ // catalog. An empty string is not the same as an absent field — absent means "inherit
+ // whatever the catalog calls this model", empty means the user cleared the name on a
+ // model the catalog does name, and inheriting there would hand the name straight back.
+ const displayName =
+ m.display_name === "" ? undefined : (optStr(m.display_name) ?? cat?.displayName);
// credential is inlined on the entry: a credential block is emitted if either api_key or base_url is present.
const apiKey = optStr(m.api_key);
const credBaseUrl = optStr(m.base_url);
@@ -924,6 +966,12 @@ export class ProjectConfigService {
const catNew = catalogEntryFor(entry.provider, entry.modelId);
if (entry.displayName && entry.displayName !== catNew?.displayName) {
next.display_name = entry.displayName;
+ } else if (!entry.displayName && catNew?.displayName !== undefined) {
+ // Cleared on a model the catalog names. Writing nothing would leave the field absent,
+ // which reads as "inherit" — so the name the user just deleted would come back on the
+ // next load. The empty string is what records the deletion. Only reached for a catalog
+ // model: a custom one has no name to inherit, so absence already says it.
+ next.display_name = "";
}
if (entry.contextWindow !== undefined) next.context_window = entry.contextWindow;
// Stored canonically: a client sending the deprecated "openai" alias persists
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index 03a89c55..50a076bd 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -25,10 +25,12 @@ import type {
UsageGroupBy,
UsageGroupRow,
UsageModelSeries,
+ UsageModelTotals,
UsageResponse,
UsageSeriesPoint,
} from "../api/types.js";
import type { ErrorFilter, ErrorsRepo } from "../db/repos/errors.js";
+import { offPeakScheduledRefs } from "@prismshadow/penguin-core/model-catalog";
import type {
UsageRepo,
UsageModelSums,
@@ -36,6 +38,7 @@ import type {
UsageSeriesModelSums,
UsageAgentBucketCount,
UsageFilter,
+ PeakTier,
} from "../db/repos/usage.js";
import {
enumerateBuckets,
@@ -60,11 +63,24 @@ export interface PricingRates {
output: number;
}
+/**
+ * What one Model costs, in the tiers it can be billed in.
+ *
+ * `offPeak` differs from `peak` only for a catalog row on a time-based schedule whose stored
+ * price is still the catalog's own. Both are returned together because a query spans time: a
+ * week that straddles the boundary contains Tokens of both kinds, and each half is priced at
+ * the rate it actually ran at rather than at whichever tier is in force when it is read.
+ */
+export interface TieredRates {
+ peak: PricingRates;
+ offPeak: PricingRates;
+}
+
export type PricingLookup = (
projectId: string,
provider: string,
modelId: string,
-) => Promise<PricingRates | undefined>;
+) => Promise<TieredRates | undefined>;
export interface UsageQuery {
from?: string;
@@ -114,8 +130,9 @@ export interface UsageErrorsClearQuery {
agentId?: string;
}
-/** Cost formula: sum of the three buckets, in USD per million Tokens. */
-function costOf(sums: UsageModelSums, rates: PricingRates): number {
+/** Cost formula: sum of the three buckets at the tier these Tokens ran in, USD per million. */
+function costOf(sums: UsageModelSums, tiered: TieredRates): number {
+ const rates = sums.peak ? tiered.peak : tiered.offPeak;
return (
(sums.cacheRead * rates.cacheRead +
sums.cacheWrite * rates.cacheWrite +
@@ -137,6 +154,23 @@ export class UsageService {
private readonly now: () => Date = () => new Date(),
) {}
+ /**
+ * The catalog's time-based schedules, as the aggregations want them.
+ *
+ * Split by the SCHEDULE, not by whether this Project is on the catalog's price: a Project
+ * that edited the price gets one rate for both halves from {@link lookupPricing}, so the extra
+ * dimension costs a row and changes no number. Doing it the other way round would need the
+ * config read before the query that discovers which references occur.
+ */
+ private tiers(): PeakTier[] {
+ return offPeakScheduledRefs().map(({ schedule, refs }) => ({
+ refs,
+ utcOffsetMinutes: schedule.utcOffsetMinutes,
+ peakDays: schedule.peakDays,
+ peakHours: schedule.peakHours,
+ }));
+ }
+
async query(projectId: string, q: UsageQuery): Promise<UsageResponse> {
const today = formatLocalDate(this.now());
// Top-level filter: agent + model (the cost center switches views by agent/model; the model filter is always sent as a pair).
@@ -158,13 +192,20 @@ export class UsageService {
...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),
...(q.toTs !== undefined ? { toTs: q.toTs } : {}),
};
- const todayRows = this.usage.bucketByModel(projectId, win(today, today));
- const last7dRows = this.usage.bucketByModel(projectId, win(localDateMinusDays(this.now(), 6)));
- const totalRows = this.usage.bucketByModel(projectId, { ...win(q.from, q.to), ...ts });
- const groupRows = this.usage.groupsByModel(projectId, q.groupBy, {
- ...win(q.from, q.to),
- ...ts,
- });
+ const tiers = this.tiers();
+ const todayRows = this.usage.bucketByModel(projectId, win(today, today), tiers);
+ const last7dRows = this.usage.bucketByModel(
+ projectId,
+ win(localDateMinusDays(this.now(), 6)),
+ tiers,
+ );
+ const totalRows = this.usage.bucketByModel(projectId, { ...win(q.from, q.to), ...ts }, tiers);
+ const groupRows = this.usage.groupsByModel(
+ projectId,
+ q.groupBy,
+ { ...win(q.from, q.to), ...ts },
+ tiers,
+ );
// Time series at the requested precision, zero-filled over the requested
// range, defaulting to the last 30 days when no range is given.
const granularity = q.granularity ?? "day";
@@ -192,10 +233,12 @@ export class UsageService {
"Date range too wide for this granularity; narrow the range or coarsen the granularity.",
);
}
- const seriesRows = this.usage.seriesByModel(projectId, granularity, {
- ...win(seriesFrom, seriesTo),
- ...ts,
- });
+ const seriesRows = this.usage.seriesByModel(
+ projectId,
+ granularity,
+ { ...win(seriesFrom, seriesTo), ...ts },
+ tiers,
+ );
// Per-Agent and per-Model series: each drops its own dimension's filter (its
// chart draws that dimension's whole breakdown) but honors the other
// dimension plus the selected range.
@@ -233,7 +276,7 @@ export class UsageService {
};
// Each paired reference that occurs is looked up for its current price only once.
- const rates = new Map<string, PricingRates | undefined>();
+ const rates = new Map<string, TieredRates | undefined>();
const allRefs = new Map<string, { provider: string; modelId: string }>();
for (const r of [...todayRows, ...last7dRows, ...totalRows, ...groupRows, ...seriesRows]) {
allRefs.set(refKey(r.provider, r.modelId), { provider: r.provider, modelId: r.modelId });
@@ -327,9 +370,26 @@ export class UsageService {
};
}
+ /**
+ * Lifetime Token totals per Model — one grouped scan of `usage_records`, no filters. The
+ * models page shows each configured model what it has actually spent, and that figure is not
+ * scoped to a range the way the cost center's is; a model with no records is simply absent,
+ * so the caller renders nothing rather than a zero.
+ */
+ modelTotals(projectId: string): UsageModelTotals {
+ return {
+ totals: this.usage.bucketByModel(projectId).map((r) => ({
+ provider: r.provider,
+ modelId: r.modelId,
+ tokens: r.total,
+ requests: r.requests,
+ })),
+ };
+ }
+
private foldBucket(
rows: UsageModelSums[],
- rates: Map<string, PricingRates | undefined>,
+ rates: Map<string, TieredRates | undefined>,
): UsageBucket {
let total = 0;
let requests = 0;
@@ -347,7 +407,7 @@ export class UsageService {
private foldGroups(
rows: UsageGroupModelSums[],
- rates: Map<string, PricingRates | undefined>,
+ rates: Map<string, TieredRates | undefined>,
groupBy: UsageGroupBy,
): UsageGroupRow[] {
// The model dimension folds by paired reference (a shared model_id name across providers is split into separate rows); other dimensions fold by their group key.
@@ -395,7 +455,7 @@ export class UsageService {
private foldSeries(
keys: string[],
rows: UsageSeriesModelSums[],
- rates: Map<string, PricingRates | undefined>,
+ rates: Map<string, TieredRates | undefined>,
): UsageSeriesPoint[] {
const byKey = new Map<string, UsageSeriesPoint>(
keys.map((bucket) => [
diff --git a/packages/server/test/authz.test.ts b/packages/server/test/authz.test.ts
index eef18092..a06c4e04 100644
--- a/packages/server/test/authz.test.ts
+++ b/packages/server/test/authz.test.ts
@@ -46,8 +46,19 @@ describe("authz", () => {
expect((await outsider.get(`/api/projects/${projectId}/members`)).status).toBe(404);
expect((await outsider.get(`/api/projects/${projectId}/usage`)).status).toBe(404);
// The error table's paging route is checked separately from /usage: it is the one place a
- // reader can walk past the dashboard's first page, so it must refuse the same way.
+ // reader can walk past the dashboard's first page, so it must refuse the same way. The
+ // per-Model totals are the other route off /usage that answers without any filter at all.
expect((await outsider.get(`/api/projects/${projectId}/usage/errors`)).status).toBe(404);
+ expect((await outsider.get(`/api/projects/${projectId}/usage/model-totals`)).status).toBe(404);
+ });
+
+ it("a member reads the per-Model totals: it is a read, not a management operation", async () => {
+ // The models page shows every viewer what each model has spent, so this one is not
+ // owner-gated the way a write is — but it is still Project-scoped, which the line above
+ // pins from the other side.
+ const res = await member.get(`/api/projects/${projectId}/usage/model-totals`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ totals: [] });
});
it("member can read models (masked) but not write; owner can write", async () => {
diff --git a/packages/server/test/model-oauth.test.ts b/packages/server/test/model-oauth.test.ts
index 988130a8..619c941d 100644
--- a/packages/server/test/model-oauth.test.ts
+++ b/packages/server/test/model-oauth.test.ts
@@ -13,7 +13,7 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { APP_URL, providerInfo } from "@prismshadow/penguin-core/model-catalog";
+import { APP_URL, presetModelEntries, providerInfo } from "@prismshadow/penguin-core/model-catalog";
import type {
ModelOAuthCodeResponse,
ModelOAuthStartResponse,
@@ -38,6 +38,12 @@ import type { TestApp } from "./helpers.js";
/** The catalog group under test; the flow exists only because this entry declares it. */
const TOKENDANCE = providerInfo("tokendance")!;
+/**
+ * How many models the minted key lands on — derived from the catalog rather than pinned, so
+ * adding a row to this group does not fail three assertions that are not about the count.
+ */
+const TOKENDANCE_MODELS = presetModelEntries().filter((m) => m.provider === "tokendance").length;
+
/** A JSON reply from the exchange endpoint, without touching the network. */
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
@@ -458,7 +464,7 @@ describe("model-oauth routes", () => {
const status = (await (
await owner.get(`${base()}/${started.flowId}`)
).json()) as ModelOAuthStatusResponse;
- expect(status).toEqual({ status: "done", provider: "tokendance", applied: 8 });
+ expect(status).toEqual({ status: "done", provider: "tokendance", applied: TOKENDANCE_MODELS });
// The exchange spoke the documented protocol, with a verifier this side never published.
expect(exchanges).toHaveLength(1);
@@ -677,7 +683,11 @@ describe("model-oauth callback without a session", () => {
expect(await groupHasKey()).toBe(false);
// The owner's own poll is what spends the code and lands the key.
- expect(await poll(flowId)).toEqual({ status: "done", provider: "tokendance", applied: 8 });
+ expect(await poll(flowId)).toEqual({
+ status: "done",
+ provider: "tokendance",
+ applied: TOKENDANCE_MODELS,
+ });
expect(exchanges).toBe(1);
expect(await groupHasKey()).toBe(true);
});
@@ -689,7 +699,11 @@ describe("model-oauth callback without a session", () => {
const browser = await owner.get(callback(flowId, "auth-code-2"));
expect(browser.status).toBe(200);
expect(await browser.text()).toContain("Authorization received");
- expect(await poll(flowId)).toEqual({ status: "done", provider: "tokendance", applied: 8 });
+ expect(await poll(flowId)).toEqual({
+ status: "done",
+ provider: "tokendance",
+ applied: TOKENDANCE_MODELS,
+ });
expect(exchanges).toBe(1);
expect(await groupHasKey()).toBe(true);
});
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 3fe89963..0a22a710 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -13,7 +13,12 @@ import type { AddressInfo } from "node:net";
import { readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { MODEL_CATALOG, userText } from "@prismshadow/penguin-core";
+import {
+ MODEL_CATALOG,
+ catalogEntryFor,
+ effectivePricing,
+ userText,
+} from "@prismshadow/penguin-core";
import type {
ModelsResponse,
ModelTestResponse,
@@ -126,6 +131,25 @@ describe("models preset & catalog enrichment", () => {
expect(mimo.clientType).toBe("openai-chat");
expect(mimo.credential?.baseUrl).toBe("https://openrouter.ai/api/v1");
expect(mimo.credential?.apiKeyMasked).toBeUndefined();
+
+ // A catalog row on a promotion is preset at the rate the seller BILLS, not at the list
+ // price the catalog records. The cost center prices only against what is written into
+ // the Project, so anything else here would report a cost nobody was charged.
+ const promoted = catalogEntryFor("tokendance", "glm-5.3-flash")!;
+ const billed = effectivePricing(promoted)!;
+ expect(pick(body, "tokendance", "glm-5.3-flash").pricing).toEqual({
+ cacheRead: billed.cache_read,
+ cacheWrite: billed.cache_write,
+ output: billed.output,
+ });
+ expect(billed.output).toBeLessThan(promoted.pricing!.output);
+ // An undiscounted row is preset at its list price, unchanged.
+ const plain = catalogEntryFor("tokendance", "hy4-preview")!;
+ expect(pick(body, "tokendance", "hy4-preview").pricing).toEqual({
+ cacheRead: plain.pricing!.cache_read,
+ cacheWrite: plain.pricing!.cache_write,
+ output: plain.pricing!.output,
+ });
});
it("masks the env fallback for first-party official entries only, and never leaks the value", async () => {
@@ -573,6 +597,89 @@ describe("model-reference rekeying and the connectivity test", () => {
expect(toml).not.toContain("openai/gpt-5.5");
});
+ it("a scheduled row answers with both of its rates, from the one stable price on disk", async () => {
+ // No clock is passed and none is wanted: which tier a given request ran in is decided from
+ // that record's own timestamp when the usage is aggregated, so the price lookup's whole job
+ // is to say what the two tiers are. The number on disk is the peak one either way.
+ const svc = new ProjectConfigService(t.root);
+ const rates = await svc.getPricing(projectId, "deepseek", "deepseek-v4-flash");
+ const catalogPeak = catalogEntryFor("deepseek", "deepseek-v4-flash")!.pricing!;
+ expect(rates!.peak.output).toBe(catalogPeak.output);
+ expect(rates!.offPeak.output).toBeCloseTo(catalogPeak.output / 2, 5);
+ expect(rates!.peak.cacheRead).toBe(catalogPeak.cache_read);
+ expect(rates!.offPeak.cacheRead).toBeCloseTo(catalogPeak.cache_read / 2, 6);
+ });
+
+ it("a hand-edited price on a scheduled row is billed as typed, in both tiers", async () => {
+ const body = (await (await api.get(url())).json()) as ModelsResponse;
+ const entries = body.models.map((m) => ({
+ provider: m.provider,
+ modelId: m.modelId,
+ ...(m.pricing
+ ? {
+ pricing:
+ m.provider === "deepseek" && m.modelId === "deepseek-v4-flash"
+ ? { cacheRead: 1, cacheWrite: 2, output: 3 }
+ : {
+ cacheRead: m.pricing.cacheRead,
+ cacheWrite: m.pricing.cacheWrite,
+ output: m.pricing.output,
+ },
+ }
+ : {}),
+ }));
+ await api.put(url(), { models: entries });
+ const svc = new ProjectConfigService(t.root);
+ // Nothing here knows whether 3 is a peak rate, so halving it would invent a discount: the
+ // two tiers collapse to the typed number and the split costs a row and changes nothing.
+ const typed = { cacheRead: 1, cacheWrite: 2, output: 3 };
+ expect(await svc.getPricing(projectId, "deepseek", "deepseek-v4-flash")).toEqual({
+ peak: typed,
+ offPeak: typed,
+ });
+ });
+
+ it("clearing a preset model's display name sticks: it falls back to the id, not back to the catalog", async () => {
+ // Only provider and modelId are required, so an entry sent without a display name is the
+ // user having cleared it. Writing nothing would leave the field absent, which reads as
+ // "inherit from the catalog" — the deleted name would be handed straight back on reload.
+ await api.put(url(), { models: [{ provider: "openai", modelId: "gpt-5.5" }] });
+ const body = (await (await api.get(url())).json()) as ModelsResponse;
+ expect(pick(body, "openai", "gpt-5.5").displayName).toBeUndefined();
+ // The empty string is what records the deletion, and it survives a second full-table PUT
+ // that likewise carries no name.
+ const toml = await readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
+ expect(toml).toContain('display_name = ""');
+ await api.put(url(), { models: [{ provider: "openai", modelId: "gpt-5.5" }] });
+ const again = (await (await api.get(url())).json()) as ModelsResponse;
+ expect(pick(again, "openai", "gpt-5.5").displayName).toBeUndefined();
+ });
+
+ it("a cleared name is restorable, and clearing a model the catalog does not name writes nothing", async () => {
+ await api.put(url(), { models: [{ provider: "openai", modelId: "gpt-5.5" }] });
+ // Naming it again drops the marker rather than leaving both on disk.
+ await api.put(url(), {
+ models: [{ provider: "openai", modelId: "gpt-5.5", displayName: "Renamed" }],
+ });
+ const body = (await (await api.get(url())).json()) as ModelsResponse;
+ expect(pick(body, "openai", "gpt-5.5").displayName).toBe("Renamed");
+ let toml = await readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
+ expect(toml).not.toContain('display_name = ""');
+
+ // A model outside the catalog has no name to inherit, so absence already says "no name"
+ // and the marker would be noise in the file.
+ await api.put(url(), {
+ models: [
+ { provider: "openai", modelId: "gpt-5.5", displayName: "Renamed" },
+ { provider: "custom", modelId: "my-own-model" },
+ ],
+ });
+ toml = await readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");
+ expect(toml).not.toContain('display_name = ""');
+ const after = (await (await api.get(url())).json()) as ModelsResponse;
+ expect(pick(after, "custom", "my-own-model").displayName).toBeUndefined();
+ });
+
it("an invalid renamedFrom is 400; rekeying without renamedFrom equals delete-old-then-create-new (the credential does not migrate)", async () => {
await api.put(url(), {
models: [{ provider: "custom", modelId: "m-a", apiKey: "sk-secret-abcd1234" }],
diff --git a/packages/server/test/project-config-cache.test.ts b/packages/server/test/project-config-cache.test.ts
index 3a5f5f39..512d0ad1 100644
--- a/packages/server/test/project-config-cache.test.ts
+++ b/packages/server/test/project-config-cache.test.ts
@@ -45,17 +45,18 @@ describe("project-config read cache", () => {
await fs.rm(root, { recursive: true, force: true });
});
+ /** This fixture's model has no schedule, so both tiers are the one price it stores. */
+ const RATES = { cacheRead: 1, cacheWrite: 2, output: 3 };
+
it("repeat reads cost one readFile: pricing, name and the typed loadConfig view share the cached parse", async () => {
const reads = vi.spyOn(fs, "readFile");
expect(await svc.getPricing(P, "custom", "m1")).toEqual({
- cacheRead: 1,
- cacheWrite: 2,
- output: 3,
+ peak: RATES,
+ offPeak: RATES,
});
expect(await svc.getPricing(P, "custom", "m1")).toEqual({
- cacheRead: 1,
- cacheWrite: 2,
- output: 3,
+ peak: RATES,
+ offPeak: RATES,
});
expect(await svc.getName(P)).toBe("cached");
expect((await svc.loadConfig(P)).models.map((m) => m.model_id)).toEqual(["m1"]);
@@ -69,9 +70,8 @@ describe("project-config read cache", () => {
const reads = vi.spyOn(fs, "readFile");
expect(await svc.getName(P)).toBe("renamed");
expect(await svc.getPricing(P, "custom", "m1")).toEqual({
- cacheRead: 1,
- cacheWrite: 2,
- output: 3,
+ peak: RATES,
+ offPeak: RATES,
});
expect(reads).toHaveBeenCalledTimes(1);
});
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index 5aa6b2bf..74b62adb 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -113,8 +113,13 @@ describe("usage-service (cost computed on the fly)", () => {
/** Mutable pricing table: simulates a "price added later" — change the price after inserting a record, and the query reflects it immediately. */
let pricing: Record<string, PricingRates | undefined>;
- // The pricing lookup callback takes three params (projectId, provider, modelId): locates the price via the paired reference.
- const lookup = async (_p: string, _provider: string, modelId: string) => pricing[modelId];
+ // The pricing lookup callback takes three params (projectId, provider, modelId): locates the
+ // price via the paired reference. These fixtures use models with no schedule, so both tiers
+ // are the one rate — a scheduled model's two tiers are exercised in the peak-split test below.
+ const lookup = async (_p: string, _provider: string, modelId: string) => {
+ const rates = pricing[modelId];
+ return rates === undefined ? undefined : { peak: rates, offPeak: rates };
+ };
beforeEach(() => {
db = openDatabase(":memory:");
@@ -146,6 +151,31 @@ describe("usage-service (cost computed on the fly)", () => {
});
}
+ it("a scheduled model is priced per record, and the total does not move with the clock", async () => {
+ // The defect this pins: pricing the whole table at whichever tier is in force when the page
+ // is opened made a finished week's cost double at 09:00 Beijing and halve at 12:00. The tier
+ // is a fact about when each request ran, so it is decided from that record's own `ts`.
+ //
+ // 2026-08-31 is a Monday. 01:30Z is 09:30 in Beijing (peak); 12:00Z is 20:00 (off-peak).
+ const REF = { provider: "deepseek", modelId: "deepseek-v4-flash" };
+ insert("2026-08-31", { ...REF, ts: "2026-08-31T01:30:00.000Z" });
+ insert("2026-08-31", { ...REF, ts: "2026-08-31T12:00:00.000Z" });
+ pricing["deepseek-v4-flash"] = { cacheRead: 1, cacheWrite: 2, output: 4 };
+ const tiered = async () => ({
+ peak: { cacheRead: 1, cacheWrite: 2, output: 4 },
+ offPeak: { cacheRead: 0.5, cacheWrite: 1, output: 2 },
+ });
+ // One row's Tokens are cacheRead 10 / cacheWrite 1 / output 5, so the peak record costs
+ // (10*1 + 1*2 + 5*4)/1e6 and the off-peak one exactly half of that.
+ const peakCost = (10 * 1 + 1 * 2 + 5 * 4) / 1e6;
+ const expected = peakCost + peakCost / 2;
+ for (const at of ["2026-08-31T01:30:00Z", "2026-08-31T12:00:00Z", "2026-09-06T01:30:00Z"]) {
+ const svc = new UsageService(repo, new ErrorsRepo(db), tiered, () => new Date(at));
+ const res = await svc.query("p1", { groupBy: "date", from: "2026-08-31", to: "2026-08-31" });
+ expect(res.summary.total.cost, at).toBeCloseTo(expected, 10);
+ }
+ });
+
it("summary cards: today / last 7 days / cumulative; Models without pricing flag hasUncosted", async () => {
const now = new Date("2026-07-06T10:00:00");
const today = formatLocalDate(now);
@@ -309,12 +339,71 @@ describe("usage-service (cost computed on the fly)", () => {
});
});
+describe("usage-service model totals (unfiltered, for the models page)", () => {
+ let db: DatabaseSync;
+ let repo: UsageRepo;
+ let service: UsageService;
+ const lookup = async () => undefined;
+
+ beforeEach(() => {
+ db = openDatabase(":memory:");
+ repo = new UsageRepo(db);
+ service = new UsageService(repo, new ErrorsRepo(db), lookup);
+ });
+ afterEach(() => db.close());
+
+ function insert(date: string, opts: Partial<Parameters<UsageRepo["insert"]>[0]> = {}): void {
+ repo.insert({
+ ts: `${date}T00:00:00.000Z`,
+ date,
+ projectId: "p1",
+ agentId: "a1",
+ sessionId: "s1",
+ originSessionId: null,
+ modelId: "m1",
+ provider: "custom",
+ cacheRead: 10,
+ cacheWrite: 1,
+ output: 5,
+ total: 100,
+ ...opts,
+ });
+ }
+
+ it("sums every record a Model ever wrote, with no date or Agent window", () => {
+ insert("2026-01-01");
+ insert("2026-07-06");
+ // A different Agent, and a date far outside any range the cost center offers: both count.
+ insert("2020-03-02", { agentId: "a2" });
+ const totals = service.modelTotals("p1").totals;
+ expect(totals).toEqual([{ provider: "custom", modelId: "m1", tokens: 300, requests: 3 }]);
+ });
+
+ it("keys by the paired reference, so one id under two providers stays two entries", () => {
+ insert("2026-07-06");
+ insert("2026-07-06", { provider: "gateway" });
+ const totals = service.modelTotals("p1").totals;
+ expect(totals).toHaveLength(2);
+ expect(totals.map((t) => t.provider).sort()).toEqual(["custom", "gateway"]);
+ });
+
+ it("is scoped to the Project, and a Model that never ran is absent rather than zero", () => {
+ insert("2026-07-06");
+ insert("2026-07-06", { projectId: "p2", modelId: "m-elsewhere" });
+ const totals = service.modelTotals("p1").totals;
+ expect(totals.map((t) => t.modelId)).toEqual(["m1"]);
+ });
+});
+
describe("usage-service series (zero-filled time-series buckets)", () => {
let db: DatabaseSync;
let repo: UsageRepo;
let service: (now: Date) => UsageService;
let pricing: Record<string, PricingRates | undefined>;
- const lookup = async (_p: string, _provider: string, modelId: string) => pricing[modelId];
+ const lookup = async (_p: string, _provider: string, modelId: string) => {
+ const rates = pricing[modelId];
+ return rates === undefined ? undefined : { peak: rates, offPeak: rates };
+ };
beforeEach(() => {
db = openDatabase(":memory:");
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 108bb32f..b5ccc985 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -132,6 +132,7 @@ import type {
UsageErrorsPage,
UsageGranularity,
UsageGroupBy,
+ UsageModelTotals,
UsageResponse,
VaultResponse,
VaultUpdateRequest,
@@ -917,6 +918,14 @@ export const clearUsageErrors = (
},
);
+/**
+ * Lifetime Token total per Model, unfiltered. The models page shows each card what it has
+ * spent; it is a separate request from the model list so a stats failure costs the figure and
+ * not the page.
+ */
+export const getUsageModelTotals = (projectId: string) =>
+ apiFetch<UsageModelTotals>(`/api/projects/${encodeURIComponent(projectId)}/usage/model-totals`);
+
export const getUsage = (
projectId: string,
params: {
diff --git a/packages/web/src/features/models/model-group-expansion.ts b/packages/web/src/features/models/model-group-expansion.ts
index 5f282ba8..e41b6950 100644
--- a/packages/web/src/features/models/model-group-expansion.ts
+++ b/packages/web/src/features/models/model-group-expansion.ts
@@ -4,10 +4,10 @@
* The page stores the set of EXPANDED provider ids rather than collapsed ones: groups
* are derived only after the model rows load (user-defined groups arrive with that
* async response), so a collapsed-set default cannot express "everything collapsed
- * except DeepSeek" without knowing every group id up front. An expanded set survives
+ * except the top group" without knowing every group id up front. An expanded set survives
* late-arriving groups — anything not in it simply renders collapsed.
*
- * The user's toggles persist per Project in localStorage (#224 follow-up: DeepSeek-only
+ * The user's toggles persist per Project in localStorage (#224 follow-up: one group open
* is the first-visit default, not a per-visit reset), mirroring the sidebar's persisted
* group-collapse sets — a `penguin.…` key namespaced by projectId holding a JSON array
* of ids. Unlike the sidebar sets, whose default IS the empty set, the default here is
@@ -16,15 +16,19 @@
* injectable (draft-cache.ts convention: vitest runs in Node, no localStorage); search
* force-open below stays derived and never writes storage.
*/
+import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
/**
- * Provider ids expanded on first visit (nothing persisted yet): DeepSeek only — the
- * default model's provider and the first group in MODEL_PROVIDERS, so the page opens
- * with exactly its top group unfolded. Returns a fresh Set per call (React state must
- * never share a module-level mutable instance).
+ * Provider ids expanded on first visit (nothing persisted yet): the leading group of
+ * MODEL_PROVIDERS and nothing else, so the page opens with exactly its top group
+ * unfolded. Read from the catalog rather than named here — the curated order is what
+ * decides which group leads, and a hard-coded id would quietly stop matching it.
+ * Returns a fresh Set per call (React state must never share a module-level mutable
+ * instance).
*/
export function defaultExpandedProviders(): Set<string> {
- return new Set(["deepseek"]);
+ const first = MODEL_PROVIDERS[0]?.id;
+ return new Set(first === undefined ? [] : [first]);
}
/**
@@ -92,7 +96,7 @@ export function parseExpandedProviders(raw: string | null): Set<string> | null {
/**
* Reads a Project's persisted expanded set; no Project yet, nothing stored, or
- * corrupted storage falls back to the DeepSeek-only default. Stored ids of
+ * corrupted storage falls back to the leading-group default. Stored ids of
* since-deleted groups pass through unpruned — harmless, expansion is a pure
* membership test and a group no longer rendered is never asked about.
*/
diff --git a/packages/web/src/features/models/model-grouping.ts b/packages/web/src/features/models/model-grouping.ts
index 04587d0d..77bc38bb 100644
--- a/packages/web/src/features/models/model-grouping.ts
+++ b/packages/web/src/features/models/model-grouping.ts
@@ -16,7 +16,12 @@
* the identity, so a profile that has never dragged a group sees exactly the catalog
* order. Storage stays out of this module: the caller loads the array and passes it in.
*/
-import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
+import {
+ MODEL_PROVIDERS,
+ catalogEntryFor,
+ effectivePricing,
+ offPeakAt,
+} from "@prismshadow/penguin-core/model-catalog";
import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
import { orderModelGroups } from "./model-group-order";
@@ -173,6 +178,90 @@ export function isFreeModel(
);
}
+/**
+ * The three price buckets as the page carries them: the DTO's numbers, or the model page's
+ * string-typed edit fields ("" = unpriced) — the same pair of shapes isFreeModel accepts.
+ */
+export interface PricingBucketsLike {
+ cacheRead?: number | string;
+ cacheWrite?: number | string;
+ output?: number | string;
+}
+
+/** The discount decoration for one model card, and the price it makes the row cost right now. */
+export interface DiscountedPrice {
+ /** Whole-percent rate off list, as the badge shows it (50 for a half-price row). */
+ percent: number;
+ /**
+ * What the seller bills for this row right now, in USD per million tokens — the figure the
+ * card prints. For a flat promotion this is the stored price, already discounted at sync
+ * time; for a scheduled one the stored price is the peak price and this is the reduced rate.
+ */
+ billed: { cacheRead: number; cacheWrite: number; output: number };
+ /** True when the rate is a time-of-day one, so the badge can explain when it applies. */
+ scheduled: boolean;
+}
+
+/** One bucket as a finite number, or undefined for an unpriced ("" / absent) field. */
+function bucketValue(v: number | string | undefined): number | undefined {
+ if (typeof v === "number") return Number.isFinite(v) ? v : undefined;
+ if (v === undefined || v.trim() === "") return undefined;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+/**
+ * The discount decoration for one model row, or undefined for a row that carries none.
+ *
+ * A row qualifies only when its (provider, modelId) names a catalog entry on a promotion AND
+ * its stored price is still exactly the price that entry expects to be stored. Prices are
+ * editable, and a hand-typed number has nothing to do with the seller's list price — marking it
+ * would invent a saving the user is not getting. The same guard covers a Project that has not
+ * run "sync presets" yet: its rows still hold whatever price they were created with.
+ *
+ * Which price that is differs by promotion kind, and the difference is the point:
+ *
+ * - A **flat** promotion is a single rate the seller bills until it lapses, so `sync presets`
+ * bakes it in and the stored number is already the discounted one.
+ * - A **scheduled** one changes twice a day. Baking it in would put a number on disk that meant
+ * something different an hour later, and would make re-syncing rewrite prices by the clock —
+ * so the peak price is stored and the reduction is applied here, against `now`. Inside the
+ * peak windows the row is simply at list price and carries no mark at all.
+ */
+export function discountedPrice(
+ row: ModelRowLike & PricingBucketsLike,
+ now: Date = new Date(),
+): DiscountedPrice | undefined {
+ const entry = catalogEntryFor(row.provider, row.modelId);
+ if (entry?.pricing === undefined) return undefined;
+ const schedule = entry.offPeakDiscount;
+ const rate = schedule?.rate ?? entry.discount;
+ // A fraction off, so only (0, 1) says anything: `effectivePricing` already ignores 0, and a
+ // badge built from a value outside that range reads as `-0%`, `-100%` beside a "Free" tag, or
+ // `--20%`. A stray 0 is the plausible one — the field's own doc says a lapsed promotion is one
+ // field to delete, and deleting a digit is the near miss.
+ if (rate === undefined || rate <= 0 || rate >= 1) return undefined;
+ const expected = schedule !== undefined ? entry.pricing : effectivePricing(entry);
+ if (expected === undefined) return undefined;
+ const same =
+ bucketValue(row.cacheRead) === expected.cache_read &&
+ bucketValue(row.cacheWrite) === expected.cache_write &&
+ bucketValue(row.output) === expected.output;
+ if (!same) return undefined;
+ if (schedule !== undefined && !offPeakAt(schedule, now)) return undefined;
+ const billed = effectivePricing(entry, now);
+ if (billed === undefined) return undefined;
+ return {
+ percent: Math.round(rate * 100),
+ billed: {
+ cacheRead: billed.cache_read,
+ cacheWrite: billed.cache_write,
+ output: billed.output,
+ },
+ scheduled: schedule !== undefined,
+ };
+}
+
export interface VisibleChatModelsOptions {
/** true = list every model (the dropdown's expanded "show all" state). */
showAll: boolean;
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index f5ef0c95..561b1dec 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -10,7 +10,7 @@
*
* The list is purely for "finding a model": grouped by vendor (group header = logo + vendor
* name + count, collapsible), with one card per model within a group — the card shows only
- * the display name + upstream id + status badges (default / vision / proxy-read), while
+ * the display name + status badges (default / vision / proxy-read), while
* context, pricing, and key status are folded into a single line of small text. Clicking a
* card opens the config dialog (credentials, context, pricing, vision toggle, plus set as
* default / set as vision model / delete); the "add model" entry point lives in each group
@@ -29,8 +29,8 @@
* Saving does a PUT full-table replace (models not present are deleted; an empty apiKey
* means keep the existing value); only the owner can edit.
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { DragEvent as ReactDragEvent } from "react";
+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { DragEvent as ReactDragEvent, ReactNode } from "react";
import type {
CredentialInfo,
ModelProtocolDetectRequest,
@@ -59,7 +59,6 @@ import { Segmented } from "../../components/ui/segmented";
import { Select } from "../../components/ui/select";
import { Switch } from "../../components/ui/switch";
import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
-import { Badge } from "../../components/ui/badge";
import { Chevron } from "../../components/ui/chevron";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { ProviderLogo } from "../../components/ui/provider-logo";
@@ -78,6 +77,7 @@ import {
import type { FastModeProtocol, ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
import {
allGroupKeys,
+ discountedPrice,
groupModelRows,
hasConfiguredKey,
isFreeModel,
@@ -187,8 +187,11 @@ const TONE_CLASS: Record<SpeedTone, string> = {
red: toneInk.danger,
};
-/** In-page key for one model's speed result. */
-const speedKey = (provider: string, modelId: string) => `${provider}\u0000${modelId}`;
+/**
+ * In-page Map key for a paired reference — the same NUL-separated shape the server uses, and
+ * never persisted. Keys every per-model side table the page holds: speed results, spend totals.
+ */
+const refMapKey = (provider: string, modelId: string) => `${provider}\u0000${modelId}`;
/** Default context window (tokens) for custom models when left unset. */
const CUSTOM_CONTEXT_DEFAULT = 128000;
@@ -369,6 +372,72 @@ export function keyStatusText(row: RowState): string {
return row.envKeyMasked ?? S.models.keyConfigured;
}
+/**
+ * A counter that advances on every clock hour, for prices that change with the time of day.
+ *
+ * DeepSeek's off-peak rate starts and ends on the hour, and every window a catalog schedule can
+ * express is hour-aligned, so waking once an hour is enough to keep a card honest — a page left
+ * open at 08:59 would otherwise still be promising half price at 09:05. It re-aims at the next
+ * hour each time rather than running on a fixed interval, so it neither drifts nor fires 60
+ * times to catch one transition.
+ */
+function useHourTick(): number {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout>;
+ const schedule = (): void => {
+ const now = new Date();
+ const next = new Date(now);
+ next.setMinutes(0, 0, 0);
+ next.setHours(next.getHours() + 1);
+ timer = setTimeout(() => {
+ setTick((n) => n + 1);
+ schedule();
+ }, next.getTime() - now.getTime());
+ };
+ schedule();
+ return () => clearTimeout(timer);
+ }, []);
+ return tick;
+}
+
+/**
+ * What to call a model in prose — its display name, or its upstream id when it has none.
+ *
+ * The blank test is `trim()`, not `!== undefined`: the display name is optional and the dialog
+ * clears it to an empty string, so `displayName ?? modelId` would quote an empty name back at
+ * the user — which is how a save confirmation came to read 「」.
+ */
+export function modelLabelOf(displayName: string | undefined, modelId: string): string {
+ return displayName?.trim() || modelId;
+}
+
+/**
+ * What to store for one price bucket on submit: the value as typed, or — when the field still
+ * holds exactly what was loaded into it — the stored number byte for byte.
+ *
+ * Loading rounds the stored USD to four decimals so it is typeable (`usdToInput`), so
+ * re-encoding an untouched field would commit that rounding as the new price: a silent edit of
+ * a number nobody changed. Small, but not nothing — a catalog row billed at CNY 0.05 per
+ * million lands on $0.0071 instead of $0.00714285…, enough to move a promoted row off the
+ * figure its seller bills and drop the discount mark that says so. Editing the field is what
+ * makes the typed value authoritative.
+ */
+export function priceToSubmit(
+ formValue: string,
+ storedUsd: string | undefined,
+ currency: Currency,
+): string {
+ if (
+ storedUsd !== undefined &&
+ storedUsd !== "" &&
+ formValue.trim() === usdToInput(storedUsd, currency)
+ ) {
+ return storedUsd;
+ }
+ return inputToUsd(formValue, currency);
+}
+
/** DTO -> row edit state (exported for unit tests): provider and modelId are both entry fields, never decomposed. */
export function toRow(m: ModelsResponse["models"][number]): RowState {
const row: RowState = {
@@ -614,6 +683,15 @@ export function ModelsPage() {
// Currency follows the user setting (toggled in sidebar settings).
const { currency } = useTheme();
+ /**
+ * Lifetime Token total per model, keyed by the paired reference. Fetched on its own rather
+ * than folded into the model list: it is telemetry hanging off a configuration page, and a
+ * stats failure must cost the figure, not the page — so the failure path just leaves the map
+ * empty and every card renders without its number.
+ */
+ const [usedTokens, setUsedTokens] = useState<Map<string, number>>(new Map());
+ const hourTick = useHourTick();
+
const load = useCallback(async () => {
if (!projectId) return;
setRows(null);
@@ -630,6 +708,16 @@ export function ModelsPage() {
} catch (e) {
setLoadError(apiErrorText(e));
}
+ try {
+ const totals = await api.getUsageModelTotals(projectId);
+ setUsedTokens(
+ new Map(totals.totals.map((t) => [refMapKey(t.provider, t.modelId), t.tokens])),
+ );
+ } catch {
+ // Fail-soft, and deliberately silent: the page's job is configuring models, and a figure
+ // that could not be read is shown as absent rather than as an error the user cannot act on.
+ setUsedTokens(new Map());
+ }
}, [projectId]);
useEffect(() => {
@@ -736,7 +824,7 @@ export function ModelsPage() {
setSpeedRunning(providerId);
try {
for (const row of targets) {
- const key = speedKey(row.provider, row.modelId);
+ const key = refMapKey(row.provider, row.modelId);
setSpeedResults((prev) => new Map(prev).set(key, "pending"));
try {
const res = await api.testModel(projectId, {
@@ -1026,15 +1114,46 @@ export function ModelsPage() {
provider={group.provider.id}
className="h-5 w-5 shrink-0 text-gray-700 dark:text-gray-300"
/>
- {/* Vendor name can truncate (min-w-0): the actions on the right must not
- shrink, otherwise on narrow screens it would get pushed out of the
- button box and overlap the action text. */}
+ {/* The vendor name is the only thing in this row allowed to take the
+ remaining space, and the only one that truncates. Giving it a
+ minimum width is what made a narrow row overlap: the items beside
+ it never shrink, so once their widths plus that floor exceeded the
+ button, the whole group overflowed the box and ran under the
+ actions. The floor is gone; what gives way instead is the two marks
+ after it, which drop out on a narrow row (below, and the actions'
+ labels do the same at @3xl). The name then always has the leftovers
+ to itself and truncates inside them, so nothing can overlap. */}
<span className="min-w-0 truncate text-sm font-semibold">
{group.provider.label}
</span>
- <span className="shrink-0 whitespace-nowrap font-mono text-xs text-gray-400">
+ <span className="hidden shrink-0 whitespace-nowrap font-mono text-xs text-gray-400 @xl:inline">
{S.models.modelCount(group.rows.length)}
</span>
+ {/* The recommendation rides the collapse bar itself, so it is read with
+ the group's name rather than as a caption floating above the
+ section. `shrink-0` keeps it whole: the vendor name beside it is
+ the element allowed to truncate on a narrow page. */}
+ {group.provider.recommended && (
+ // Not a `Badge`: its `brand` tone is deliberately gray — neutral
+ // emphasis outside the status vocabulary — and an endorsement is
+ // neither a status nor neutral, which is the category tone.ts keeps
+ // out on purpose. Unfilled, like the card marks below it: an outline
+ // is enough to make it a pill, and a block of colour on the collapse
+ // bar competes with the vendor name it is endorsing. It holds on
+ // longer than the model count beside it and gives way before the
+ // name does.
+ //
+ // Gold, and the darker end of it: `yellow-700` (#a16207) is the last
+ // rung that still clears 4.5:1 against this bar's gray-50 — 11px bold
+ // is not WCAG "large text", so the brighter golds above it are not
+ // available in light mode. Dark mode takes yellow-400, the bright
+ // gold, which clears it comfortably on this app's near-black. The
+ // ring is the text's own hue at 40%, in both themes: a ring brighter
+ // than the words it encloses reads as a highlighter, not as gold.
+ <span className="hidden shrink-0 whitespace-nowrap rounded-full border border-yellow-700/40 px-2 py-0.5 text-[11px] font-semibold text-yellow-700 @lg:inline dark:border-yellow-400/40 dark:text-yellow-400">
+ {S.models.recommendedGroup}
+ </span>
+ )}
</button>
{isOwner && (
// Add-model entry point: present on every group header (including
@@ -1183,7 +1302,9 @@ export function ModelsPage() {
currency={currency}
isDefault={sameModelRef(rowRef(row), defaultModel)}
isVisionModel={sameModelRef(rowRef(row), visionModel)}
- speed={speedResults.get(speedKey(row.provider, row.modelId))}
+ speed={speedResults.get(refMapKey(row.provider, row.modelId))}
+ usedTokens={usedTokens.get(refMapKey(row.provider, row.modelId))}
+ hourTick={hourTick}
onOpen={() => setEditing(rowRef(row))}
/>
))
@@ -1729,7 +1850,36 @@ function AddGroupDialog({
// ---------------------------------------------------------------------------
/**
- * Card: display name + upstream id + status badges; context / pricing / key status folded
+ * Card tag palette. Every mark wears one small neutral pill — the same faint surface and border
+ * whatever it says — and the hue survives only in the text. Six marks filling six coloured
+ * chips turned a row of tags into confetti; on a page whose job is scanning names, the marks
+ * are meant to be noticed second.
+ *
+ * Three inks, so the row groups instead of enumerating: what the model IS (its default status),
+ * what it CAN do, and what it COSTS. Identity is carried by the words in every case — the ink
+ * only sorts them at a glance, and never alone says which mark this is.
+ *
+ * These are identities, not judgements, which is why they are spelled here instead of in
+ * `lib/tone.ts`, whose five tones each rate a thing's state — the same reason
+ * `category-colors.ts` and `update-dot.tsx` keep their own colours. Contrast against the
+ * surfaces a card sits on (white and gray-50 in light; this app's overridden gray-950 `#000000`
+ * and gray-900 `#0d0d0d` in dark) clears 4.5:1 for every ink; the shared border is decorative,
+ * so it is not held to 3:1.
+ */
+/** The pill itself: no fill at all, so a row of marks sits on the card rather than on top of it. */
+const TAG_SHAPE =
+ "whitespace-nowrap rounded-full border border-gray-200 px-1.5 text-[10px] font-medium leading-[15px] dark:border-gray-700";
+const TAG_INK = {
+ /** This model's standing in the Project. */
+ status: "text-brand-700 dark:text-brand-300",
+ /** What it can do. */
+ capability: "text-emerald-700 dark:text-emerald-400",
+ /** What it costs. */
+ price: "text-amber-700 dark:text-amber-400",
+} as const;
+
+/**
+ * Card: display name + lifetime Token spend + status badges; context / pricing / key status folded
* into one line of small text; group speed-test results (TTFT / TPS, tone-colored) ride the
* title row's right edge. The whole card is clickable (the model homepage link lives in the
* config dialog).
@@ -1740,6 +1890,8 @@ function ModelCard({
isDefault,
isVisionModel,
speed,
+ usedTokens,
+ hourTick,
onOpen,
}: {
row: RowState;
@@ -1747,19 +1899,118 @@ function ModelCard({
isDefault: boolean;
isVisionModel: boolean;
speed?: SpeedResult | "pending";
+ /** Lifetime Tokens spent on this model; absent for a model that has never run. */
+ usedTokens?: number;
+ /** Bumped on the hour (see useHourTick): the cue to re-read a time-of-day price. */
+ hourTick: number;
onOpen: () => void;
}) {
const priced = row.cacheRead || row.cacheWrite || row.output;
- const meta = [
+ /**
+ * A promoted catalog row. `discountedPrice` returns nothing once the price has been edited
+ * away from the catalog's, and nothing for a row on a time-of-day schedule while it is inside
+ * its peak windows — at peak it is simply at list price, which is what is stored.
+ *
+ * `hourTick` is in the dependency list for that second case: a scheduled row's price changes
+ * on the hour with nobody touching the page, and a card left open would otherwise keep
+ * printing a rate that stopped applying.
+ */
+ const discount = useMemo(() => discountedPrice(row), [row, hourTick]);
+ // The buckets to print: what the seller bills right now. They differ from the stored numbers
+ // only for a scheduled discount, whose stored price is the peak one.
+ const shownPrice = discount
+ ? {
+ cacheRead: String(discount.billed.cacheRead),
+ cacheWrite: String(discount.billed.cacheWrite),
+ output: String(discount.billed.output),
+ }
+ : { cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output };
+ /**
+ * Every standing mark this row carries, in one horizontal row of its own.
+ *
+ * They had been sharing the title's line, where each was width the model's NAME had to give
+ * up — a long name truncated to make room for a mark that could have been read anywhere. A
+ * row of their own costs one line and gives the name the whole of the first.
+ *
+ * Order is fixed rather than by which happen to be true, so the eye can learn where to look:
+ * what this Project chose (default, vision proxy) before what the model is (vision, fast,
+ * free) before what it costs today (the discount).
+ */
+ const tags: Array<{ key: string; label: string; title?: string; className: string }> = [
+ ...(isDefault
+ ? [
+ {
+ key: "default",
+ label: S.models.default,
+ className: TAG_INK.status,
+ },
+ ]
+ : []),
+ ...(row.vision
+ ? [
+ {
+ key: "vision",
+ label: S.models.visionBadge,
+ className: TAG_INK.capability,
+ },
+ ]
+ : []),
+ ...(isVisionModel
+ ? [
+ {
+ key: "visionModel",
+ label: S.models.visionModelBadge,
+ className: TAG_INK.capability,
+ },
+ ]
+ : []),
+ ...(row.fastMode
+ ? [
+ {
+ key: "fastMode",
+ label: S.models.fastModeBadge,
+ className: TAG_INK.capability,
+ },
+ ]
+ : []),
+ ...(isFreeModel(row)
+ ? [
+ {
+ key: "free",
+ label: S.models.freeBadge,
+ className: TAG_INK.price,
+ },
+ ]
+ : []),
+ ...(discount
+ ? [
+ {
+ key: "discount",
+ label: S.models.discountBadge(discount.percent),
+ title: discount.scheduled
+ ? S.models.offPeakTitle(discount.percent)
+ : S.models.discountTitle(discount.percent),
+ className: TAG_INK.price,
+ },
+ ]
+ : []),
+ ];
+
+ const priceLine = (a: string, b: string, c: string): string =>
+ `${displayPrice(a, currency)} / ${displayPrice(b, currency)} / ${displayPrice(c, currency)}`;
+ const meta: ReactNode[] = [
row.contextWindow ? humanizeTokens(Number(row.contextWindow)) : null,
// Three prices (cache read / cache write / output); units are explained in the config dialog, not repeated on the card.
- priced
- ? `${displayPrice(row.cacheRead, currency)} / ${displayPrice(row.cacheWrite, currency)} / ${displayPrice(row.output, currency)}`
- : null,
+ // One price, the one being billed right now. What the row would cost without the promotion
+ // answers no question a reader of this list is asking, and spending the meta line's width
+ // on it pushes out the figures that do.
+ priced ? (
+ <span>{priceLine(shownPrice.cacheRead, shownPrice.cacheWrite, shownPrice.output)}</span>
+ ) : null,
// Key status (see keyStatusText): the stored mask, a detected env fallback's mask, a plain
// "configured" for a key typed but not yet saved, or "not configured".
keyStatusText(row),
- ].filter((v): v is string => v !== null);
+ ].filter((v) => v !== null);
const speedBadges =
speed === "pending" ? (
@@ -1799,35 +2050,51 @@ function ModelCard({
<button
type="button"
onClick={onOpen}
- className="flex w-full flex-col gap-0.5 rounded-md border border-gray-200 px-3 py-2.5 text-left transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:bg-gray-800/40"
+ className="flex w-full flex-col gap-1 rounded-md border border-gray-200 px-3 py-2.5 text-left transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:bg-gray-800/40"
>
- <span className="flex flex-wrap items-center gap-1.5">
- <span className="text-sm font-medium">{row.displayName ?? row.modelId}</span>
- {isDefault && <Badge tone="brand">{S.models.default}</Badge>}
- {/* Free rows (all three price buckets 0, e.g. :free variants / openrouter/free): a
- light-yellow badge so zero-cost models stand out at a glance (informational, kept
- distinct from the amber warning tone the proxy-vision badge uses). */}
- {isFreeModel(row) && <Badge tone="yellow">{S.models.freeBadge}</Badge>}
- {row.vision && <Badge tone="green">{S.models.visionBadge}</Badge>}
- {isVisionModel && <Badge tone="amber">{S.models.visionModelBadge}</Badge>}
- {/* Fast mode moves the model onto a premium price list that the recorded prices do not
- reflect, so it has to be visible without opening the dialog (amber, like the other
- badge that flags a standing cost/behavior choice). */}
- {row.fastMode && <Badge tone="amber">{S.models.fastModeBadge}</Badge>}
- </span>
- {/* Upstream id in small text (grouping already separates by group, no composite id is
- shown anymore); when there's no display name, the main line is already the
- upstream id, so it isn't repeated on a second line. */}
- {row.displayName !== undefined && (
- <span className="truncate font-mono text-[11px] text-gray-500 dark:text-gray-400">
- {row.modelId}
+ {/* 1. What the model is called — the name alone. The upstream id used to share this row,
+ but it is a detail you go looking for rather than one you scan by, and it is a click
+ away in the config dialog; the width it was taking now belongs to the name. */}
+ <span className="flex w-full min-w-0 items-baseline gap-2">
+ <span className="min-w-0 flex-1 truncate text-[13px] font-medium">
+ {modelLabelOf(row.displayName, row.modelId)}
</span>
- )}
- {/* Meta line: the truncating text takes the flexible space; speed badges keep their own
+ {/* What this model has spent over its whole life, on the row's right edge. Recessive by
+ design — grey and a size below the meta line: it is context for a name you are
+ scanning past, not a figure the page is about. A model that has never run shows
+ nothing rather than a zero, which would read as a measurement instead of an
+ absence. */}
+ {usedTokens !== undefined && usedTokens > 0 && (
+ <span
+ className="shrink-0 text-[10px] tabular-nums text-gray-400 dark:text-gray-500"
+ title={S.models.usedTokensTitle}
+ >
+ {S.models.usedTokens(humanizeTokens(usedTokens))}
+ </span>
+ )}
+ </span>
+ {/* 2. Every standing mark, on one row of its own (see `tags`). The row is rendered even
+ when empty: most models carry no mark at all, and letting it collapse would leave the
+ grid ragged — cards in the same row of a two-column grid stretch to the tallest, so an
+ absent line shows up as uneven padding rather than as a shorter card. Its height is
+ the tags' own, so a card with marks and a card without are exactly as tall. */}
+ <span className="flex min-h-[17px] w-full flex-wrap items-center gap-1">
+ {tags.map((tag) => (
+ <span key={tag.key} title={tag.title} className={`${TAG_SHAPE} ${tag.className}`}>
+ {tag.label}
+ </span>
+ ))}
+ </span>
+ {/* 3. Meta line: the truncating text takes the flexible space; speed badges keep their own
non-shrinking slot on the right so the numbers never wrap or get pushed out. */}
<span className="flex w-full items-center gap-1.5">
<span className="min-w-0 flex-1 truncate text-[11px] text-gray-400 dark:text-gray-500">
- {meta.join(" · ")}
+ {meta.map((part, i) => (
+ <Fragment key={i}>
+ {i > 0 && " · "}
+ {part}
+ </Fragment>
+ ))}
</span>
{speedBadges}
</span>
@@ -2224,6 +2491,8 @@ function ModelDialog({
const suffixLabel =
showProtocolPicker && protocolChoice === null ? S.models.protocolUnset : protocolPath;
+ const modelLabel = modelLabelOf(form.displayName, form.modelId);
+
const validated = (): RowState | null => {
const modelId = form.modelId.trim();
const ref: ModelRefDto = { provider: form.provider, modelId };
@@ -2274,9 +2543,9 @@ function ModelDialog({
// Custom models with an empty context window fall back to the default value (preset models left empty just mean "unknown", not auto-filled).
contextWindow:
!preset && !contextWindow ? String(CUSTOM_CONTEXT_DEFAULT) : form.contextWindow,
- cacheRead: inputToUsd(form.cacheRead, currency),
- cacheWrite: inputToUsd(form.cacheWrite, currency),
- output: inputToUsd(form.output, currency),
+ cacheRead: priceToSubmit(form.cacheRead, row?.cacheRead, currency),
+ cacheWrite: priceToSubmit(form.cacheWrite, row?.cacheWrite, currency),
+ output: priceToSubmit(form.output, row?.output, currency),
};
};
@@ -2520,28 +2789,46 @@ function ModelDialog({
}
>
<div className="space-y-3">
- {/* Header: logo + display name + badges + upstream id (existing model); the model
- homepage entry lives here as a small secondary button on the right (moved out of
- the form body — it's a property of the model, not an input). */}
+ {/* Header: the logo, and beside it one line each for the name, the upstream id and the
+ marks. The marks used to share the name's line, where they pushed a long name into
+ wrapping under them and left the header two ragged lines tall; on a line of their
+ own the name keeps the width it needs. Same pills the cards wear, so the list and
+ the dialog agree about what a mark looks like. The model homepage entry stays a
+ small secondary button on the right — a property of the model, not an input. */}
{!isNew && (
<div className="flex items-center gap-2.5 rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800/60">
<ProviderLogo
provider={form.provider}
className="h-6 w-6 shrink-0 text-gray-700 dark:text-gray-300"
/>
- <div className="flex min-w-0 flex-1 flex-col">
- <span className="flex flex-wrap items-center gap-1.5 text-sm font-medium">
- {form.displayName ?? form.modelId}
- {isDefault && <Badge tone="brand">{S.models.default}</Badge>}
- {form.vision && <Badge tone="green">{S.models.visionBadge}</Badge>}
- {isVisionModel && <Badge tone="amber">{S.models.visionModelBadge}</Badge>}
- </span>
- {/* Upstream id in small text: when there's no display name, the main line is already showing it, so don't repeat. */}
- {form.displayName !== undefined && (
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-sm font-medium">{modelLabel}</span>
+ {/* Upstream id in small text: when there's no display name the line above is
+ already showing it, so don't repeat. Tested on the trimmed value, not on
+ `undefined`: clearing the field leaves an empty string, which is just as
+ nameless. */}
+ {form.displayName?.trim() && (
<span className="truncate font-mono text-xs text-gray-500 dark:text-gray-400">
{form.modelId}
</span>
)}
+ {(isDefault || form.vision || isVisionModel) && (
+ <span className="flex flex-wrap items-center gap-1 pt-0.5">
+ {isDefault && (
+ <span className={`${TAG_SHAPE} ${TAG_INK.status}`}>{S.models.default}</span>
+ )}
+ {form.vision && (
+ <span className={`${TAG_SHAPE} ${TAG_INK.capability}`}>
+ {S.models.visionBadge}
+ </span>
+ )}
+ {isVisionModel && (
+ <span className={`${TAG_SHAPE} ${TAG_INK.capability}`}>
+ {S.models.visionModelBadge}
+ </span>
+ )}
+ </span>
+ )}
</div>
{row && modelHomepageUrl(row.provider, row.modelId) && (
<a
@@ -3051,7 +3338,7 @@ function ModelDialog({
}}
>
<p className="text-sm text-gray-700 dark:text-gray-300">
- {CONFIRM_BODY[confirming](form.displayName ?? form.modelId)}
+ {CONFIRM_BODY[confirming](modelLabel)}
</p>
</ConfirmModal>
)}
diff --git a/packages/web/src/lib/format.ts b/packages/web/src/lib/format.ts
index 74f5d4fd..733a8ddf 100644
--- a/packages/web/src/lib/format.ts
+++ b/packages/web/src/lib/format.ts
@@ -2,7 +2,7 @@
* Human-friendly formatting utilities.
*
* Token and duration abbreviation conventions exactly match the CLI
- * (packages/cli/src/render.ts): `4k`, `1.2k`, `1.5M`, `820ms`, `5.1s`,
+ * (packages/cli/src/render.ts): `4k`, `1.2k`, `1.5M`, `17.7B`, `820ms`, `5.1s`,
* `2m10s`; deltas are explicitly signed (`+1k` / `-1k`). Also provides
* display formats for cost (USD), byte counts, and dates, reused by the
* stats page and Trace page.
@@ -14,12 +14,13 @@ function trimZero(v: number): string {
return s.endsWith(".0") ? s.slice(0, -2) : s;
}
-/** Abbreviate a token count for humans: 1234→1.2k, 1500000→1.5M, <1000 unchanged. */
+/** Abbreviate a token count for humans: 1234→1.2k, 1500000→1.5M, 1.77e10→17.7B, <1000 unchanged. */
export function humanizeTokens(n: number): string {
const abs = Math.abs(n);
if (abs < 1000) return `${n}`;
if (abs < 1_000_000) return `${trimZero(n / 1000)}k`;
- return `${trimZero(n / 1_000_000)}M`;
+ if (abs < 1_000_000_000) return `${trimZero(n / 1_000_000)}M`;
+ return `${trimZero(n / 1_000_000_000)}B`;
}
/**
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 01674625..235d41b6 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -819,7 +819,19 @@ export const en: Strings = {
fastModeBadge: "Fast",
visionBadge: "Vision",
freeBadge: "Free",
+ /**
+ * Rides the group's own collapse bar, which on this group carries five actions — the most
+ * crowded row on the page. One word, because the vendor name beside it is what a reader
+ * needs first and is the element that truncates.
+ */
+ recommendedGroup: "Recommended",
+ discountBadge: (pct: number): string => `-${pct}%`,
+ discountTitle: (pct: number): string => `Promotion: ${pct}% off the list price`,
+ offPeakTitle: (pct: number): string =>
+ `Off-peak rate: ${pct}% off list. Peak hours bill at list price — 09:00–12:00 and 14:00–18:00 Beijing time, Monday to Friday`,
visionModelBadge: "Proxy vision",
+ usedTokens: (v: string) => `${v} toks`,
+ usedTokensTitle: "Tokens this model has used, all time",
setVisionModel: "Set as proxy vision model",
visionModelHint: "Describes images via describe_image for models without vision",
priceUnitShort: "/M tok",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 818d4f90..c20b9445 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -796,7 +796,21 @@ export const zh = {
visionBadge: "视觉",
/** Light-yellow badge on zero-cost models (all three price buckets 0, e.g. the :free variants and openrouter/free). */
freeBadge: "免费",
+ /**
+ * Caption above a provider group the catalog marks as recommended. It travels with the
+ * group, so a user who drags that group elsewhere still sees why it is called out.
+ */
+ recommendedGroup: "官方推荐",
+ /** Badge on a row the seller is currently discounting: the rate off its list price. */
+ discountBadge: (pct: number): string => `-${pct}%`,
+ discountTitle: (pct: number): string => `促销价:已在牌价基础上打 ${pct}% 折扣`,
+ /** Same badge as a flat promotion; only the explanation differs, because this rate comes and goes with the clock. */
+ offPeakTitle: (pct: number): string =>
+ `空闲时段价:比牌价低 ${pct}%。高峰时段按牌价计费——北京时间周一至周五 9:00–12:00、14:00–18:00`,
visionModelBadge: "视觉代理",
+ /** Card's right-edge figure: what this model has spent over its whole life. The unit stays English and is abbreviated the way the rest of the page abbreviates it — `tok/s`, `/M tok`. */
+ usedTokens: (v: string) => `${v} toks`,
+ usedTokensTitle: "该模型累计消耗的 Token(不限时间范围)",
setVisionModel: "设为视觉代理模型",
visionModelHint: "供不支持图片的模型经 describe_image 代读图片",
priceUnitShort: "/M tok",
@@ -804,8 +818,8 @@ export const zh = {
testing: "测试中…",
testOk: (ms: number): string => `连通正常(${ms} ms)`,
testFailed: (msg: string): string => `连通失败:${msg}`,
- priceCacheRead: "缓存读取价格",
- priceCacheWrite: "缓存写入价格",
+ priceCacheRead: "缓存命中价格",
+ priceCacheWrite: "缓存未命中价格",
priceOutput: "输出价格",
currency: "币种",
currencyUsd: "美元 $",
@@ -2154,9 +2168,9 @@ Benchmark:
requests: "Requests",
from: "起始日期",
to: "结束日期",
- colCacheRead: "cache_read",
- colCacheWrite: "cache_write",
- colOutput: "output",
+ colCacheRead: "缓存命中",
+ colCacheWrite: "缓存未命中",
+ colOutput: "输出",
uncostedNote: "* 只计入配置了价格的模型成本",
filterAllAgents: "全部 Agent",
filterAllModels: "全部模型",
diff --git a/packages/web/test/format.test.ts b/packages/web/test/format.test.ts
index 79f0f66b..f5ab9a9a 100644
--- a/packages/web/test/format.test.ts
+++ b/packages/web/test/format.test.ts
@@ -45,6 +45,13 @@ describe("humanizeTokens", () => {
expect(humanizeTokens(2_000_000)).toBe("2M");
});
+ it("billions abbreviated — a lifetime model total reaches them", () => {
+ expect(humanizeTokens(1_000_000_000)).toBe("1B");
+ expect(humanizeTokens(17_700_000_000)).toBe("17.7B");
+ // The boundary belongs to M, so the two tiers cannot both claim it.
+ expect(humanizeTokens(999_900_000)).toBe("999.9M");
+ });
+
it("negatives keep the sign (context shrink)", () => {
expect(humanizeTokens(-1200)).toBe("-1.2k");
expect(humanizeTokens(-500)).toBe("-500");
diff --git a/packages/web/test/model-group-expansion.test.ts b/packages/web/test/model-group-expansion.test.ts
index 8473263e..c09a3f64 100644
--- a/packages/web/test/model-group-expansion.test.ts
+++ b/packages/web/test/model-group-expansion.test.ts
@@ -34,12 +34,16 @@ function memStorage(): ExpansionStorage & { map: Map<string, string> } {
};
}
+/** The group the catalog puts first, which is the one the page opens on with nothing stored. */
+const LEAD_GROUP = MODEL_PROVIDERS[0]!.id;
+
describe("defaultExpandedProviders", () => {
- it("contains exactly deepseek, the first provider of the catalog", () => {
- expect([...defaultExpandedProviders()]).toEqual(["deepseek"]);
- // The default leans on the catalog ordering promise (DeepSeek first): pin it here so a
- // reordering shows up as this failure instead of a silently odd default.
- expect(MODEL_PROVIDERS[0]?.id).toBe("deepseek");
+ it("contains exactly the leading catalog group, and follows it when the curation changes", () => {
+ expect([...defaultExpandedProviders()]).toEqual([MODEL_PROVIDERS[0]!.id]);
+ // The group that leads is a product decision, so it is spelled out once here: the page
+ // opens on the recommended group rather than on whichever id used to be hard-coded.
+ expect(MODEL_PROVIDERS[0]!.id).toBe("tokendance");
+ expect(MODEL_PROVIDERS[0]!.recommended).toBe(true);
});
it("returns a fresh set per call (React state must not share one mutable instance)", () => {
@@ -55,7 +59,7 @@ describe("isGroupExpanded", () => {
const expanded = defaultExpandedProviders();
it("without a search query, only members of the expanded set are open", () => {
- expect(isGroupExpanded(expanded, "deepseek", false)).toBe(true);
+ expect(isGroupExpanded(expanded, LEAD_GROUP, false)).toBe(true);
expect(isGroupExpanded(expanded, "anthropic", false)).toBe(false);
expect(isGroupExpanded(expanded, "custom", false)).toBe(false);
// User-defined groups are decided by the same membership rule — collapsed until toggled.
@@ -84,7 +88,7 @@ describe("isGroupExpanded", () => {
// Clearing the query falls back to the stored set: the same groups collapse again.
for (const g of groups) {
expect(isGroupExpanded(defaultExpandedProviders(), g.provider.id, false)).toBe(
- g.provider.id === "deepseek",
+ g.provider.id === LEAD_GROUP,
);
}
});
@@ -95,21 +99,21 @@ describe("toggleExpandedProvider", () => {
const initial = defaultExpandedProviders();
const withAnthropic = toggleExpandedProvider(initial, "anthropic");
expect(withAnthropic.has("anthropic")).toBe(true);
- expect(withAnthropic.has("deepseek")).toBe(true);
+ expect(withAnthropic.has(LEAD_GROUP)).toBe(true);
expect(initial.has("anthropic")).toBe(false); // input untouched (React state discipline)
- const withoutDeepseek = toggleExpandedProvider(withAnthropic, "deepseek");
- expect(withoutDeepseek.has("deepseek")).toBe(false);
- expect(withoutDeepseek.has("anthropic")).toBe(true);
- expect(withAnthropic.has("deepseek")).toBe(true);
+ const withoutLead = toggleExpandedProvider(withAnthropic, LEAD_GROUP);
+ expect(withoutLead.has(LEAD_GROUP)).toBe(false);
+ expect(withoutLead.has("anthropic")).toBe(true);
+ expect(withAnthropic.has(LEAD_GROUP)).toBe(true);
});
});
describe("persisted expansion (per-Project localStorage)", () => {
- it("nothing stored — or no Project yet — falls back to the DeepSeek-only default", () => {
+ it("nothing stored — or no Project yet — falls back to the leading group alone", () => {
const s = memStorage();
- expect([...loadExpandedProviders("p1", s)]).toEqual(["deepseek"]);
- expect([...loadExpandedProviders(null, s)]).toEqual(["deepseek"]);
+ expect([...loadExpandedProviders("p1", s)]).toEqual([LEAD_GROUP]);
+ expect([...loadExpandedProviders(null, s)]).toEqual([LEAD_GROUP]);
expect(s.map.size).toBe(0); // load never writes; save without a Project is a no-op
saveExpandedProviders(null, new Set(["openai"]), s);
expect(s.map.size).toBe(0);
@@ -119,7 +123,7 @@ describe("persisted expansion (per-Project localStorage)", () => {
const s = memStorage();
let set = loadExpandedProviders("p1", s);
set = toggleExpandedProvider(set, "anthropic"); // open anthropic
- set = toggleExpandedProvider(set, "deepseek"); // close deepseek
+ set = toggleExpandedProvider(set, LEAD_GROUP); // close the group that opens by default
saveExpandedProviders("p1", set, s);
const restored = loadExpandedProviders("p1", s);
expect(restored).toEqual(new Set(["anthropic"]));
@@ -136,7 +140,7 @@ describe("persisted expansion (per-Project localStorage)", () => {
const s = memStorage();
for (const raw of ["{not json", '"deepseek"', "42", "null", "{}", ""]) {
s.map.set(expandedGroupsKey("p1"), raw);
- expect([...loadExpandedProviders("p1", s)]).toEqual(["deepseek"]);
+ expect([...loadExpandedProviders("p1", s)]).toEqual([LEAD_GROUP]);
}
// An array survives element-level junk: non-strings are filtered, strings kept.
s.map.set(expandedGroupsKey("p1"), '["anthropic", 7, null, {"x": 1}]');
@@ -150,7 +154,7 @@ describe("persisted expansion (per-Project localStorage)", () => {
expect([...loadExpandedProviders("p1", s)]).toEqual(["openai"]);
expect(loadExpandedProviders("p2", s)).toEqual(new Set(["moonshot", "my-proxy"]));
// A third Project is untouched by the writes above and opens on the default.
- expect([...loadExpandedProviders("p3", s)]).toEqual(["deepseek"]);
+ expect([...loadExpandedProviders("p3", s)]).toEqual([LEAD_GROUP]);
});
it("stale ids of since-deleted groups are harmless and survive round-trips", () => {
@@ -178,6 +182,6 @@ describe("persisted expansion (per-Project localStorage)", () => {
},
};
expect(() => saveExpandedProviders("p1", new Set(["openai"]), broken)).not.toThrow();
- expect([...loadExpandedProviders("p1", broken)]).toEqual(["deepseek"]);
+ expect([...loadExpandedProviders("p1", broken)]).toEqual([LEAD_GROUP]);
});
});
diff --git a/packages/web/test/model-group-order.test.ts b/packages/web/test/model-group-order.test.ts
index bebbbe85..ab6ebe33 100644
--- a/packages/web/test/model-group-order.test.ts
+++ b/packages/web/test/model-group-order.test.ts
@@ -185,6 +185,35 @@ describe("groupModelRows with a manual group order", () => {
]);
});
+ it("a stored order survives a change to the catalog's DEFAULT sequence", () => {
+ // A drop materialises every group key, so any Project that has ever reordered its
+ // groups holds a full arrangement — and re-curating MODEL_PROVIDERS cannot move a
+ // single group for that user. Only a Project with nothing stored follows the default.
+ const dropped = commitModelGroupOrder([], allGroupKeys(rows), "minimax", "anthropic", false);
+ expect(dropped).toEqual(expect.arrayContaining(CATALOG_IDS));
+ const before = groupModelRows(rows, "", dropped).map((g) => g.provider.id);
+ // Simulate a later release promoting some group to the front of the catalog order: the
+ // stored array pins every key, so the rendered order is unchanged.
+ const recurated = [
+ CATALOG_IDS.at(-2)!,
+ ...CATALOG_IDS.filter((id) => id !== CATALOG_IDS.at(-2)),
+ ];
+ expect(recurated).not.toEqual(CATALOG_IDS);
+ const after = orderModelGroups(
+ recurated.map((id) => ({ id })),
+ (g) => g.id,
+ dropped,
+ ).map((g) => g.id);
+ expect(after).toEqual(
+ orderModelGroups(
+ CATALOG_IDS.map((id) => ({ id })),
+ (g) => g.id,
+ dropped,
+ ).map((g) => g.id),
+ );
+ expect(before).toEqual(groupModelRows(rows, "", dropped).map((g) => g.provider.id));
+ });
+
it("stale keys are inert — a stored group that no longer exists changes nothing", () => {
expect(idsOf(["gone-vendor", "minimax", "also-gone"])).toEqual(idsOf(["minimax"]));
});
diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.ts
index fb46f1a8..2db0dbf9 100644
--- a/packages/web/test/model-grouping.test.ts
+++ b/packages/web/test/model-grouping.test.ts
@@ -12,8 +12,13 @@
* configured or on showAll.
*/
import { describe, expect, it } from "vitest";
-import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
import {
+ MODEL_PROVIDERS,
+ catalogEntryFor,
+ effectivePricing,
+} from "@prismshadow/penguin-core/model-catalog";
+import {
+ discountedPrice,
groupModelRows,
hasConfiguredKey,
isFreeModel,
@@ -76,8 +81,11 @@ describe("groupModelRows", () => {
expect(groups[4]!.provider.envKey).toBe("OPENAI_API_KEY");
expect(groups[4]!.rows.map((r) => r.modelId)).toEqual(["weird-model"]);
// Group order matches MODEL_PROVIDERS, whose sequence is hand-curated (gateways and
- // first-party vendors interleaved): DeepSeek first, custom last.
+ // first-party vendors interleaved): TokenDance first as the recommended group, DeepSeek
+ // next as the default model's provider, custom last. This is the page's DEFAULT — the
+ // stored per-Project order applied below overrides it.
expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual([
+ "tokendance",
"deepseek",
"openrouter",
"fireworks",
@@ -85,7 +93,6 @@ describe("groupModelRows", () => {
"openai",
"anthropic",
"siliconflow",
- "tokendance",
"zhipu",
"moonshot",
"minimax",
@@ -329,3 +336,114 @@ describe("isFreeModel", () => {
expect(isFreeModel({ cacheRead: "0", cacheWrite: "0", output: "3" })).toBe(false);
});
});
+describe("discountedPrice", () => {
+ /**
+ * A row carrying exactly what "sync presets" would write for a catalog entry: the discounted
+ * price for a flat promotion, the peak price for a scheduled one (which is never baked in).
+ */
+ const syncedRow = (provider: string, modelId: string) => {
+ const entry = catalogEntryFor(provider, modelId)!;
+ const billed = (entry.offPeakDiscount !== undefined ? entry.pricing : effectivePricing(entry))!;
+ return {
+ provider,
+ modelId,
+ cacheRead: String(billed.cache_read),
+ cacheWrite: String(billed.cache_write),
+ output: String(billed.output),
+ };
+ };
+
+ it("a synced row on a flat promotion reports the rate, and bills at the stored price", () => {
+ const row = syncedRow("tokendance", "glm-5.3-flash");
+ const found = discountedPrice(row)!;
+ expect(found.percent).toBe(50);
+ expect(found.scheduled).toBe(false);
+ // A flat promotion is baked in at sync time, so what is billed is what is stored.
+ expect(found.billed).toEqual({
+ cacheRead: Number(row.cacheRead),
+ cacheWrite: Number(row.cacheWrite),
+ output: Number(row.output),
+ });
+ // And it really is below the catalog's list price.
+ const entry = catalogEntryFor("tokendance", "glm-5.3-flash")!;
+ expect(entry.pricing!.cache_write).toBeGreaterThan(found.billed.cacheWrite);
+ });
+
+ // Beijing is UTC+8, so 01:00Z is 09:00 there. 2026-08-31 is a Monday.
+ const PEAK = new Date("2026-08-31T01:30:00Z");
+ const OFF_PEAK = new Date("2026-08-31T05:00:00Z");
+
+ it("a scheduled row is marked and halved off-peak, and left at list price at peak", () => {
+ const row = syncedRow("deepseek", "deepseek-v4-flash");
+ const entry = catalogEntryFor("deepseek", "deepseek-v4-flash")!;
+
+ const off = discountedPrice(row, OFF_PEAK)!;
+ expect(off.percent).toBe(50);
+ expect(off.scheduled).toBe(true);
+ expect(off.billed.output).toBeCloseTo(entry.pricing!.output / 2, 6);
+
+ // At peak the row carries no mark at all: the stored price is the price.
+ expect(discountedPrice(row, PEAK)).toBeUndefined();
+ });
+
+ it("a scheduled row whose price was edited is never halved, at either hour", () => {
+ const row = { ...syncedRow("deepseek", "deepseek-v4-pro"), output: "1.234" };
+ expect(discountedPrice(row, OFF_PEAK)).toBeUndefined();
+ expect(discountedPrice(row, PEAK)).toBeUndefined();
+ });
+
+ it("undiscounted catalog rows, off-catalog rows and unpriced rows report nothing", () => {
+ expect(discountedPrice(syncedRow("tokendance", "qwen3.8-flash"))).toBeUndefined();
+ expect(discountedPrice(syncedRow("tokendance", "hy4-preview"))).toBeUndefined();
+ expect(
+ discountedPrice({
+ provider: "custom",
+ modelId: "my-proxy",
+ cacheRead: "1",
+ cacheWrite: "2",
+ output: "3",
+ }),
+ ).toBeUndefined();
+ expect(discountedPrice({ provider: "tokendance", modelId: "kimi-k3" })).toBeUndefined();
+ expect(
+ discountedPrice({
+ provider: "tokendance",
+ modelId: "kimi-k3",
+ cacheRead: "",
+ cacheWrite: "",
+ output: "",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("an edited price drops the decoration: a hand-typed number is not a discount off list", () => {
+ const row = syncedRow("tokendance", "kimi-k3");
+ expect(discountedPrice(row)).toBeDefined();
+ expect(discountedPrice({ ...row, output: "9.99" })).toBeUndefined();
+ // A row still holding the LIST price (a Project that has not synced presets) is not
+ // being billed the promotional rate, so it gets no badge either.
+ const entry = catalogEntryFor("tokendance", "kimi-k3")!;
+ expect(
+ discountedPrice({
+ ...row,
+ cacheRead: String(entry.pricing!.cache_read),
+ cacheWrite: String(entry.pricing!.cache_write),
+ output: String(entry.pricing!.output),
+ }),
+ ).toBeUndefined();
+ });
+
+ it("accepts the DTO's numeric buckets as well as the edit form's strings", () => {
+ const row = syncedRow("tokendance", "qwen3.8-max");
+ expect(discountedPrice(row)?.percent).toBe(10);
+ expect(
+ discountedPrice({
+ provider: row.provider,
+ modelId: row.modelId,
+ cacheRead: Number(row.cacheRead),
+ cacheWrite: Number(row.cacheWrite),
+ output: Number(row.output),
+ })?.percent,
+ ).toBe(10);
+ });
+});
diff --git a/packages/web/test/models-input.test.ts b/packages/web/test/models-input.test.ts
index 74f7869f..9d0cf90b 100644
--- a/packages/web/test/models-input.test.ts
+++ b/packages/web/test/models-input.test.ts
@@ -23,6 +23,8 @@ import {
detectedEnvKeys,
digitsOnly,
fastModeState,
+ modelLabelOf,
+ priceToSubmit,
hasKey,
keyStatusText,
nextPointers,
@@ -31,6 +33,50 @@ import {
} from "../src/features/models/models-page";
import { S } from "../src/lib/strings";
+describe("priceToSubmit", () => {
+ // The catalog bills this row at CNY 0.05 per million, i.e. $0.00714285714... The form can
+ // only show four decimals, so the loaded field reads 0.0071.
+ const STORED = "0.007142857";
+
+ it("returns the stored number untouched when the field still holds what was loaded", () => {
+ expect(priceToSubmit("0.0071", STORED, "USD")).toBe(STORED);
+ // Same in CNY, where the round trip also passes through the x7 conversion.
+ expect(priceToSubmit("0.05", STORED, "CNY")).toBe(STORED);
+ });
+
+ it("takes the typed value once the field has actually been edited", () => {
+ expect(priceToSubmit("0.9", STORED, "USD")).toBe("0.9");
+ expect(priceToSubmit("7", STORED, "CNY")).toBe("1");
+ });
+
+ it("encodes normally when there is nothing stored to preserve", () => {
+ expect(priceToSubmit("0.0071", undefined, "USD")).toBe("0.0071");
+ expect(priceToSubmit("0.0071", "", "USD")).toBe("0.0071");
+ });
+
+ it("passes an emptied field through as empty, which clears the price", () => {
+ expect(priceToSubmit("", STORED, "USD")).toBe("");
+ });
+});
+
+describe("modelLabelOf", () => {
+ it("prefers the display name", () => {
+ expect(modelLabelOf("My GPT", "gpt-5.5")).toBe("My GPT");
+ });
+
+ it("falls back to the id when the name was cleared, not just when it was never set", () => {
+ // The dialog clears the field to "", so `?? modelId` would hand back an empty label — which
+ // is how a save confirmation came to quote an empty name.
+ expect(modelLabelOf(undefined, "gpt-5.5")).toBe("gpt-5.5");
+ expect(modelLabelOf("", "gpt-5.5")).toBe("gpt-5.5");
+ expect(modelLabelOf(" ", "gpt-5.5")).toBe("gpt-5.5");
+ });
+
+ it("keeps a name that merely has padding around it", () => {
+ expect(modelLabelOf(" My GPT ", "gpt-5.5")).toBe("My GPT");
+ });
+});
+
describe("digitsOnly (context window)", () => {
it("keeps digits only", () => {
expect(digitsOnly("200000")).toBe("200000");
diff --git a/packages/web/test/protocol-path.test.ts b/packages/web/test/protocol-path.test.ts
index c963506f..e5ce92e2 100644
--- a/packages/web/test/protocol-path.test.ts
+++ b/packages/web/test/protocol-path.test.ts
@@ -39,6 +39,7 @@ describe("protocolPathForModel", () => {
"openrouter",
"fireworks",
"siliconflow",
+ "tokendance",
"qwen-token-plan",
"qwen-pay-as-you-go",
]) {