Skip to content

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

usage: a deleted provider's calls stay apart from a new one under its id

yetone3e22123c9c0a
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index 9dadf4ead..f49eaffdb 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -24,7 +24,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (`codexBody`) and take the fields Codex CLI adds by choice, such as `access_programs` (OpenAI's Daybreak), while `store`, `tool_choice` and `include`, which the backend needs as `codexBody` sets them, can't be set (`codexOwned`). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by `withPicks`; the editor has no box for it. A client's own top-level `access_programs` on Responses or Chat is carried to a Responses build as it came (`Request.AccessPrograms`), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. It reaches only the upstreams Codex itself sends it to (`keepsAccessPrograms`, #3172, see [gateway routing](gateway-routing.md)); it is taken out before the extraBody merge, so an `access_programs` the user puts in a provider's extraBody still goes. One object goes to every API; fields for one API alone are not a thing yet. A `thinking` budget it puts in on an Anthropic endpoint is fitted to a Claude that thinks only adaptively after the merge, as an agent's is (`adaptiveThinking`, `TestExtraBodyBudgetFittedToAdaptiveModel`). | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
-| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
+| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A provider deleted (`Delete`) is kept in providers.json's `deleted` with its name, `Was`, `Gave` and when (`provider.Deleted`): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to `Deleted.UsageID`, `<id>~<when, UTC>`, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (`Renames.Gone`, `Named.Deleted`). Deletes before this was kept have no record and go to whoever holds the id now. A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models (`waitsForPicks`), not the vendor's list. `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js
index 76f114a19..7087f3b0d 100644
--- a/internal/gui/assets/plugins/usage/i18n.js
+++ b/internal/gui/assets/plugins/usage/i18n.js
@@ -2,6 +2,7 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
+ "Deleted {date}": "{date} 已删除",
"Bar chart": "柱状图",
"Line chart": "折线图",
"Chart style": "图表样式",
@@ -204,6 +205,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
},
"zh-TW": {
+ "Deleted {date}": "{date} 已刪除",
"Bar chart": "長條圖",
"Line chart": "折線圖",
"Chart style": "圖表樣式",
@@ -406,6 +408,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
},
ja: {
+ "Deleted {date}": "{date} に削除",
"Bar chart": "棒グラフ",
"Line chart": "折れ線グラフ",
"Chart style": "グラフの種類",
@@ -608,6 +611,7 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
},
de: {
+ "Deleted {date}": "Gelöscht am {date}",
"Bar chart": "Balkendiagramm",
"Line chart": "Liniendiagramm",
"Chart style": "Diagrammart",
diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js
index 7b996ca07..d60bbaa52 100644
--- a/internal/gui/assets/plugins/usage/page.js
+++ b/internal/gui/assets/plugins/usage/page.js
@@ -1790,7 +1790,7 @@ function renderLedger() {
$("#ledPurpose").title = t("Purpose");
sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOwn("computer"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOwn("agent"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
- sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOwn("provider"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
+ sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: p.deleted ? t("Deleted {date}", { date: new Date(p.deleted).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }) }) : "" })), "Provider", (v) => { ledProvider = v; ledOwn("provider"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.name || a.id, note: [a.name && a.id, ...(a.providers || []).map((p) => t(p))].filter(Boolean).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledKey"), "All gateway keys", ledCallerKey, callers.map((k) => ({
v: k.id, name: k.name, note: "",
diff --git a/internal/provider/provider.go b/internal/provider/provider.go
index 105264605..87106afa3 100644
--- a/internal/provider/provider.go
+++ b/internal/provider/provider.go
@@ -487,6 +487,9 @@ type file struct {
// when it was removed and put back when it is added again (#2057; see
// plugin_left.go).
PluginLeft []LeftRecord `json:"pluginLeft,omitempty"`
+ // Deleted are the providers the user deleted, so the calls made to
+ // one stay its own when another is added under its id (Renames).
+ Deleted []Deleted `json:"deleted,omitempty"`
}
// Path is the file the user's providers live in.
@@ -1248,6 +1251,9 @@ func Delete(id string) error {
for _, p := range f.Providers {
if p.ID == id {
found = true
+ // its calls stay its own, not a provider's added later under
+ // its id (cybercaius on Discord)
+ f.Deleted = append(f.Deleted, Deleted{ID: p.ID, Name: p.Name, Icon: p.Icon, At: time.Now(), Was: slices.Clone(p.Was), Gave: slices.Clone(p.Gave)})
continue
}
keep = append(keep, p)
diff --git a/internal/provider/rename.go b/internal/provider/rename.go
index 1705097cc..e1121c5a5 100644
--- a/internal/provider/rename.go
+++ b/internal/provider/rename.go
@@ -163,6 +163,25 @@ type Gave struct {
Until time.Time `json:"until"`
}
+// Deleted is a provider the user deleted (Delete): the calls recorded
+// under its id, and under the ids it had (Was, Gave), until it was
+// deleted are its own, under its id while no other has taken it and
+// under UsageID once one has, never a provider's added later under the
+// same id. cybercaius on Discord: a provider deleted and
+// another added under its id showed as one on the Usage page.
+type Deleted struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ Icon string `json:"icon,omitempty"`
+ At time.Time `json:"at"`
+ Was []string `json:"was,omitempty"`
+ Gave []Gave `json:"gave,omitempty"`
+}
+
+// UsageID is the id its calls are counted under: its id and when it was
+// deleted, which no provider can take ("~" is never in one, Slug).
+func (d Deleted) UsageID() string { return d.ID + "~" + d.At.UTC().Format("20060102T150405") }
+
// Renames say which provider a call recorded under a provider id was
// made to, as its id is now: a provider renamed takes the calls recorded
// under the ids it had (Was), and an id another provider took since
@@ -178,6 +197,8 @@ type Renames struct {
// on, "" for a site two are on: a model list asked at a provider's
// bare domain before it was saved on its api. subdomain (OnSite)
sites map[string]string
+ // gone are the deleted providers by UsageID
+ gone map[string]Deleted
}
type gaveTo struct {
@@ -255,6 +276,13 @@ func SiteOf(host string) string {
return site
}
+// Gone is the deleted provider whose calls are counted under id: its
+// own id while no provider has it, or its UsageID.
+func (r Renames) Gone(id string) (Deleted, bool) {
+ d, ok := r.gone[id]
+ return d, ok
+}
+
// Timed is whether the id's calls go to more than one provider by when
// they were made, so Of needs each call's time.
func (r Renames) Timed(id string) bool { return len(r.gave[id]) > 0 }
@@ -298,17 +326,47 @@ func UsageRenames() Renames {
}
return Renames{now: map[string]string{}}
}
- r := renamesOf(f.Providers)
+ r := renamesOf(f.Providers, f.Deleted)
lastRenames.Store(&r)
return r
}
-func renamesOf(ps []Provider) Renames {
+func renamesOf(ps []Provider, deleted []Deleted) Renames {
r := Renames{now: map[string]string{}}
held := map[string]bool{}
for _, p := range ps {
held[p.ID] = true
}
+ give := func(id string, until time.Time, to string) {
+ if r.gave == nil {
+ r.gave = map[string][]gaveTo{}
+ }
+ r.gave[id] = append(r.gave[id], gaveTo{until, to})
+ }
+ for i, d := range deleted {
+ // its calls stay under its id until a provider is added under it,
+ // deleted since or there now
+ to := d.ID
+ if held[d.ID] || slices.ContainsFunc(deleted[i+1:], func(l Deleted) bool { return l.ID == d.ID || slices.Contains(l.Was, d.ID) }) {
+ to = d.UsageID()
+ }
+ if r.gone == nil {
+ r.gone = map[string]Deleted{}
+ }
+ r.gone[to] = d
+ if to != d.ID {
+ give(d.ID, d.At, to)
+ }
+ for _, w := range d.Was {
+ // the subscription's id is the subscription's (Rename)
+ if !subscriptionID(w) {
+ give(w, d.At, to)
+ }
+ }
+ for _, g := range d.Gave {
+ give(g.ID, g.Until, to)
+ }
+ }
for _, p := range ps {
for _, w := range p.Was {
// the subscription's id is the subscription's (Rename)
@@ -317,10 +375,7 @@ func renamesOf(ps []Provider) Renames {
}
}
for _, g := range p.Gave {
- if r.gave == nil {
- r.gave = map[string][]gaveTo{}
- }
- r.gave[g.ID] = append(r.gave[g.ID], gaveTo{g.Until, p.ID})
+ give(g.ID, g.Until, p.ID)
}
}
for _, gs := range r.gave {
diff --git a/internal/usage/rename_usage_test.go b/internal/usage/rename_usage_test.go
index 53045d99b..12c70c38d 100644
--- a/internal/usage/rename_usage_test.go
+++ b/internal/usage/rename_usage_test.go
@@ -4,6 +4,7 @@ import (
"context"
"net/http"
"slices"
+ "strings"
"testing"
"time"
@@ -224,3 +225,50 @@ func TestProbesOfAProviderOnAnotherHostOfItsSiteListIt(t *testing.T) {
t.Fatalf("deleted %s's rows: total %d", id, p.Total)
}
}
+
+// cybercaius on Discord: a provider deleted and another added under its
+// id were one on the Usage page, the new one with the old one's calls.
+// The deleted one's calls stay its own, under an id of their own, named
+// as it was and marked deleted; the new one has only its own.
+func TestDeletedProviderKeepsItsCallsFromOneAddedUnderItsID(t *testing.T) {
+ reportedHome(t)
+ if err := provider.Save(provider.Provider{ID: "relay", Name: "Old relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ then := time.Now().Add(-time.Hour)
+ Append(Record{Time: then, Agent: "codex", Session: "s1", Provider: "relay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+ Append(Record{Time: then.Add(time.Second), Agent: "codex", Session: "s1", Provider: "relay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+ if err := provider.Delete("relay"); err != nil {
+ t.Fatal(err)
+ }
+ if err := provider.Save(provider.Provider{ID: "relay", Name: "New relay", Key: "k2", Chat: "http://127.0.0.1:2/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ Append(Record{Time: time.Now().Add(time.Second), Agent: "codex", Session: "s2", Provider: "relay", Model: "gpt-9", Input: 100, Output: 10, Status: 200})
+
+ page := QueryPage(All, Filter{}, 0, 50)
+ if len(page.Providers) != 2 || page.Providers[0] != "relay" || !strings.HasPrefix(page.Providers[1], "relay~") {
+ t.Fatalf("providers %v", page.Providers)
+ }
+ old := page.Providers[1]
+ d, ok := provider.UsageRenames().Gone(old)
+ if !ok || d.ID != "relay" || d.Name != "Old relay" {
+ t.Fatalf("gone %q: %+v %v", old, d, ok)
+ }
+ if p := QueryPage(All, Filter{Provider: "relay"}, 0, 50); p.Sum.Calls != 1 {
+ t.Fatalf("the new one's: %+v", p.Sum)
+ }
+ if p := QueryPage(All, Filter{Provider: old}, 0, 50); p.Sum.Calls != 2 {
+ t.Fatalf("the deleted one's: %+v", p.Sum)
+ }
+ if vs := Vias(time.Time{}).Of("codex|s1"); len(vs) != 1 || vs[0].Provider != old {
+ t.Fatalf("vias of the deleted one %+v", vs)
+ }
+ calls := map[string]int{}
+ for _, g := range Summarize(All).Models {
+ calls[g.ID] += g.Calls
+ }
+ if calls["relay/gpt-9"] != 1 || calls[old+"/gpt-9"] != 2 {
+ t.Fatalf("summary %v", calls)
+ }
+}
diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go
index 765534f24..cb3ac2987 100644
--- a/internal/usageapi/usageapi.go
+++ b/internal/usageapi/usageapi.go
@@ -142,10 +142,17 @@ func providerFaces(all []provider.Provider) func(id string) Named {
for _, p := range all {
set[p.ID] = p
}
+ renames := provider.UsageRenames()
return func(id string) Named {
a := Named{ID: id}
if p, ok := set[id]; ok && p.Name != "" {
a.Name, a.Icon = p.Name, p.Icon
+ } else if d, ok := renames.Gone(id); ok {
+ at := d.At
+ a.Name, a.Icon, a.Deleted = d.Name, d.Icon, &at
+ if a.Name == "" {
+ a.Name = d.ID
+ }
} else if id == usage.UnknownProvider {
a.Name = "Local session"
} else {
@@ -275,6 +282,9 @@ type Named struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
+ // Deleted is when the provider was deleted, for one whose calls are
+ // kept apart from a provider's added under its id since
+ Deleted *time.Time `json:"deleted,omitempty"`
}
// LedgerPage is one page of the ledger: limit rows (100 when none is
diff --git a/internal/usageapi/usageapi_test.go b/internal/usageapi/usageapi_test.go
index 173538978..e624f6d44 100644
--- a/internal/usageapi/usageapi_test.go
+++ b/internal/usageapi/usageapi_test.go
@@ -1,6 +1,8 @@
package usageapi
import (
+ "path/filepath"
+ "strings"
"testing"
"time"
@@ -76,3 +78,39 @@ func TestProvidersNotSetUpAreNamed(t *testing.T) {
t.Errorf("models: %+v", s.Models)
}
}
+
+// cybercaius on Discord: the Usage page's Provider filter lists a
+// provider deleted and the one added under its id since apart, the
+// deleted one by its own name with when it was deleted.
+func TestDeletedProviderListedApartAndMarked(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ if err := provider.Save(provider.Provider{ID: "relay", Name: "Old relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "codex", Provider: "relay", Model: "gpt-9", Input: 10, Output: 2})
+ if err := provider.Delete("relay"); err != nil {
+ t.Fatal(err)
+ }
+ // while no other has its id, its calls stay under it, named as it was
+ if ps := LedgerPage(usage.All, usage.Filter{}, 0, 100).Providers; len(ps) != 1 || ps[0].ID != "relay" || ps[0].Name != "Old relay" || ps[0].Deleted == nil {
+ t.Fatalf("deleted, its id not taken: %+v", ps)
+ }
+ if err := provider.Save(provider.Provider{ID: "relay", Name: "New relay", Key: "k2", Chat: "http://127.0.0.1:2/v1", Models: []string{"gpt-9"}}); err != nil {
+ t.Fatal(err)
+ }
+ usage.Append(usage.Record{Time: time.Now().Add(time.Second), Agent: "codex", Provider: "relay", Model: "gpt-9", Input: 10, Output: 2})
+
+ got := map[string]Named{}
+ for _, p := range LedgerPage(usage.All, usage.Filter{}, 0, 100).Providers {
+ got[p.Name] = p
+ }
+ if n := got["New relay"]; n.ID != "relay" || n.Deleted != nil {
+ t.Errorf("the new one: %+v", n)
+ }
+ if n := got["Old relay"]; !strings.HasPrefix(n.ID, "relay~") || n.Deleted == nil {
+ t.Errorf("the deleted one: %+v (all %+v)", n, got)
+ }
+}