Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)

yetoneea9454d2d84b
diff --git a/docs/reference.md b/docs/reference.md
index a519ef9e8..5a8bd2cb4 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -1162,6 +1162,37 @@ provider and model. Records now identify upstream API keys, but a provider
charging different tariffs per key still cannot be costed exactly from a
single provider-wide price.
+### Counting two ids as one model
+
+A vendor can name one model two ways, as `deepseek-v4.1-flash` and
+`deepseek-flash`, and Usage, Sessions and `magpie usage` then show it as two
+rows. Say they are one, and every place that counts usage by model counts
+them under the name you gave:
+
+```sh
+magpie model alias deepseek-v4.1-flash deepseek-flash # count it as deepseek-flash
+magpie model alias deepseek-v4.1-flash # what it is counted as
+magpie model alias deepseek-v4.1-flash --reset # under its own id again
+magpie model aliases # every alias you set
+```
+
+It is kept in settings.json as `"usageAliases": {"deepseek-v4.1-flash":
+"deepseek-flash"}`, and nothing changes until you write one. Both sides are
+model ids with no provider, matched the way routing groups match them: a
+vendor's `prefix/`, case, `_` against `-` and a snapshot date make no
+difference, and the alias holds at every provider. An alias of an alias is
+followed to its end; one that maps a model to itself or loops back to it is
+refused.
+
+An alias is how usage is **shown**, nothing more. Requests still ask for the
+id the agent picked, the model lists written into agents and the gateway's
+`/v1/models` are unchanged, and routing groups and Same as are separate.
+Each call is still **priced by the id it was made under** and only then
+counted under the alias: the alias's own price is never put on the other
+id's calls, and a merged row is priced only when every id in it is. The
+Usage page's Requests list and its model filter still show each request's
+own id.
+
### What a model takes
A provider that serves a model models.dev does not list, or lists at the
diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md
index 21f2b28f1..e510bc74f 100644
--- a/docs/subsystems/gateway-sessions.md
+++ b/docs/subsystems/gateway-sessions.md
@@ -59,6 +59,18 @@ subagent whose session file is in a temp folder). Verification:
models, token totals, start/last timestamps and effective prices come from the
same usage records used by Usage and stats endpoints.
+A model the user counts under another id (`usageAliases` in settings.json,
+`magpie model alias`; [`provider.UsageAlias`](../../internal/provider/usagealias.go))
+is merged after pricing, never before: `buildGatewaySessions` prices each
+record by its own model and keys its day and model rows by the alias, and
+`sessions.List`, `Get`, `Find` and the stats (`aliasStats` in
+[`alias.go`](../../internal/sessions/alias.go)) merge a native session's rows
+the same way, into new slices so the memo is never changed. The alias is read
+before any lock, and an unreadable settings.json keeps the last aliases read.
+Requests, the Requests ledger and model lists keep each call's own id.
+Verification: `TestUsageAliasCountsTwoIdsAsOne`,
+`TestSessionsCountAliasedModelsAsOne`, `TestAliasStatsLeavesItsInputAlone`.
+
Claude Desktop gateway rows can have a local name even without a CLI
transcript (#1675). [`DesktopTitles`](../../internal/sessions/desktop_titles.go)
reads `claude-code-sessions/*/*/local_*.json` and
diff --git a/internal/cli/model_alias_cli_test.go b/internal/cli/model_alias_cli_test.go
new file mode 100644
index 000000000..00b623d73
--- /dev/null
+++ b/internal/cli/model_alias_cli_test.go
@@ -0,0 +1,55 @@
+package cli
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// magpie model alias counts a model's usage under another id, shows it,
+// lists it under aliases and takes it off with --reset; it refuses a
+// model aliased to itself, a loop, and a flag taken as a model id.
+func TestModelAliasCmd(t *testing.T) {
+ groupsHome(t)
+ out, err := runOut(t, "model", "aliases")
+ if err != nil || !strings.Contains(out, "no model is counted under another id yet") {
+ t.Fatalf("empty list: %q %v", out, err)
+ }
+ if out, err = runOut(t, "model", "alias", "deepseek-v4.1-flash", "deepseek-flash"); err != nil || !strings.Contains(out, "counted as deepseek-flash") {
+ t.Fatalf("set: %q %v", out, err)
+ }
+ if got := settings.Load().UsageAliases; got["deepseek-v4.1-flash"] != "deepseek-flash" {
+ t.Fatalf("settings: %v", got)
+ }
+ if out, err = runOut(t, "model", "alias", "deepseek/deepseek-v4.1-flash"); err != nil || !strings.Contains(out, "deepseek-v4.1-flash") || !strings.Contains(out, "counted as deepseek-flash") {
+ t.Fatalf("show: %q %v", out, err)
+ }
+ if out, err = runOut(t, "model", "aliases"); err != nil || !strings.Contains(out, "deepseek-v4.1-flash → deepseek-flash") {
+ t.Fatalf("list: %q %v", out, err)
+ }
+ for _, bad := range [][]string{
+ {"model", "alias", "deepseek-flash", "DeepSeek_Flash"},
+ {"model", "alias", "deepseek-flash", "deepseek-v4.1-flash"},
+ {"model", "alias", "deepseek-flash", "--force"},
+ } {
+ if _, err := runOut(t, bad...); err == nil {
+ t.Fatalf("took %v", bad)
+ }
+ }
+ if out, err = runOut(t, "model", "alias", "--help"); err != nil || !strings.Contains(out, "magpie model alias <model> <name>") {
+ t.Fatalf("--help: %q %v", out, err)
+ }
+ if got := settings.Load().UsageAliases; len(got) != 1 {
+ t.Fatalf("a refused alias was written: %v", got)
+ }
+ if out, err = runOut(t, "model", "alias", "deepseek-v4.1-flash", "--reset"); err != nil || !strings.Contains(out, "its own id again") {
+ t.Fatalf("reset: %q %v", out, err)
+ }
+ if got := settings.Load().UsageAliases; got != nil {
+ t.Fatalf("after reset: %v", got)
+ }
+ if out, err = runOut(t, "model", "alias", "deepseek-v4.1-flash"); err != nil || !strings.Contains(out, "counted under its own id") {
+ t.Fatalf("show after reset: %q %v", out, err)
+ }
+}
diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go
index 89adcc85a..aaee5f08a 100644
--- a/internal/cli/model_cli.go
+++ b/internal/cli/model_cli.go
@@ -54,6 +54,16 @@ const modelUsage = `usage:
and says when there was no name of its own to take away
magpie model wires the names your vendors are asked for models by
magpie model names the models you named or narrowed
+ magpie model alias <model> <name> count the model's usage under another model id in Usage,
+ Sessions and the usage summaries, e.g. deepseek-v4.1-flash
+ deepseek-flash: two ids of one model are one row. Each call is
+ still priced by the id it was made under. Requests, routing and
+ the agents' model lists never change. Ids match as the routing
+ groups match them: a vendor/ prefix, case, "_" or a snapshot
+ date make no difference
+ magpie model alias <model> the name the model's usage is counted under
+ magpie model alias <model> --reset count its usage under its own id again
+ magpie model aliases the models whose usage you count under another id
magpie model disable <model> [<model>...] turn models off for every request through magpie: each an id
(provider/model or a bare model id) or a glob, * any run of
characters and ? one, as '*fable*'. A disabled model leaves
@@ -117,6 +127,10 @@ func modelCmd(args []string) error {
return modelOutput(args[1:])
case "wire", "upstream":
return modelWire(args[1:])
+ case "alias":
+ return modelUsageAlias(args[1:])
+ case "aliases":
+ return modelUsageAliases()
case "disable":
return modelDisable(args[1:])
case "enable":
@@ -775,6 +789,83 @@ func modelWires() error {
return nil
}
+// modelUsageAlias shows or sets the name a model's usage is counted under
+// (provider.SetUsageAlias).
+func modelUsageAlias(args []string) error {
+ if len(args) == 0 || len(args) > 2 {
+ return fmt.Errorf("%s", modelUsage)
+ }
+ if slices.Contains([]string{"-h", "--help", "help"}, args[0]) {
+ fmt.Println(modelUsage)
+ return nil
+ }
+ from := args[0]
+ if len(args) == 1 {
+ f, to, counted, ok, err := provider.UsageAliasFor(from)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ fmt.Println(bold.Render(from), muted.Render("· counted under its own id"))
+ return nil
+ }
+ line := muted.Render("· counted as ") + to
+ if counted != to {
+ line += muted.Render(" → " + counted)
+ }
+ fmt.Println(bold.Render(f), line)
+ return nil
+ }
+ if isReset(args[1:]) {
+ changed, err := provider.SetUsageAlias(from, "")
+ if err != nil {
+ return err
+ }
+ if !changed {
+ fmt.Println(muted.Render(from + " was counted under its own id already"))
+ return nil
+ }
+ fmt.Println(bold.Render(from), muted.Render("· counted under its own id again"))
+ return nil
+ }
+ to := args[1]
+ changed, err := provider.SetUsageAlias(from, to)
+ if err != nil {
+ return err
+ }
+ if !changed {
+ fmt.Println(muted.Render(from + " was counted as " + to + " already"))
+ return nil
+ }
+ fmt.Println(bold.Render(from), muted.Render("· counted as ")+to, muted.Render("in Usage and Sessions; requests still ask for "+from))
+ return nil
+}
+
+// modelUsageAliases lists the models whose usage is counted under another id.
+func modelUsageAliases() error {
+ s, err := settings.LoadChecked()
+ if err != nil {
+ return err
+ }
+ m := s.UsageAliases
+ rows := make([][2]string, 0, len(m))
+ w := 0
+ for _, k := range slices.Sorted(maps.Keys(m)) {
+ if n := strings.TrimSpace(m[k]); n != "" {
+ rows = append(rows, [2]string{k, n})
+ w = max(w, len(k))
+ }
+ }
+ if len(rows) == 0 {
+ fmt.Println(muted.Render("no model is counted under another id yet · magpie model alias <model> <name>"))
+ return nil
+ }
+ for _, r := range rows {
+ fmt.Println(" " + pad(r[0], w) + " → " + r[1])
+ }
+ return nil
+}
+
func modelContext(args []string) error {
if len(args) == 0 {
return fmt.Errorf("%s", modelUsage)
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 92fe2b6ed..7c0f85682 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -1247,6 +1247,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.PanelUsageHidden = cur.PanelUsageHidden
// and the clients the Usage page's Agents list leaves out, set there
in.UsageAgentsHidden = cur.UsageAgentsHidden
+ // and the names models' usage is counted under (magpie model alias)
+ in.UsageAliases = cur.UsageAliases
// and the clients it counts as agents, set there too (#1958)
in.ClientAgents = cur.ClientAgents
// how agents' lists name models, set on its own for the agents to be told
diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go
index 35cf41e83..85d912e06 100644
--- a/internal/gui/settings_keep_test.go
+++ b/internal/gui/settings_keep_test.go
@@ -133,6 +133,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
ModelWires: map[string]string{"p/m": "vendor-c/m"},
ModelAPIs: map[string]string{"p/m": "anthropic"},
ModelSameAs: map[string]string{"p/m": "deepseek-v4.1-flash"},
+ UsageAliases: map[string]string{"deepseek-v4.1-flash": "deepseek-flash"},
ModelKinds: map[string]string{"p/m": "video"},
RedactRules: []redact.Rule{{Kind: "prefix", Prefix: "oc_sk_"}},
RedactActions: map[string]string{"API_KEY": "block", "EMAIL": "warn"},
diff --git a/internal/provider/usagealias.go b/internal/provider/usagealias.go
new file mode 100644
index 000000000..fb9884a60
--- /dev/null
+++ b/internal/provider/usagealias.go
@@ -0,0 +1,218 @@
+package provider
+
+import (
+ "errors"
+ "fmt"
+ "maps"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// A model alias is a name the user counts a model's usage under, so that
+// what one model spent under two ids is one row in Usage and Sessions
+// (SlouchyQuill507 on Discord: deepseek-v4.1-flash and deepseek-flash).
+// It is a way of showing usage and nothing else: a request, the model
+// lists written into agents, routing and prices never read it. A call is
+// still priced by the id it was made under, and only then counted under
+// the alias.
+
+// SetUsageAlias counts usage of the model from under the name to, or, with
+// to "", under its own id again. Both are model ids as any vendor spells
+// them, matched as the groups magpie finds match them (sameModel: a
+// vendor's prefix, case, "_" or a snapshot date make no difference). It
+// refuses an alias of a model to itself and one that would loop back to
+// from through the others. changed is false when there was nothing to
+// change.
+func SetUsageAlias(from, to string) (changed bool, err error) {
+ from, to = strings.TrimSpace(from), strings.TrimSpace(to)
+ if err := checkAliasName(from); err != nil {
+ return false, err
+ }
+ if to != "" {
+ if err := checkAliasName(to); err != nil {
+ return false, err
+ }
+ if sameModel(from) == sameModel(to) {
+ return false, fmt.Errorf("%s is %s already: an alias names another model id", from, to)
+ }
+ }
+ err = settings.EditUsageAliases(func(m map[string]string) (map[string]string, error) {
+ before := maps.Clone(m)
+ // one entry per model however it was spelt: the new one takes the
+ // place of an older spelling
+ for k := range m {
+ if sameModel(k) == sameModel(from) {
+ delete(m, k)
+ }
+ }
+ if to != "" {
+ if m == nil {
+ m = map[string]string{}
+ }
+ m[from] = to
+ if loop := aliasLoop(m, from); loop != nil {
+ return nil, fmt.Errorf("%s would come back to itself: %s", from, strings.Join(loop, " → "))
+ }
+ }
+ changed = !maps.Equal(before, m)
+ return m, nil
+ })
+ if err != nil {
+ return false, err
+ }
+ return changed, nil
+}
+
+// checkAliasName is whether s can be a side of an alias: a model's id.
+func checkAliasName(s string) error {
+ if s == "" {
+ return errors.New("name a model id, as deepseek-v4.1-flash")
+ }
+ if strings.HasPrefix(s, "-") {
+ return fmt.Errorf("%q is a flag, not a model id", s)
+ }
+ if len([]rune(s)) > 80 {
+ return errors.New("a model id is at most 80 characters")
+ }
+ if Slug(sameModel(s)) == "" {
+ return fmt.Errorf("%q names no model: give a model's id, as deepseek-v4.1-flash", s)
+ }
+ return nil
+}
+
+// aliasLoop is the ids from comes back to itself through when m is
+// followed from it, from first and last; nil when it doesn't.
+func aliasLoop(m map[string]string, from string) []string {
+ by := aliasIndex(m)
+ path := []string{from}
+ seen := map[string]bool{sameModel(from): true}
+ k := sameModel(from)
+ for {
+ e, ok := by[k]
+ if !ok {
+ return nil
+ }
+ path = append(path, e.to)
+ k = sameModel(e.to)
+ if seen[k] {
+ if k == sameModel(from) {
+ return path
+ }
+ return nil // a loop further on, not through from
+ }
+ seen[k] = true
+ }
+}
+
+type aliasEntry struct{ from, to string }
+
+// aliasIndex is m by sameModel of its keys; of two keys spelt as one, the
+// first in order wins, so a hand-written file reads the same each time.
+func aliasIndex(m map[string]string) map[string]aliasEntry {
+ by := make(map[string]aliasEntry, len(m))
+ for _, k := range slices.Sorted(maps.Keys(m)) {
+ to := strings.TrimSpace(m[k])
+ sk := sameModel(k)
+ if to == "" || sk == "" || sameModel(to) == sk {
+ continue
+ }
+ if _, ok := by[sk]; !ok {
+ by[sk] = aliasEntry{strings.TrimSpace(k), to}
+ }
+ }
+ return by
+}
+
+// UsageAliasFor is the alias the user set for the model id, as
+// settings.json has it (from as written there), and where usage of it is
+// counted in the end, through any alias of that. ok is false when it has
+// none. err is settings.json not read: unknown, not "none".
+func UsageAliasFor(id string) (from, to, counted string, ok bool, err error) {
+ s, err := settings.LoadChecked()
+ if err != nil {
+ return "", "", "", false, err
+ }
+ e, ok := aliasIndex(s.UsageAliases)[sameModel(strings.TrimSpace(id))]
+ if !ok {
+ return "", "", "", false, nil
+ }
+ return e.from, e.to, usageAliasOf(s.UsageAliases)(e.from), true, nil
+}
+
+// UsageAliases are the aliases the user set, as settings.json has them.
+func UsageAliases() map[string]string { return maps.Clone(usageAliasesNow()) }
+
+// lastAliases is the last UsageAliases read, for when settings.json can't
+// be read: a failed read is not "no aliases", and usage would otherwise be
+// shown split until the file reads again.
+var lastAliases atomic.Pointer[map[string]string]
+
+func usageAliasesNow() map[string]string {
+ s, err := settings.LoadChecked()
+ if err != nil {
+ if p := lastAliases.Load(); p != nil {
+ return *p
+ }
+ return nil
+ }
+ m := s.UsageAliases
+ lastAliases.Store(&m)
+ return m
+}
+
+// UsageAlias is the name a model's usage is counted under: the alias the
+// user set for it, followed through any alias of that, else the model's
+// own id. It is nil when there are no aliases, so a caller does nothing
+// for each row. Read once for a whole summary, not for each row; it reads
+// settings.json, so it is taken before any lock a reader of the usage
+// waits on.
+func UsageAlias() func(string) string { return usageAliasOf(usageAliasesNow()) }
+
+// UsageAliasIn is UsageAlias for the aliases m.
+func UsageAliasIn(m map[string]string) func(string) string { return usageAliasOf(m) }
+
+func usageAliasOf(m map[string]string) func(string) string {
+ by := aliasIndex(m)
+ if len(by) == 0 {
+ return nil
+ }
+ // each alias followed to its end once; a loop written into the file by
+ // hand counts under each model's own id ("")
+ resolved := make(map[string]string, len(by))
+ for k, e := range by {
+ seen := map[string]bool{k: true}
+ name := e.to
+ for {
+ nk := sameModel(name)
+ if seen[nk] {
+ name = ""
+ break
+ }
+ seen[nk] = true
+ next, ok := by[nk]
+ if !ok {
+ break
+ }
+ name = next.to
+ }
+ resolved[k] = name
+ }
+ // a summary asks for the same few ids over every row: sameModel is
+ // worked out once for each
+ var memo sync.Map
+ return func(model string) string {
+ if v, ok := memo.Load(model); ok {
+ return v.(string)
+ }
+ out := model
+ if name := resolved[sameModel(model)]; name != "" {
+ out = name
+ }
+ memo.Store(model, out)
+ return out
+ }
+}
diff --git a/internal/provider/usagealias_test.go b/internal/provider/usagealias_test.go
new file mode 100644
index 000000000..0a3938f07
--- /dev/null
+++ b/internal/provider/usagealias_test.go
@@ -0,0 +1,139 @@
+package provider
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+func aliasHome(t *testing.T) {
+ t.Helper()
+ h := t.TempDir()
+ t.Setenv("HOME", h)
+ t.Setenv("USERPROFILE", h)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
+ lastAliases.Store(nil)
+ t.Cleanup(func() { lastAliases.Store(nil) })
+}
+
+// magpie model alias: off by default, a model counted under another id,
+// matched however the id is spelt, and --reset gives it its own id back.
+func TestUsageAliasSetAndReset(t *testing.T) {
+ aliasHome(t)
+ if UsageAlias() != nil {
+ t.Fatal("an alias with none set")
+ }
+ changed, err := SetUsageAlias("deepseek-v4.1-flash", "deepseek-flash")
+ if err != nil || !changed {
+ t.Fatal(changed, err)
+ }
+ if got := settings.Load().UsageAliases; len(got) != 1 || got["deepseek-v4.1-flash"] != "deepseek-flash" {
+ t.Fatalf("settings: %v", got)
+ }
+ a := UsageAlias()
+ for _, id := range []string{"deepseek-v4.1-flash", "deepseek/deepseek-v4.1-flash", "DeepSeek-V4.1-Flash", "deepseek-v4-1-flash"} {
+ if got := a(id); got != "deepseek-flash" {
+ t.Fatalf("%s counted as %q", id, got)
+ }
+ }
+ if got := a("deepseek-pro"); got != "deepseek-pro" {
+ t.Fatalf("another model counted as %q", got)
+ }
+ if changed, err := SetUsageAlias("deepseek-v4.1-flash", "deepseek-flash"); err != nil || changed {
+ t.Fatal("set again", changed, err)
+ }
+ // another spelling of the same model takes its place, not a second entry
+ if _, err := SetUsageAlias("DeepSeek-V4.1-Flash", "ds-flash"); err != nil {
+ t.Fatal(err)
+ }
+ if got := settings.Load().UsageAliases; len(got) != 1 || got["DeepSeek-V4.1-Flash"] != "ds-flash" {
+ t.Fatalf("respelt: %v", got)
+ }
+ if from, to, counted, ok, err := UsageAliasFor("deepseek-v4.1-flash"); err != nil || !ok || from != "DeepSeek-V4.1-Flash" || to != "ds-flash" || counted != "ds-flash" {
+ t.Fatal(from, to, counted, ok, err)
+ }
+ if changed, err := SetUsageAlias("deepseek-v4.1-flash", ""); err != nil || !changed {
+ t.Fatal("reset", changed, err)
+ }
+ if got := settings.Load().UsageAliases; got != nil {
+ t.Fatalf("after reset: %v", got)
+ }
+ if UsageAlias() != nil {
+ t.Fatal("an alias after reset")
+ }
+ if changed, err := SetUsageAlias("deepseek-v4.1-flash", ""); err != nil || changed {
+ t.Fatal("reset again", changed, err)
+ }
+}
+
+// A model aliased to itself, or one that would loop back through the
+// others, is refused and nothing is written; a chain is followed to its end.
+func TestUsageAliasRefusesSelfAndLoops(t *testing.T) {
+ aliasHome(t)
+ for _, to := range []string{"deepseek-flash", "DeepSeek_Flash", "deepseek/deepseek-flash"} {
+ if _, err := SetUsageAlias("deepseek-flash", to); err == nil {
+ t.Fatalf("took deepseek-flash → %s", to)
+ }
+ }
+ for _, bad := range [][2]string{{"", "x"}, {"--help", "x"}, {"m", "--reset-ish"}, {"///", "x"}} {
+ if _, err := SetUsageAlias(bad[0], bad[1]); err == nil {
+ t.Fatalf("took %q → %q", bad[0], bad[1])
+ }
+ }
+ if _, err := SetUsageAlias("a-model", "b-model"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetUsageAlias("b-model", "c-model"); err != nil {
+ t.Fatal(err)
+ }
+ _, err := SetUsageAlias("c-model", "a-model")
+ if err == nil || !strings.Contains(err.Error(), "c-model → a-model → b-model → c-model") {
+ t.Fatalf("loop: %v", err)
+ }
+ if got := settings.Load().UsageAliases; len(got) != 2 {
+ t.Fatalf("a refused loop was written: %v", got)
+ }
+ a := UsageAlias()
+ if a("a-model") != "c-model" || a("b-model") != "c-model" || a("c-model") != "c-model" {
+ t.Fatal(a("a-model"), a("b-model"), a("c-model"))
+ }
+}
+
+// A loop written into settings.json by hand counts each model under its
+// own id rather than spinning or picking one.
+func TestUsageAliasHandWrittenLoop(t *testing.T) {
+ a := UsageAliasIn(map[string]string{"x-model": "y-model", "y-model": "x-model", "p-model": "q-model", "self": "SELF"})
+ if a("x-model") != "x-model" || a("y-model") != "y-model" || a("p-model") != "q-model" || a("self") != "self" {
+ t.Fatal(a("x-model"), a("y-model"), a("p-model"), a("self"))
+ }
+}
+
+// A settings.json that can't be read is unknown, not "no aliases": usage
+// keeps the aliases last read, and nothing is written over the file.
+func TestUsageAliasUnreadSettings(t *testing.T) {
+ aliasHome(t)
+ if _, err := SetUsageAlias("deepseek-v4.1-flash", "deepseek-flash"); err != nil {
+ t.Fatal(err)
+ }
+ if a := UsageAlias(); a == nil || a("deepseek-v4.1-flash") != "deepseek-flash" {
+ t.Fatal("not read")
+ }
+ if err := os.WriteFile(settings.Path(), []byte("{not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if a := UsageAlias(); a == nil || a("deepseek-v4.1-flash") != "deepseek-flash" {
+ t.Fatal("an unread settings.json dropped the aliases")
+ }
+ if _, err := SetUsageAlias("m-one", "m-two"); err == nil {
+ t.Fatal("wrote over an unread settings.json")
+ }
+ if b, _ := os.ReadFile(settings.Path()); string(b) != "{not json" {
+ t.Fatalf("settings.json rewritten: %s", b)
+ }
+ if _, _, _, _, err := UsageAliasFor("deepseek-v4.1-flash"); err == nil {
+ t.Fatal("UsageAliasFor read an unread file as none")
+ }
+}
diff --git a/internal/sessions/alias.go b/internal/sessions/alias.go
new file mode 100644
index 000000000..d2aa2d0a2
--- /dev/null
+++ b/internal/sessions/alias.go
@@ -0,0 +1,142 @@
+package sessions
+
+import "sort"
+
+// A session's models are counted under the names the user gave them
+// (provider.UsageAlias, `magpie model alias`): two ids of one model are one
+// row. Each was priced by its own id before; the merged row adds those
+// costs and is priced only when every id in it was. Everything here makes
+// new slices, so what List and Stats keep for the next read is never
+// changed.
+
+// aliasModels is ms with the models alias names alike made one, the most
+// used first as assembleListed sorts them.
+func aliasModels(ms []Model, alias func(string) string) []Model {
+ out := make([]Model, 0, len(ms))
+ at := make(map[string]int, len(ms))
+ for _, m := range ms {
+ name := alias(m.Model)
+ i, ok := at[name]
+ if !ok {
+ at[name] = len(out)
+ m.Model = name
+ out = append(out, m)
+ continue
+ }
+ o := &out[i]
+ o.Tokens.add(m.Tokens)
+ o.Cost += m.Cost
+ o.Priced = o.Priced && m.Priced
+ }
+ sort.SliceStable(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ if a.Input+a.Output != b.Input+b.Output {
+ return a.Input+a.Output > b.Input+b.Output
+ }
+ return a.Model < b.Model
+ })
+ return out
+}
+
+// aliasSession counts s's models under their aliases. When rows merged,
+// Unpriced is the merged rows without a price, as it counted them before.
+func aliasSession(s *Session, alias func(string) string) {
+ if len(s.Models) == 0 {
+ return
+ }
+ n := len(s.Models)
+ s.Models = aliasModels(s.Models, alias)
+ if len(s.Models) < n {
+ s.Unpriced = 0
+ for _, m := range s.Models {
+ if !m.Priced {
+ s.Unpriced++
+ }
+ }
+ }
+ s.ModelEffort = aliasEffort(s.ModelEffort, alias)
+}
+
+// aliasStats is st with each day's usage and each session's models counted
+// under their aliases.
+func aliasStats(st Stats, alias func(string) string) Stats {
+ days := make([]Day, len(st.Days))
+ for i, d := range st.Days {
+ d.Usage = aliasUsage(d.Usage, alias)
+ days[i] = d
+ }
+ st.Days = days
+ sums := make([]Summary, len(st.Sessions))
+ for i, s := range st.Sessions {
+ s.Models = aliasNames(s.Models, alias)
+ s.ModelEffort = aliasEffort(s.ModelEffort, alias)
+ sums[i] = s
+ }
+ st.Sessions = sums
+ return st
+}
+
+// aliasUsage is a day's usage with the rows of one agent, folder and
+// aliased model made one, in the order they first came.
+func aliasUsage(us []Usage, alias func(string) string) []Usage {
+ type key struct{ agent, cwd, model string }
+ out := make([]Usage, 0, len(us))
+ at := make(map[key]int, len(us))
+ for _, u := range us {
+ u.Model = alias(u.Model)
+ k := key{u.Agent, u.Cwd, u.Model}
+ i, ok := at[k]
+ if !ok {
+ at[k] = len(out)
+ out = append(out, u)
+ continue
+ }
+ o := &out[i]
+ o.Tokens.add(u.Tokens)
+ o.Cost += u.Cost
+ o.Priced = o.Priced && u.Priced
+ }
+ return out
+}
+
+// aliasNames is names under their aliases, each once, in the order they
+// first came (the most used first stays first).
+func aliasNames(names []string, alias func(string) string) []string {
+ out := make([]string, 0, len(names))
+ seen := make(map[string]bool, len(names))
+ for _, n := range names {
+ n = alias(n)
+ if !seen[n] {
+ seen[n] = true
+ out = append(out, n)
+ }
+ }
+ return out
+}
+
+// aliasEffort is a session's model and effort rows with those of one
+// aliased model and effort made one, in the order they first came.
+func aliasEffort(es []ModelEffort, alias func(string) string) []ModelEffort {
+ if len(es) == 0 {
+ return es
+ }
+ type key struct{ model, effort string }
+ out := make([]ModelEffort, 0, len(es))
+ at := make(map[key]int, len(es))
+ for _, e := range es {
+ e.Model = alias(e.Model)
+ k := key{e.Model, e.Effort}
+ i, ok := at[k]
+ if !ok {
+ at[k] = len(out)
+ out = append(out, e)
+ continue
+ }
+ o := &out[i]
+ o.Tokens.add(e.Tokens)
+ o.Reasoning += e.Reasoning
+ o.Cost += e.Cost
+ o.Priced = o.Priced && e.Priced
+ }
+ return out
+}
diff --git a/internal/sessions/alias_test.go b/internal/sessions/alias_test.go
new file mode 100644
index 000000000..2f81af0e6
--- /dev/null
+++ b/internal/sessions/alias_test.go
@@ -0,0 +1,131 @@
+package sessions
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// aliasMsg is a line of a Claude Code reply by model.
+func aliasMsg(id, model, at string, in int) string {
+ return `{"type":"assistant","isSidechain":false,"message":{"model":"` + model + `","id":"` + id + `","role":"assistant","content":[],"usage":{"input_tokens":` + itoa(in) + `,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0}},"timestamp":"` + at + `","cwd":"/work/alias","sessionId":"44444444-2222-3333-4444-555555555555"}` + "\n"
+}
+
+// A model counted under another id (magpie model alias) is one row of a
+// session's models, of a day's usage and of a session's summary, and each
+// keeps the cost of the id it was made under (SlouchyQuill507 on Discord).
+func TestSessionsCountAliasedModelsAsOne(t *testing.T) {
+ inZone(t, 0)
+ claude, _ := setup(t)
+ dir := filepath.Join(claude, "projects", "-work-alias")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ body := aliasMsg("m1", "claude-opus-5-5", "2026-09-25T10:00:00Z", 1000000) +
+ aliasMsg("m2", "gpt-6-astra", "2026-09-25T10:01:00Z", 1000000)
+ if err := os.WriteFile(filepath.Join(dir, "44444444-2222-3333-4444-555555555555.jsonl"), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ find := func() Session {
+ t.Helper()
+ for _, s := range List(0) {
+ if s.Cwd == "/work/alias" {
+ return s
+ }
+ }
+ t.Fatal("session not listed")
+ return Session{}
+ }
+ day := func(st Stats) []Usage {
+ var out []Usage
+ for _, d := range st.Days {
+ for _, u := range d.Usage {
+ if u.Cwd == "/work/alias" {
+ out = append(out, u)
+ }
+ }
+ }
+ return out
+ }
+ // off by default: two rows
+ if s := find(); len(s.Models) != 2 {
+ t.Fatalf("with no alias: %+v", s.Models)
+ }
+ if u := day(statsAt(0, statsNow)); len(u) != 2 {
+ t.Fatalf("with no alias: %+v", u)
+ }
+
+ if _, err := provider.SetUsageAlias("gpt-6-astra", "claude-opus-5-5"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _, _ = provider.SetUsageAlias("gpt-6-astra", "") })
+ // $4 for opus's 1M in, $10 for astra's at astra's price: not $8
+ want := 4.0 + 10.0
+ s := find()
+ if len(s.Models) != 1 || s.Models[0].Model != "claude-opus-5-5" || s.Models[0].Input != 2000000 || !s.Models[0].Priced || !near(s.Models[0].Cost, want) {
+ t.Fatalf("aliased session: %+v", s.Models)
+ }
+ if !near(s.Cost, want) || s.Unpriced != 0 {
+ t.Fatalf("aliased session cost %v unpriced %d", s.Cost, s.Unpriced)
+ }
+ if g, ok := Get(s.Agent + ":" + s.ID); !ok || len(g.Models) != 1 {
+ t.Fatalf("Get: %+v", g.Models)
+ }
+ if f, ok := Find(s.Agent, s.ID); !ok || len(f.Models) != 1 {
+ t.Fatalf("Find: %+v", f.Models)
+ }
+ st := statsAt(0, statsNow)
+ u := day(st)
+ if len(u) != 1 || u[0].Model != "claude-opus-5-5" || u[0].Input != 2000000 || !u[0].Priced || !near(u[0].Cost, want) {
+ t.Fatalf("aliased day: %+v", u)
+ }
+ for _, sum := range st.Sessions {
+ if sum.Cwd == "/work/alias" && (len(sum.Models) != 1 || sum.Models[0] != "claude-opus-5-5") {
+ t.Fatalf("aliased summary models: %v", sum.Models)
+ }
+ }
+ // what List and Stats keep for the next read is not changed: with the
+ // alias gone, the next read has two rows again
+ if _, err := provider.SetUsageAlias("gpt-6-astra", ""); err != nil {
+ t.Fatal(err)
+ }
+ if s := find(); len(s.Models) != 2 {
+ t.Fatalf("after reset: %+v", s.Models)
+ }
+ if u := day(statsAt(0, statsNow)); len(u) != 2 {
+ t.Fatalf("after reset: %+v", u)
+ }
+}
+
+// Merging never writes into the slices it was given: a memo's copy stays
+// as it was.
+func TestAliasStatsLeavesItsInputAlone(t *testing.T) {
+ alias := provider.UsageAliasIn(map[string]string{"b-model": "a-model"})
+ in := Stats{
+ Days: []Day{{Date: "2026-09-25", Usage: []Usage{
+ {Agent: "x", Cwd: "/w", Model: "a-model", Tokens: Tokens{Input: 1}, Cost: 1, Priced: true},
+ {Agent: "x", Cwd: "/w", Model: "b-model", Tokens: Tokens{Input: 2}, Cost: 2, Priced: false},
+ {Agent: "x", Cwd: "/v", Model: "b-model", Tokens: Tokens{Input: 4}, Cost: 4, Priced: true},
+ }}},
+ Sessions: []Summary{{Key: "x:1", Models: []string{"b-model", "c-model", "a-model"}, ModelEffort: []ModelEffort{
+ {Model: "a-model", Effort: "high", Tokens: Tokens{Input: 1}, Reasoning: 1, Cost: 1, Priced: true},
+ {Model: "b-model", Effort: "high", Tokens: Tokens{Input: 2}, Reasoning: 2, Cost: 2, Priced: true},
+ }}},
+ }
+ out := aliasStats(in, alias)
+ u := out.Days[0].Usage
+ if len(u) != 2 || u[0].Model != "a-model" || u[0].Input != 3 || u[0].Cost != 3 || u[0].Priced || u[1].Cwd != "/v" || u[1].Model != "a-model" {
+ t.Fatalf("usage: %+v", u)
+ }
+ if m := out.Sessions[0].Models; len(m) != 2 || m[0] != "a-model" || m[1] != "c-model" {
+ t.Fatalf("models: %v", m)
+ }
+ if e := out.Sessions[0].ModelEffort; len(e) != 1 || e[0].Input != 3 || e[0].Reasoning != 3 || !e[0].Priced {
+ t.Fatalf("efforts: %+v", e)
+ }
+ if in.Days[0].Usage[1].Model != "b-model" || in.Days[0].Usage[0].Input != 1 || in.Sessions[0].Models[0] != "b-model" || in.Sessions[0].ModelEffort[0].Input != 1 {
+ t.Fatalf("input changed: %+v", in)
+ }
+}
diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go
index 1bc68841e..f7ab8f742 100644
--- a/internal/sessions/sessions.go
+++ b/internal/sessions/sessions.go
@@ -1105,6 +1105,18 @@ func Reset() {
// List reads the latest sessions of every agent, the most recently active
// first, at most limit of them (Limit when 0).
func List(limit int) []Session {
+ // read before the locks: it reads settings.json
+ alias := provider.UsageAlias()
+ out := listSessions(limit)
+ if alias != nil {
+ for i := range out {
+ aliasSession(&out[i], alias)
+ }
+ }
+ return out
+}
+
+func listSessions(limit int) []Session {
storeMu.RLock()
defer storeMu.RUnlock()
if limit <= 0 {
@@ -1962,7 +1974,16 @@ func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''
// it: the Sessions page shows it, and its conversation, Markdown and
// Terminal open from it as from any other (#2273).
func Find(agent, id string) (Session, bool) {
- for _, s := range List(0) {
+ alias := provider.UsageAlias()
+ s, ok := findListed(agent, id)
+ if ok && alias != nil {
+ aliasSession(&s, alias)
+ }
+ return s, ok
+}
+
+func findListed(agent, id string) (Session, bool) {
+ for _, s := range listSessions(0) {
if s.Agent == agent && s.ID == id {
return s, true
}
@@ -2055,7 +2076,11 @@ func Titles(keys []string) map[string]string {
// Get is the session whose files are grouped under key (a Summary's Key),
// however long ago it was at work.
func Get(key string) (Session, bool) {
+ alias := provider.UsageAlias()
s, ok, _ := get(key)
+ if ok && alias != nil {
+ aliasSession(&s, alias)
+ }
return s, ok
}
diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go
index dc5199e8c..85d6dc109 100644
--- a/internal/sessions/stats.go
+++ b/internal/sessions/stats.go
@@ -7,6 +7,8 @@ import (
"sort"
"strings"
"time"
+
+ "github.com/yetone/magpie/internal/provider"
)
// Stats is what every session spent, day by day: all of them, not only the
@@ -121,6 +123,16 @@ func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) }
// statsIn is statsAt, filling native as StatsAndNative says when not nil.
func statsIn(days int, now time.Time, native map[string]bool) Stats {
+ // read before the locks: it reads settings.json
+ alias := provider.UsageAlias()
+ st := statsRead(days, now, native)
+ if alias != nil {
+ st = aliasStats(st, alias)
+ }
+ return st
+}
+
+func statsRead(days int, now time.Time, native map[string]bool) Stats {
now = now.In(time.Local)
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
var since time.Time
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 89456f1e7..97121d20c 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -11,6 +11,7 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "maps"
"math"
"net/url"
"os"
@@ -708,6 +709,15 @@ type Settings struct {
// that model's maker's price (provider.SamePriceIn, #2344). Absent
// leaves it to its id.
ModelSameAs map[string]string `json:"modelSameAs,omitempty"`
+ // UsageAliases are the model ids the user counts as one in Usage and
+ // Sessions, from an id to the name it is counted under
+ // ("deepseek-v4.1-flash": "deepseek-flash", SlouchyQuill507 on
+ // Discord): what spent the same model under two names is one row there.
+ // Only how usage is grouped and shown changes: no request, model list
+ // or price reads it (provider.SetUsageAlias). Keyed by a bare model id,
+ // not "<provider>/<model>", so it is not named Model* and is not one
+ // of the per-model maps a provider's rename moves. Absent is none.
+ UsageAliases map[string]string `json:"usageAliases,omitempty"`
// ModelKinds is what the user said a model makes, by "<provider
// id>/<model id>": "image" or "video", for a provider set up with a
// base URL whose own model list doesn't say so (shen-joe, #1399).
@@ -1354,6 +1364,29 @@ func EditCheckinOff(edit func([]string) []string) error {
return save(s, false)
}
+// EditUsageAliases changes UsageAliases alone, as edit returns them from
+// what the file holds now, so a save elsewhere from an older snapshot isn't
+// undone. A settings file that can't be read is left as it is, with the
+// error: what it holds is unknown, not "no aliases". edit is given a copy,
+// and an error from it saves nothing.
+func EditUsageAliases(edit func(map[string]string) (map[string]string, error)) error {
+ fileMu.Lock()
+ defer fileMu.Unlock()
+ s, err := loadChecked()
+ if err != nil {
+ return err
+ }
+ m, err := edit(maps.Clone(s.UsageAliases))
+ if err != nil {
+ return err
+ }
+ if len(m) == 0 {
+ m = nil
+ }
+ s.UsageAliases = m
+ return save(s, false)
+}
+
// SetRedactModel turns the local masking model on or off, on its own, as
// Settings → Privacy does once the model is downloaded.
func SetRedactModel(on bool) error {
diff --git a/internal/usage/direct.go b/internal/usage/direct.go
index 4bc4a3275..64df79ab8 100644
--- a/internal/usage/direct.go
+++ b/internal/usage/direct.go
@@ -4,6 +4,7 @@ import (
"sort"
"time"
+ "github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
@@ -92,6 +93,7 @@ func direct(p Period, now time.Time, rows []Row) Summary {
}
m[k].addRow(r)
}
+ alias := provider.UsageAlias() // each row priced by its own id already
for _, r := range rows {
if r.Source != "log" || r.IsRejected() || r.Time.Before(s.Since) || after(until, r.Time) {
continue
@@ -99,7 +101,11 @@ func direct(p Period, now time.Time, rows []Row) Summary {
s.Totals.addRow(r)
id := ReportedAs(r.Agent)
put(agents, id, Group{ID: id}, r)
- put(models, r.Provider+"/"+r.Model, Group{ID: r.Provider + "/" + r.Model, Provider: r.Provider, Model: r.Model}, r)
+ model := r.Model
+ if alias != nil {
+ model = alias(model)
+ }
+ put(models, r.Provider+"/"+model, Group{ID: r.Provider + "/" + model, Provider: r.Provider, Model: model}, r)
if who := r.Account(); who != "" {
put(accounts, r.Provider+"@"+who, Group{ID: r.Provider + "@" + who, Provider: r.Provider, Account: who}, r)
}
diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go
index c1fe4bcf1..dbea5330e 100644
--- a/internal/usage/gateway_sessions.go
+++ b/internal/usage/gateway_sessions.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
@@ -92,7 +93,7 @@ func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySessi
}
// any other start is read from the log, and not kept
snapshot := readLogSnapshot()
- out, _ := buildGatewaySessions(snapshot, since, nativeKeys)
+ out, _ := buildGatewaySessions(snapshot, since, nativeKeys, provider.UsageAlias())
return out
}
@@ -201,12 +202,14 @@ var gatewayCache struct {
func gatewayProjection() gatewayProjectionEntry {
snapshot := readLogSnapshot()
meta := usagePriceCacheKey(time.Now())
+ // read before the lock: it reads settings.json
+ alias := provider.UsageAlias()
gatewayCache.Lock()
defer gatewayCache.Unlock()
if e := gatewayCache.entry; e != nil && e.version == snapshot.version && e.meta == meta && e.zone == time.Local {
return *e
}
- ss, _ := buildGatewaySessions(snapshot, time.Time{}, nil)
+ ss, _ := buildGatewaySessions(snapshot, time.Time{}, nil, alias)
e := gatewayProjectionEntry{version: snapshot.version, meta: meta, zone: time.Local, sessions: ss, byID: make(map[string]int, len(ss))}
for i, s := range ss {
e.byID[s.Agent+"|"+s.ID] = i
@@ -270,7 +273,10 @@ func gatewayDays(ss []GatewaySession) []GatewayDayUsage {
// gatewayBuilds counts the projections built from the log, for tests.
var gatewayBuilds atomic.Int64
-func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
+// alias is the name each model's usage is counted under (provider.UsageAlias),
+// nil for each its own id: a call is priced by the id it was made under
+// first, then counted under the alias.
+func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool, alias func(string) string) ([]GatewaySession, []GatewayDayUsage) {
gatewayBuilds.Add(1)
priceOf := Pricer()
type key struct{ agent, id string }
@@ -314,11 +320,15 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map
}
}
tokens := sessions.Tokens{Input: r.Input, Output: r.Output, CacheRead: r.CacheRead, CacheWrite: r.CacheWrite, CacheWrite1h: r.CacheWrite1h}
- dk := dayKey{r.Time.In(time.Local).Format(time.DateOnly), a, r.Model}
+ model := r.Model // priced above by the id it was made under
+ if alias != nil {
+ model = keep.of(alias(model))
+ }
+ dk := dayKey{r.Time.In(time.Local).Format(time.DateOnly), a, model}
for _, kept := range []map[dayKey]*GatewayDayUsage{daily, perSession[k]} {
d := kept[dk]
if d == nil {
- d = &GatewayDayUsage{Date: dk.date, Agent: a, Model: r.Model, Priced: true}
+ d = &GatewayDayUsage{Date: dk.date, Agent: a, Model: model, Priced: true}
kept[dk] = d
}
d.Input += tokens.Input
@@ -340,10 +350,10 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map
s.CacheRead += r.CacheRead
s.CacheWrite += r.CacheWrite
s.CacheWrite1h += r.CacheWrite1h
- m := models[k][r.Model]
+ m := models[k][model]
if m == nil {
- m = &GatewayModel{Model: r.Model, Priced: true}
- models[k][r.Model] = m
+ m = &GatewayModel{Model: model, Priced: true}
+ models[k][model] = m
}
m.addRecord(r, p)
})
diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.go
index 61b06e89a..d8203bf90 100644
--- a/internal/usage/gateway_sessions_test.go
+++ b/internal/usage/gateway_sessions_test.go
@@ -171,7 +171,7 @@ func TestGatewayWindowsShareOneProjection(t *testing.T) {
t.Fatalf("built %d projections for one log and %d ranges, want 1 kept and shared by them all", built, len(backs))
}
for _, back := range backs {
- want, _ := buildGatewaySessions(readLogSnapshot(), day(back), nil)
+ want, _ := buildGatewaySessions(readLogSnapshot(), day(back), nil, nil)
g, w := key(got[back]), key(want)
if len(g) != len(w) {
t.Fatalf("from %d days back: %d sessions, want %d: %+v", back, len(g), len(w), got[back])
diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go
index 10464f971..4422bc273 100644
--- a/internal/usage/summary_cache.go
+++ b/internal/usage/summary_cache.go
@@ -123,9 +123,12 @@ func usagePriceCacheKey(now time.Time) string {
// Sign-ins and plugin lists can change independently of providers.json.
// Their identity and price feeds affect both grouping and historical costs.
h := sha256.New()
- prices, _ := json.Marshal(settings.Load().ModelPrices)
+ st := settings.Load()
+ prices, _ := json.Marshal(st.ModelPrices)
aliases, _ := json.Marshal(provider.Renamed())
- fmt.Fprint(h, string(prices), string(aliases))
+ // and the names models' usage is counted under, which the groups key on
+ usageAliases, _ := json.Marshal(st.UsageAliases)
+ fmt.Fprint(h, string(prices), string(aliases), string(usageAliases))
for _, current := range provider.All() {
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index c3f26802a..b90d771be 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -801,6 +801,9 @@ func summarize(p Period, now time.Time, recs []Record) Summary {
func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[string]bool, read func(func(Record))) Summary {
renamed := provider.Renamed()
+ // the names models' usage is counted under (SlouchyQuill507): a model's
+ // row sums its ids, each call priced by its own id first
+ alias := provider.UsageAlias()
normalizedKeys := map[string]bool{}
for id := range historicalKeys {
if next, ok := renamed[id]; ok {
@@ -886,13 +889,17 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
agents[id] = a
}
a.add(r, pr)
- k, host := r.Provider+"/"+r.Model, ""
+ model := r.Model
+ if alias != nil {
+ model = alias(model)
+ }
+ k, host := r.Provider+"/"+model, ""
if w := who(r.Host); w != "" && (len(hosts[r.Provider]) > 1 || w != goesNow[r.Provider]) {
k, host = k+" @ "+w, w
}
m := models[k]
if m == nil {
- m = &Group{ID: k, Provider: r.Provider, Model: r.Model, Host: host}
+ m = &Group{ID: k, Provider: r.Provider, Model: model, Host: host}
models[k] = m
}
m.add(r, pr)
diff --git a/internal/usage/usage_alias_test.go b/internal/usage/usage_alias_test.go
new file mode 100644
index 000000000..1fce89e7d
--- /dev/null
+++ b/internal/usage/usage_alias_test.go
@@ -0,0 +1,98 @@
+package usage
+
+import (
+ "math"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// A model counted under another id (magpie model alias) is one row in the
+// usage summary and in a gateway session, and each call keeps the price of
+// the id it was made under: the alias's own price is never put on the
+// other id's calls (SlouchyQuill507 on Discord: deepseek-v4.1-flash and
+// deepseek-flash).
+func TestUsageAliasCountsTwoIdsAsOne(t *testing.T) {
+ resetUsageTest(t)
+ cfg := settings.Load()
+ cfg.ModelPrices = map[string]settings.ModelPrice{
+ "*/deepseek-v4.1-flash": {Input: new(2.0), Output: new(0.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
+ "*/deepseek-flash": {Input: new(100.0), Output: new(0.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
+ }
+ if err := settings.Save(cfg); err != nil {
+ t.Fatal(err)
+ }
+ at := time.Now().Add(-time.Minute)
+ Append(Record{Time: at, Agent: "pi", Session: "s", Provider: "p", Model: "deepseek-v4.1-flash", Input: 1000000, Status: 200})
+ Append(Record{Time: at, Agent: "pi", Session: "s", Provider: "p", Model: "deepseek-flash", Input: 1000000, Status: 200})
+
+ // off by default: two rows, as before
+ if s := Summarize(All); len(s.Models) != 2 {
+ t.Fatalf("with no alias: %+v", s.Models)
+ }
+ if got := GatewaySessions(time.Time{}, nil); len(got) != 1 || len(got[0].Models) != 2 {
+ t.Fatalf("with no alias: %+v", got)
+ }
+
+ if _, err := provider.SetUsageAlias("deepseek-v4.1-flash", "deepseek-flash"); err != nil {
+ t.Fatal(err)
+ }
+ s := Summarize(All)
+ if len(s.Models) != 1 || s.Models[0].ID != "p/deepseek-flash" || s.Models[0].Model != "deepseek-flash" || s.Models[0].Input != 2000000 {
+ t.Fatalf("aliased summary: %+v", s.Models)
+ }
+ // $2 for the v4.1 call at its own price, $100 for the other: not $200
+ if c := s.Models[0].Cost; math.Abs(c-102) > 1e-9 || math.Abs(s.Cost-102) > 1e-9 {
+ t.Fatalf("aliased cost %v (total %v), want 102: each call at its own id's price", c, s.Cost)
+ }
+ got := GatewaySessions(time.Time{}, nil)
+ if len(got) != 1 || len(got[0].Models) != 1 || got[0].Models[0].Model != "deepseek-flash" || got[0].Models[0].Input != 2000000 {
+ t.Fatalf("aliased session: %+v", got)
+ }
+ if m := got[0].Models[0]; !m.Priced || math.Abs(m.Cost-102) > 1e-9 {
+ t.Fatalf("aliased session cost: %+v", m)
+ }
+ if _, days := GatewaySessionWindow(time.Time{}); len(days) != 1 || days[0].Model != "deepseek-flash" || math.Abs(days[0].Cost-102) > 1e-9 {
+ t.Fatalf("aliased days: %+v", days)
+ }
+
+ // --reset: two rows again
+ if _, err := provider.SetUsageAlias("deepseek-v4.1-flash", ""); err != nil {
+ t.Fatal(err)
+ }
+ if s := Summarize(All); len(s.Models) != 2 {
+ t.Fatalf("after reset: %+v", s.Models)
+ }
+}
+
+// An unpriced id counted under a priced one leaves the merged row unpriced:
+// the alias's price is not borrowed for it.
+func TestUsageAliasKeepsUnpricedCallsUnpriced(t *testing.T) {
+ resetUsageTest(t)
+ cfg := settings.Load()
+ cfg.ModelPrices = map[string]settings.ModelPrice{
+ "*/known-model": {Input: new(5.0), Output: new(0.0), CacheRead: new(0.0), CacheWrite: new(0.0)},
+ }
+ if err := settings.Save(cfg); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provider.SetUsageAlias("zz-unknown-model-x", "known-model"); err != nil {
+ t.Fatal(err)
+ }
+ at := time.Now().Add(-time.Minute)
+ Append(Record{Time: at, Agent: "pi", Session: "s", Provider: "p", Model: "zz-unknown-model-x", Input: 1000000, Status: 200})
+ Append(Record{Time: at, Agent: "pi", Session: "s", Provider: "p", Model: "known-model", Input: 1000000, Status: 200})
+ got := GatewaySessions(time.Time{}, nil)
+ if len(got) != 1 || len(got[0].Models) != 1 {
+ t.Fatalf("session: %+v", got)
+ }
+ if m := got[0].Models[0]; m.Priced || math.Abs(m.Cost-5) > 1e-9 {
+ t.Fatalf("merged row %+v: want unpriced, $5 from the priced id only", m)
+ }
+ s := Summarize(All)
+ if len(s.Models) != 1 || math.Abs(s.Models[0].Cost-5) > 1e-9 || s.Models[0].Unpriced != 1 {
+ t.Fatalf("summary: %+v", s.Models)
+ }
+}