* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读
Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。
* 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
* 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
(dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
(ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
* WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
正是本次要消灭的那类"两页对不上",只是方向相反。
* dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
一样的读法,好让请求表的若干列有东西可填。
* 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
同一通调用会在每个 fork 上再花一次。
* WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
文件、不是子代理的"用的。
夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。
TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。
验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。
* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏
用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。
* usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
(流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
* 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
* 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
到全部的路。
* /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
方块样式在下一个提交里。
* Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。
Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。
验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。
* gui: 请求页把来源拆成三栏,汇总那一排也改成方块
用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。
* 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
* 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
四项合计,和上面 KPI 的算法一致。
* 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
the same element across redraws, changed in place, so one being pressed or focused is
never swapped out"),正在点的那个不该被换掉。
* 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
不参与这套分隔线。
* 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
* 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
* 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
i18n-keys 绿)。
验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。
---------
Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
571 lines
19 KiB
Go
571 lines
19 KiB
Go
package gui
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/agent"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// usageGroup is a usage.Group with what the UI needs to draw it.
|
|
type usageGroup struct {
|
|
usage.Group
|
|
Name string `json:"name"`
|
|
Sub string `json:"sub,omitempty"` // models: the provider's name
|
|
Icon string `json:"icon,omitempty"` // a real logo, or "generic" for an unknown client
|
|
}
|
|
|
|
type usageJSON struct {
|
|
usage.Summary
|
|
Agents []usageGroup `json:"agents"`
|
|
Models []usageGroup `json:"models"`
|
|
Accounts []usageGroup `json:"accounts"`
|
|
CallerKeys []usageGroup `json:"callerKeys"`
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
func usageState(p usage.Period) usageJSON {
|
|
s := usage.Summarize(p)
|
|
out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Accounts: []usageGroup{}, Path: tilde(usage.Path())}
|
|
agents := map[string]*agent.Agent{}
|
|
for _, a := range agent.Clients() {
|
|
agents[a.ID] = a
|
|
}
|
|
for _, g := range s.Agents {
|
|
ug := usageGroup{Group: g, Name: g.ID, Icon: "generic"}
|
|
if a := agents[g.ID]; a != nil {
|
|
ug.Name, ug.Icon = a.Name, a.Icon
|
|
}
|
|
out.Agents = append(out.Agents, ug)
|
|
}
|
|
providers := map[string]provider.Provider{}
|
|
for _, p := range provider.All() {
|
|
providers[p.ID] = p
|
|
}
|
|
for _, g := range s.Models {
|
|
ug := usageGroup{Group: g, Name: g.Model, Sub: g.Provider, Icon: "generic"}
|
|
if p, ok := providers[g.Provider]; ok {
|
|
ug.Sub = p.Name
|
|
if p.Icon != "" {
|
|
ug.Icon = p.Icon
|
|
}
|
|
}
|
|
if g.Host != "" {
|
|
ug.Sub += " · " + g.Host
|
|
}
|
|
out.Models = append(out.Models, ug)
|
|
}
|
|
// each subscription account's share, by the account that answered
|
|
// (#557); Name "" is the calls whose record names none, the page
|
|
// saying "account not recorded"
|
|
for _, g := range s.Accounts {
|
|
ug := usageGroup{Group: g, Name: g.Account, Sub: g.Provider, Icon: "generic"}
|
|
if p, ok := providers[g.Provider]; ok {
|
|
ug.Sub = p.Name
|
|
if p.Icon != "" {
|
|
ug.Icon = p.Icon
|
|
}
|
|
}
|
|
out.Accounts = append(out.Accounts, ug)
|
|
}
|
|
out.CallerKeys = callerUsageGroups(s)
|
|
return out
|
|
}
|
|
|
|
func callerUsageGroups(s usage.Summary) []usageGroup {
|
|
keys := []usageGroup{}
|
|
current, _ := access.List()
|
|
names := map[string]string{}
|
|
for _, k := range current {
|
|
names[k.ID] = k.Name
|
|
}
|
|
for _, g := range s.CallerKeys {
|
|
n := names[g.CallerKeyID]
|
|
if n == "" {
|
|
n = g.CallerKeyName
|
|
}
|
|
if n == "" {
|
|
n = g.CallerKeyID
|
|
}
|
|
keys = append(keys, usageGroup{Group: g, Name: n, Icon: "generic"})
|
|
}
|
|
return keys
|
|
}
|
|
|
|
func periodOf(s string) usage.Period {
|
|
switch p := usage.Period(s); p {
|
|
case usage.Today, usage.Week, usage.Month, usage.All:
|
|
return p
|
|
}
|
|
return usage.Month
|
|
}
|
|
|
|
// csvStamp names the selected day, or, when no day is selected, the period
|
|
// and the day of now, the moment its rows were read at.
|
|
func csvStamp(p usage.Period, day string, now time.Time) string {
|
|
if _, err := time.Parse(time.DateOnly, day); err == nil {
|
|
return "magpie-requests-day-" + day
|
|
}
|
|
return "magpie-requests-" + string(p) + "-" + now.Format(time.DateOnly)
|
|
}
|
|
|
|
func ledgerFilter(q url.Values) usage.Filter {
|
|
id, _ := strconv.ParseInt(q.Get("route"), 10, 64)
|
|
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
|
|
}
|
|
|
|
// viaOf is the source a request's ?via= names, "" for both.
|
|
func viaOf(s string) string {
|
|
switch s {
|
|
case usage.SourceGateway, usage.SourceSession:
|
|
return s
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// ledgerRow is a usage.Row with the names the page shows it by.
|
|
type ledgerRow struct {
|
|
usage.Row
|
|
CallerKeyLabel string `json:"callerKeyLabel,omitempty"`
|
|
AgentName string `json:"agentName"`
|
|
Icon string `json:"icon"` // the agent's
|
|
ProviderName string `json:"providerName"`
|
|
Access string `json:"access,omitempty"` // known account/route type, independent of model maker
|
|
PricingModel string `json:"pricing_model,omitempty"`
|
|
// ComputerName is the other computer a call was made on, shared through sync (#542)
|
|
ComputerName string `json:"computerName,omitempty"`
|
|
}
|
|
|
|
type ledgerJSON struct {
|
|
CallerKeys []usageGroup `json:"callerKeys"`
|
|
Period usage.Period `json:"period"`
|
|
Rows []ledgerRow `json:"rows"`
|
|
Offset int `json:"offset"`
|
|
Total int `json:"total"` // the rows the filter keeps, on every page
|
|
// Series: the period by hour, day or week (Bucket), before the day filter
|
|
Bucket string `json:"bucket"`
|
|
Series []usage.SeriesPoint `json:"series"`
|
|
// By: the rows told apart by provider, agent, model and model at each
|
|
// provider ("modelAt", named "model · provider"), the most tokens
|
|
// first. The one by a dimension the filter has picked is of the rows
|
|
// without that pick, so the others are still there to switch to.
|
|
By map[string][]ledgerShare `json:"by"`
|
|
ChartBy map[string][]ledgerShare `json:"chartBy,omitempty"`
|
|
Day string `json:"day,omitempty"`
|
|
usage.Totals
|
|
// Through and Direct: the rows the gateway served, and the rows read
|
|
// from the agents' own session files, which it never saw. Totals is
|
|
// the two together, so the page can show all three (#the usage report).
|
|
Through usage.Totals `json:"through"`
|
|
Direct usage.Totals `json:"direct"`
|
|
// Agents, Providers and Purposes: those with calls in the period, for the filters
|
|
Agents []ledgerAgent `json:"agents"`
|
|
Providers []ledgerAgent `json:"providers"`
|
|
Purposes []string `json:"purposes"`
|
|
// Accounts: the subscription accounts that answered calls in the
|
|
// period, for the Account filter (#557)
|
|
Accounts []ledgerAccount `json:"accounts"`
|
|
// Computers: this one ("this", no name) and the others whose usage
|
|
// sync brought (#542), for the filter; none while there are none
|
|
Computers []ledgerShare `json:"computers,omitempty"`
|
|
}
|
|
|
|
// ledgerShare is a usage.Share with the name and logo the page shows it by.
|
|
type ledgerShare struct {
|
|
usage.Share
|
|
Name string `json:"name"`
|
|
Icon string `json:"icon,omitempty"`
|
|
}
|
|
|
|
// ledgerAccount is a subscription account the Account filter offers: its
|
|
// name, and the providers it answered for, by name.
|
|
type ledgerAccount struct {
|
|
ID string `json:"id"`
|
|
Providers []string `json:"providers"`
|
|
}
|
|
|
|
type ledgerAgent struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Icon string `json:"icon"`
|
|
}
|
|
|
|
// ledgerPage is one page of the ledger: limit rows (100 when none is
|
|
// given, 500 at most) from offset.
|
|
func ledgerPage(p usage.Period, f usage.Filter, offset, limit int) ledgerJSON {
|
|
l := usage.QueryPage(p, f, offset, limit)
|
|
offset = max(0, min(offset, l.Total))
|
|
page := l.Rows
|
|
agents := map[string]*agent.Agent{}
|
|
for _, a := range agent.Clients() {
|
|
agents[a.ID] = a
|
|
}
|
|
// A session file without route evidence is a local source, not a supplier.
|
|
names := map[string]string{usage.UnknownProvider: "Local session"}
|
|
icons := map[string]string{}
|
|
access := map[string]string{}
|
|
for _, pr := range provider.All() {
|
|
names[pr.ID], icons[pr.ID] = pr.Name, pr.Icon
|
|
if pr.Account != nil {
|
|
access[pr.ID] = "subscription"
|
|
} else if pr.Key != "" {
|
|
access[pr.ID] = "api"
|
|
}
|
|
}
|
|
who := func(id string) ledgerAgent {
|
|
if a := agents[id]; a != nil {
|
|
return ledgerAgent{ID: id, Name: a.Name, Icon: a.Icon}
|
|
}
|
|
return ledgerAgent{ID: id, Name: id, Icon: "generic"}
|
|
}
|
|
which := func(id string) ledgerAgent {
|
|
a := ledgerAgent{ID: id, Name: names[id], Icon: icons[id]}
|
|
if a.Name == "" {
|
|
a.Name = id
|
|
}
|
|
if a.Icon == "" {
|
|
a.Icon = "generic"
|
|
}
|
|
return a
|
|
}
|
|
out := ledgerJSON{Period: p, Rows: make([]ledgerRow, 0, len(page)), Offset: offset, Total: l.Total, Totals: l.Sum, Agents: []ledgerAgent{}, Providers: []ledgerAgent{}, Accounts: []ledgerAccount{}}
|
|
out.Through, out.Direct = l.Through, l.Direct
|
|
out.Bucket, out.Series = l.Bucket, l.Series
|
|
out.Purposes = l.Purposes
|
|
out.Day = f.Day
|
|
out.CallerKeys = callerUsageGroups(usage.Summary{CallerKeys: l.CallerKeys})
|
|
callerLabels := map[string]string{}
|
|
for _, g := range out.CallerKeys {
|
|
callerLabels[g.CallerKeyID] = g.Name
|
|
}
|
|
for _, r := range page {
|
|
a := who(r.Agent)
|
|
lr := ledgerRow{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: names[r.Provider]}
|
|
if r.Source != "log" {
|
|
lr.Access = access[r.Provider]
|
|
}
|
|
if r.Priced {
|
|
if model := provider.PricedName(r.Model); model != r.Model {
|
|
lr.PricingModel = model
|
|
}
|
|
}
|
|
if lr.ProviderName == "" {
|
|
lr.ProviderName = r.Provider
|
|
}
|
|
lr.CallerKeyLabel = callerLabels[r.CallerKeyID]
|
|
if r.Computer != "" {
|
|
lr.ComputerName = l.Names[r.Computer]
|
|
if lr.ComputerName == "" {
|
|
lr.ComputerName = r.Computer
|
|
}
|
|
}
|
|
out.Rows = append(out.Rows, lr)
|
|
}
|
|
for _, id := range l.Agents {
|
|
out.Agents = append(out.Agents, who(id))
|
|
}
|
|
for _, id := range l.Providers {
|
|
out.Providers = append(out.Providers, which(id))
|
|
}
|
|
// one choice per account, most used first, with the providers it
|
|
// answered for: the same email may be a Codex and a Claude account
|
|
at := map[string]int{}
|
|
for _, g := range l.Accounts {
|
|
name := which(g.Provider).Name
|
|
if i, ok := at[g.Account]; ok {
|
|
if a := &out.Accounts[i]; !slices.Contains(a.Providers, name) {
|
|
a.Providers = append(a.Providers, name)
|
|
}
|
|
continue
|
|
}
|
|
at[g.Account] = len(out.Accounts)
|
|
out.Accounts = append(out.Accounts, ledgerAccount{ID: g.Account, Providers: []string{name}})
|
|
}
|
|
// what each is of: the rows of the filter, or, for the dimension the
|
|
// filter has picked, of the rows without that pick
|
|
sharesJSON := func(by map[string][]usage.Share) map[string][]ledgerShare {
|
|
out := map[string][]ledgerShare{}
|
|
for _, d := range usage.Dimensions {
|
|
shares := []ledgerShare{}
|
|
for _, s := range by[d] {
|
|
ls := ledgerShare{Share: s, Name: s.ID}
|
|
switch d {
|
|
case "provider":
|
|
a := which(s.ID)
|
|
ls.Name, ls.Icon = a.Name, a.Icon
|
|
case "agent":
|
|
a := who(s.ID)
|
|
ls.Name, ls.Icon = a.Name, a.Icon
|
|
case "modelAt":
|
|
// the model, and the provider it went to
|
|
prov, model, _ := strings.Cut(s.ID, "/")
|
|
a := which(prov)
|
|
ls.Name, ls.Icon = model+" · "+a.Name, a.Icon
|
|
}
|
|
shares = append(shares, ls)
|
|
}
|
|
out[d] = shares
|
|
}
|
|
return out
|
|
}
|
|
out.By = sharesJSON(l.By)
|
|
if l.ChartBy != nil {
|
|
out.ChartBy = sharesJSON(l.ChartBy)
|
|
}
|
|
for _, s := range l.Computers {
|
|
ls := ledgerShare{Share: s, Name: l.Names[s.ID]}
|
|
if s.ID != usage.ThisComputer && ls.Name == "" {
|
|
ls.Name = s.ID
|
|
}
|
|
out.Computers = append(out.Computers, ls)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// contentJSON is what was said in a request, or why it can't be told.
|
|
type contentJSON struct {
|
|
Found bool `json:"found"`
|
|
// Why not: "session" (the request named none), "agent" (magpie reads the session
|
|
// files of Claude Code, Claude Desktop and Codex only), "missing" (the files have no
|
|
// such call: deleted, moved, or not written yet) or "read" (the file wouldn't read)
|
|
Why string `json:"why,omitempty"`
|
|
Model string `json:"model,omitempty"`
|
|
sessions.Content
|
|
}
|
|
|
|
// requestContent finds the call a request is in its agent's session files and reads it.
|
|
func requestContent(agent, session string, from, to, at time.Time) contentJSON {
|
|
out := contentJSON{Content: sessions.Content{Input: []sessions.Part{}, Output: []sessions.Part{}}}
|
|
switch {
|
|
case session == "":
|
|
out.Why = "session"
|
|
case agent != "claude" && agent != "claude-desktop" && agent != "codex":
|
|
out.Why = "agent"
|
|
default:
|
|
c, ok := sessions.FindCall(session, from, to, at)
|
|
if !ok {
|
|
out.Why = "missing"
|
|
break
|
|
}
|
|
content, err := sessions.ContentOf(c)
|
|
if err != nil {
|
|
out.Why = "read"
|
|
break
|
|
}
|
|
out.Found, out.Model, out.Content = true, c.Model, content
|
|
}
|
|
return out
|
|
}
|
|
|
|
func usageRoutes(mux *http.ServeMux, w Windows) {
|
|
mux.HandleFunc("GET /api/usage", func(rw http.ResponseWriter, r *http.Request) {
|
|
p := usage.Period(r.URL.Query().Get("period"))
|
|
switch p {
|
|
case usage.Today, usage.Week, usage.Month, usage.All:
|
|
default:
|
|
p = usage.Month
|
|
}
|
|
writeJSON(rw, usageState(p))
|
|
})
|
|
// the ledger: the period's calls, newest first, a page at a time
|
|
mux.HandleFunc("GET /api/usage/requests", func(rw http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
offset, _ := strconv.Atoi(q.Get("offset"))
|
|
limit, _ := strconv.Atoi(q.Get("limit"))
|
|
writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(q), offset, limit))
|
|
})
|
|
// what was said in one request, read from the agent's session file when the
|
|
// row is opened, between two times (the call's own, or a gateway request's
|
|
// span): magpie keeps no copy
|
|
mux.HandleFunc("GET /api/usage/requests/content", func(rw http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
from, err1 := time.Parse(time.RFC3339Nano, q.Get("from"))
|
|
to, err2 := time.Parse(time.RFC3339Nano, q.Get("to"))
|
|
if err1 != nil || err2 != nil {
|
|
http.Error(rw, "from and to are times", http.StatusBadRequest)
|
|
return
|
|
}
|
|
// at: when the call should have ended (a gateway request's start and
|
|
// its time); none is the window's end
|
|
at, err := time.Parse(time.RFC3339Nano, q.Get("at"))
|
|
if err != nil {
|
|
at = to
|
|
}
|
|
writeJSON(rw, requestContent(q.Get("agent"), q.Get("session"), from, to, at))
|
|
})
|
|
// the same CSV to a browser (magpie web), which saves it itself
|
|
mux.HandleFunc("GET /api/usage/requests.csv", func(rw http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
p := periodOf(q.Get("period"))
|
|
// one moment for the rows and the day in the file's name
|
|
now := usage.Clock()
|
|
rows := usage.LedgerOfAt(p, ledgerFilter(q), now).Rows
|
|
rw.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
|
rw.Header().Set("Content-Disposition", `attachment; filename="`+csvStamp(p, q.Get("day"), now)+`.csv"`)
|
|
usage.WriteCSV(rw, rows)
|
|
})
|
|
// the rows the ledger shows, all its pages, as a CSV in Downloads
|
|
mux.HandleFunc("POST /api/usage/requests/export", func(rw http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
p := periodOf(q.Get("period"))
|
|
now := usage.Clock()
|
|
rows := usage.LedgerOfAt(p, ledgerFilter(q), now).Rows
|
|
var b bytes.Buffer
|
|
if err := usage.WriteCSV(&b, rows); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
dir := downloads()
|
|
stamp := csvStamp(p, q.Get("day"), now)
|
|
name := filepath.Join(dir, stamp+".csv")
|
|
for i := 2; ; i++ { // never over an earlier one
|
|
if _, err := os.Stat(name); err != nil {
|
|
break
|
|
}
|
|
name = filepath.Join(dir, fmt.Sprintf("%s-%d.csv", stamp, i))
|
|
}
|
|
if err := edit.WriteAtomic(name, b.Bytes()); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
_ = w.OpenFolder(dir) // saved either way; the path is in the answer
|
|
writeJSON(rw, map[string]any{"path": tilde(name), "rows": len(rows)})
|
|
})
|
|
// The subscriptions' quotas, the plans' bought with a key, and the
|
|
// keys' balances come from the
|
|
// vendors, which can be slow or unreachable, so the page asks for them
|
|
// apart from the local log.
|
|
// ?asked=1 is the user opening or refreshing the page: Claude Code's
|
|
// own /usage is run at once (provider.AskClaudeUsage).
|
|
mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Query().Get("asked") != "" {
|
|
provider.AskClaudeUsage()
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
|
defer cancel()
|
|
// a WorkBuddy (China) account's card says how its daily check-in
|
|
// went (#694)
|
|
qs := provider.WithCheckins(provider.Quotas(ctx))
|
|
// an account's card may be the stale copy a read under way will
|
|
// replace: the page asks again until it has landed (#959)
|
|
if provider.SubscriptionUsageReading() {
|
|
rw.Header().Set("X-Magpie-Reading", "1")
|
|
}
|
|
writeJSON(rw, qs)
|
|
})
|
|
// One card read again, from its refresh button (#840): ?provider= and,
|
|
// of a card with several accounts, &user=; the others are left as they
|
|
// were read. The answer is every card, as GET's.
|
|
mux.HandleFunc("POST /api/usage/quotas/refresh", func(rw http.ResponseWriter, r *http.Request) {
|
|
id := r.URL.Query().Get("provider")
|
|
if id == "" {
|
|
http.Error(rw, "provider is required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
|
defer cancel()
|
|
provider.RefreshUsage(ctx, id, r.URL.Query().Get("user"))
|
|
writeJSON(rw, provider.WithCheckins(provider.Quotas(ctx)))
|
|
})
|
|
// WorkBuddy's daily check-in pressed now, from the Usage card, for
|
|
// each account not in yet today, as `magpie accounts checkin` does; the
|
|
// card is read again after
|
|
mux.HandleFunc("POST /api/usage/workbuddy-checkin", func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
rs := provider.CheckInWorkBuddy(ctx)
|
|
if rs == nil {
|
|
rs = []provider.WorkBuddyCheckin{}
|
|
}
|
|
writeJSON(rw, rs)
|
|
})
|
|
// and Trae CN's, for each Trae CN account (#694)
|
|
mux.HandleFunc("POST /api/usage/trae-checkin", func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
rs := provider.CheckInTrae(ctx)
|
|
if rs == nil {
|
|
rs = []provider.WorkBuddyCheckin{}
|
|
}
|
|
writeJSON(rw, rs)
|
|
})
|
|
// and MiniMax Code's, for each MiniMax Code (China) account (#811)
|
|
mux.HandleFunc("POST /api/usage/minimax-checkin", func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
rs := provider.CheckInMiniMax(ctx)
|
|
if rs == nil {
|
|
rs = []provider.WorkBuddyCheckin{}
|
|
}
|
|
writeJSON(rw, rs)
|
|
})
|
|
// and Qoder's daily credits, for each Qoder and Qoder CN account
|
|
mux.HandleFunc("POST /api/usage/qoder-checkin", func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
rs := provider.CheckInQoder(ctx)
|
|
if rs == nil {
|
|
rs = []provider.WorkBuddyCheckin{}
|
|
}
|
|
writeJSON(rw, rs)
|
|
})
|
|
// and a plugin's own, for each account of the provider it names
|
|
mux.HandleFunc("POST /api/usage/plugin-checkin", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Provider string }
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Provider == "" {
|
|
fail(rw, errors.New("no provider"))
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
rs := provider.CheckInPlugins(ctx, in.Provider)
|
|
if rs == nil {
|
|
rs = []provider.WorkBuddyCheckin{}
|
|
}
|
|
writeJSON(rw, rs)
|
|
})
|
|
// what was left of each window over time, for the quota cards' curves
|
|
// (#651); ?days= back
|
|
mux.HandleFunc("GET /api/usage/quotas/history", func(rw http.ResponseWriter, r *http.Request) {
|
|
days := r.URL.Query().Get("days")
|
|
hs := provider.QuotaHistories(provider.QuotaHistorySince(days, time.Now()), "", "")
|
|
// and a remote magpie's, for its cards (office/codex)
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
writeJSON(rw, append(hs, provider.RemoteQuotaHistories(ctx, days)...))
|
|
})
|
|
// spends one of a Codex account's rate-limit resets, which the page
|
|
// has asked the user about first; what it did comes back
|
|
mux.HandleFunc("POST /api/usage/codex-reset", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct{ User string }
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
|
defer cancel()
|
|
out, err := provider.UseCodexReset(ctx, in.User)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, out)
|
|
})
|
|
}
|