Commit Graph
15 Commits
Author SHA1 Message Date
yetone c201fe2266 usage: Codex's auto-review through a ChatGPT sign-in costs nothing (silverzhou)
silverzhou (Discord): codex-auto-review has been free for a long time,
but magpie still estimates a cost for it. OpenAI's Codex lead
(thsottiaux, "Day 2.1"): "We have made Auto-review free for all users
signed in through a ChatGPT account."

provider.ListPrice now prices codex-auto-review at $0 on the "codex"
provider, the one that holds only ChatGPT sign-ins, unless that sign-in
is on the Free plan: cybercaius measured auto-review spending the Free
allowance, which is why the gateway's freeOnChatGPT already left Free
out. That rule now has one owner, provider.ChatGPTReviewFree, and
freeOnChatGPT calls it. The plan is read from Codex's current sign-in;
an unreadable plan or a Codex signed out since counts as a paid plan
(priceOf's unknown-model branch answers $0 for it too).

Still priced, since nothing says those are free: codex-auto-review sent
with an API key (openai, chatgpt-api), through a relay, or a review
magpie made follow the session's model (the row's served model is that
model). A price the user set for the model wins over the $0.
PricedNameFor names the model itself, so the Requests list no longer
says "priced as gpt-5.6-luna". The usage summary cache key carries the
Codex plan, so a plan change re-prices cached views.

Old rows: prices are applied when the log is read, so every past
codex-auto-review row through a ChatGPT sign-in reads $0 after the
upgrade: Usage's Overview and Requests, the tray, the ledger and key
limits' estimated-cost caps (their in-memory sums are rebuilt at start).
Nothing is rewritten on disk.

Left alone: a Codex window's holds (apiPricer) still count these calls,
filed as #4181. docs/subsystems/providers-accounts.md has the rule.

Run at this tree (rebased on 033b17baf):
- mote-run: TestAutoReviewFreeOnChatGPTSignIn (provider) and
  TestAutoReviewFreeOnChatGPT (usage: ledger, Summarize, ledger sum,
  NewCoster), the KimiCode, CodexSignInPlan and gateway Review tests: ok.
- Red on the old code: both new tests fail with the code changes taken
  out (codex priced at luna, $0.234; summary 0.992 vs 0.758; key limit
  0.134).
- Broken by hand: dropping the plan check or the provider check turns
  the Free-plan and relay/openai assertions red in both tests.
- go vet on mote, and GOOS=linux and GOOS=windows; gofmt -l clean.
- At the rebased head, mote-run go test ./internal/provider
  ./internal/usage ./internal/usageapi ./internal/gateway: all ok (gateway 1883s, provider 846s,
  usage 158s, usageapi 4s); gofmt -l clean.
- Full suite: a mote run at the pre-rebase head reached two packages (ok)
  and then died (exit 144) when the touched-package run re-synced the
  same mote copy, at load ~340 with five other full suites; per the owner's
  ship-at-once rule it is run again after the push.
Not tried: a real auto-review row (none in ~/.codex/sessions or the
real usage log); a multi-account Codex with mixed plans (the live
sign-in's plan decides); the summary cache's plan key was not broken by
hand.
2026-10-29 16:11:26 +08:00
yetone 28c89afcef usage: a period's summary counts only the log's blocks since the last
Each call the gateway logged changed the log's version, and every
/api/usage ask for Week or Month counted the whole period again: on
the #2278 bench (a busy gateway, 4 calls a second, the GUI's polls every
5 s) topSummary was 11% of CPU, beside GC at ~30%.

A period's summary now keeps what it counted over the log's full blocks
(512 rows each, never written again once full) and counts only the
blocks since, then the last block. It counts afresh when anything a
count depends on changed: a block it counted was replaced, a rewrite,
prices or names (meta), cleared calls, the period's bounds or series, or
the keying (hosts, accounts, keyed providers) changed. In the last case
an account that newly answers for a provider splits that provider's
earlier calls too. Rows are counted in the same order as before, so
every float comes out bit-identical. The group maps are copy-on-write
over the kept prefix, and only what was touched is copied.

Run at this tree, 213a31b4d before this message (the parent is origin/main 7795f5573, no rebase):
- New TestSummaryCountedOnIsCountedAfresh. Over 3*512+100 rows, for
  Today, Week, Month and All, it DeepEquals the folded summary against
  summarizeFrom: after appends across a block edge, a new host, an
  account newly answering for openai, another block, and a log written
  over. It also checks that at least one summary per period was counted
  on from a prefix.
- Broken by hand twice. With the keying check skipped, red at "an
  account". With one block left uncounted, red at "first". Restored
  after each.
- On mote: go test ./internal/usage ./internal/usageapi ./internal/tui
  all ok (usage 17.2s); GOOS=linux/windows/darwin go vet -tags nogui
  ok; gofmt clean. Before the last comment-only edit: go test
  ./internal/gui is red only on TestMainWindowCorners/macOS_26_SDK,
  the known #3949 on mote's macOS 27.
- A/B on mote, v0.1.1963 against this, 240 s each, under the same
  polls and feed, with another session's GUI suite also running (load
  ~35):
  - topSummary: 3.24 s to 0.93 s of a 60 s CPU profile.
  - Polls, mean seconds:
    - /api/usage?period=7d: 0.16 to 0.13
    - /api/usage?period=30d: 0.27 to 0.14
    - all polls: 0.65 to 0.63
  - Steady RSS after 130 s: 892 to 920 MiB.
  - The cold-start peak at 30 s, before any calls were fed: 1000 to
    1219 MiB (ps); footprint peak 755 to 781 MB. The cold-start peak
    swings between runs; the RSS peak is the next work.

Not tried: rolling windows ("last:") and picked ranges are still
counted afresh on every ask, as before.

Refs #2278
2026-10-29 06:04:22 +08:00
yetone 42976f9a08 usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.

What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
  under id at that time belongs to now. Every usage reader goes through it:
  summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
  NewCoster, the Requests page's gateway blocks, probe rows and other
  computers' days, window holds and their history, buildVias, and
  gateway loggedAnswers. Visit stays as recorded so Of is taken once.
  The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
  into the old one. Rename onto, or Save of a new provider under, an id in
  another's Was moves it into that one's Gave with the time (giveID):
  calls before then stay the old provider's. freeID treats Was ids as
  taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
  a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
  of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
  release under a renamed id show under the new id at once. An id that was
  reused before this release has no hand-over time, so its calls show under
  whoever holds the id now, as before.

Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.

Run at the tree before the rebase; rebased onto 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone 1f589e3f4f usage: read today's usage ahead at startup
CyberCaius (Discord, Windows): "今天 N 次调用" is slow on the first
panel open after a start. The first usage?period=today parses
usage.jsonl: 0.33s for 2MB, 0.43s for a 40MB sandbox log here, more
on a slower disk. startBackend now runs usage.ReadAhead() in the
background, which works out today's summary into the summary cache,
so the panel's first ask finds it.

Parallel parsing was not done: with the read ahead, a request 1s
after start answers in 1-2ms, so there is nothing left to win there.

Test: TestReadAheadLeavesTodayNothingToRead. After ReadAhead, a
SummarizeTopIn(Today) parses nothing and works nothing out. Red with
ReadAhead's body emptied ("parsed the log 1 more times and was
worked out 1 more").

Run at tree 53ae48f72 (on origin/main 3b5a2f612): go test -tags nogui
-timeout 45m ./internal/usage ./internal/gui ok (TestCoreScriptBudget
included, no budget raised; app.js 1,317,465 of 1,317,486). GUI files
panel*, tray*, i18n-keys, routing-sessions (27 files, chromium and
webkit): 336 pass, 0 fail. gofmt clean. Earlier, at 7571ebc93: full
GUI suite 1095 pass; the 4 reds are two tests red on main too (#3497,
removed by hand gives "changed height 630 !== 561".
2026-10-24 23:49:08 +08:00
yetone ea9454d2d8 usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:

  magpie model alias deepseek-v4.1-flash deepseek-flash
  magpie model alias deepseek-v4.1-flash            (what it is counted as)
  magpie model alias deepseek-v4.1-flash --reset
  magpie model aliases

kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.

Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is 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. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.

Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.

Run (worktree at f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00
yetone e00fbdbbc7 usage: times and days follow the viewer's time zone, not the server's (Outvi V, Discord)
Outvi V reads a remote magpie through `magpie web`. The Usage page
bucketed calls by the server's days and hours, so a call at 9:00 in
UTC+8 showed under 1:00.

What changed:
- The Usage page (plugins/usage/page.js) names its browser's IANA zone
  in ?tz= on /api/usage, /api/usage/requests, /api/usage/heatmap, the
  CSV link and the export.
- usage.Zone turns the name into one cached *time.Location per name, so
  a Filter holding it stays a comparable cache key. An empty or unknown
  name, or a zone that keeps this computer's clock, is time.Local, so
  the desktop page, the tray and the TUI see no change and share caches.
- Filter.Zone carries the zone. Today/7d/30d, the chart's hour and day
  buckets and labels, the Day filter and the heatmap's days are all
  read in it (Clock().In(zone)). The summary cache is keyed by period
  and zone, and the request-page cache by the reader's date.
- Shared days from other computers are read with a 2-day margin, not
  1, since two zones can be 26h apart.
- Limit and quota resets are unchanged. The gateway's
  /v1/magpie/usage stays on the computer's zone.

Run at e435b8867 + this change:
- gofmt -l and go vet on internal/usage, internal/usageapi and
  internal/gui: darwin, GOOS=linux -tags nogui, and GOOS=windows. The
  vet ran before the new _test files were added.
- go test ./internal/usage ./internal/usageapi and
  -tags nogui ./internal/gui: ok with TZ=UTC and with
  TZ=Asia/Shanghai.
- New tests:
  - TestUsageReadsTheViewersZone and TestZoneNames (internal/usage).
  - TestUsageRoutesReadTheViewersZone (internal/gui) asks the routes
    with ?tz= naming a zone other than the server's.
  - Each holds usage.Clock and checks the hour label, today's
    membership, the Day filter, the week chart's day label and the
    heatmap's days. With no ?tz=, the server's days are kept.

Broken by hand:
- Clock().In(zone) / Clock().In(f.loc()) back to Clock(): red in both
  zones (Summary, Requests, ledger, heatmap, /api/usage,
  /api/usage/requests, /api/usage/heatmap).
- The Day filter read in time.Local: red under TZ=UTC.
- The summary's and chart's bucketing in time.Local: the week-day label
  check goes red under TZ=UTC. Under TZ=Asia/Shanghai the chosen
  moment falls on one date in both zones, so it can't tell there.
Each was restored after.

Not tried:
- A Playwright GUI test with timezoneId in Chromium and WebKit was
  not written. The GUI suite and usage-stale-answer.test.cjs (which got
  a usageZoneQ stub) were not run: the disk was at ~350 MB free.
- TestCoreScriptBudget was not run again after the change. app.js is
  untouched, and page.js is a plugin page outside the core budget.
- A real remote `magpie web` from another zone, and the Windows box.
- Siblings left alone:
  - The Sessions tab buckets by the server's days and hours in its
    cached rollups, and its "By hour" card labels them with the
    browser's zone name.
  - The Routing history's day files are the server's days.
  These need issues of their own.
2026-10-23 10:54:27 +08:00
yetoneandfchengyan 62378c5f84 cli, usage: magpie usage takes --last <dur> and --days <n>, a window ending now, with or without --csv and --account (#2075, tinysnake, fcy222fcy)
today, 7d and 30d begin at a local midnight, so a caller wanting "the
last few hours" just after midnight had to take 7d's CSV, seven days of
rows for one. `magpie usage [--csv [--account <name>]] --last 24h` (any
Go duration, 90m) or `--days 1.5` now reads a window that began that
long ago; the presets are unchanged.

From fcy222fcy's branch (usage-rolling-window, 60472c661): a rolling
window is a period "last:<dur>" (usage.LastOf / Period.Last) that Since,
Known, shown and the chart's timeline answer for, so the ledger, Direct
and the summary read the same window.

Review fixes on top:
- a summary of a rolling window is worked out each time, like a picked
  range: kept, its start didn't move with the clock while the log
  stayed the same (reachable through the web API's ?period=last:24h);
- the CSV export's file name has no colon from "last:24h0m0s", which
  Windows refuses;
- `--last 24h 7d` is refused rather than silently taking --last;
- --days refuses NaN, Inf and over a century;
- the help line and docs/reference.md name the flags.

Run: new TestRollingWindowIsNotKeptStale fails with the cache fix taken
out ("an hour later: 1 calls, want 0"); TestCSVStamp fails without the
colon fix ("magpie-requests-last:24h0m0s-2026-09-30");
TestUsageRollingWindowRejectsJunk fails without the preset/--days
checks; TestUsageRollingWindow and the new ...WithAccount fail (3 rows,
want 2) with Since moved back. go test -tags nogui ./internal/usage/...
./internal/cli/... ./internal/usageapi/... ./internal/gui/... in a
sandbox HOME: ok. gofmt -l clean; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows; go build darwin, linux nogui, windows.
Real use: the built binary on a sandbox HOME with a generated 50,000-call
7-day usage.jsonl: --csv 7d 47,233 rows / 6.97 MB; today 4,376; --last
24h 7,140 / 1.05 MB; --last 90m 444; --days 1.5 10,712; --account me@x
--last 24h 3,570 (that account's half); oldest row of each at the
window's start.
Not tried: the full go test ./... suite; the process still parses the
whole usage.jsonl into its in-memory index on each run (as every period
does), so the cut is in rows decoded and written, not bytes read.

Co-authored-by: fchengyan <3181088318@qq.com>
2026-10-14 15:26:28 +08:00
yetone 60f896031e usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.

- settings: clientAgents, client name (lowercased) -> agent id.
  ClientAgentsNow reads just that field through filememo, so a pass over
  the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
  for what is reported only: the summary, the agents list and filters,
  request rows and pages, priced blocks, direct, Vias and gateway
  sessions. The gateway's routing, keys and caps still go by AgentOf,
  the client's own name. The mapping is read once per ledger pass
  (readLogSnapshot) and is part of the keys of the summary price cache,
  the vias cache and the request page cache, so a change redraws the
  history already counted. A request row keeps the client's own name in
  a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
  client magpie already knows as an agent, "other" or magpie's own, and
  an "as" that isn't a known agent or is magpie. as "" counts it on its
  own again. /api/settings keeps the mapping it doesn't send. On the
  Usage page an unknown client's "…" offers "Count as an agent…" (a
  picker of the known agents), the agent's row says "with <client>",
  and the agent's "…" offers "Count <client> on its own". Strings are
  in all 5 languages.

Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
  mapping left out of the vias key or the request page key. With the
  summary key alone left out it stays green, because the settings stat
  already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
  (ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
  (its menu now has two items for an unknown client) pass in Chromium
  and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
  countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
  windows.

Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
2026-10-13 18:17:47 +08:00
yetone 99fcddeeba usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in
usage.jsonl. On Usage > Requests every filter, model pick and refresh
spun forever and the page never updated.

Reproduced in a sandbox HOME with 750k generated records in the real
format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process.
The cause: the #563 budget dropped the index's blocks once they passed
24 MB (60 MB here), so every read, of any period, parsed the whole file
again (6 s CPU) and priced every call again; All took 12 s of CPU, the
heatmap 13 s, and the page read both at once.

What changed:
- log_index: the gateway's blocks are always kept (about 80 bytes a call,
  S2-compressed instead of flate); the file is parsed once, then only
  what was appended.
- block_price: the gateway's blocks are priced per query, once per set of
  provider/model/served/effort names rather than per call, into pooled
  buffers; range loops go by pointer (a packed row is 264 bytes).
- request_page: pages are always cached (16 at most), session-file chunks
  stay in the budget, and a page asked again while it is worked out (the
  refresh button, the timer) waits for that one instead of starting a
  second scan.
- Siblings that read the same history:
  - The heatmap names each day once.
  - A day filter no longer allocates per call.
  - The ledger behind the TUI, magpie usage, the CSV export and sync
    (LedgerOf, OwnDays) reads the gateway's calls from the index instead
    of Load parsing the whole file.
  - Direct/Summaries matches the session files' calls against the index's
    blocks without pricing all 750k gateway calls.
  - A summary of more than 1024 sessions is now cached with its top 1024
    (it was not cached at all). The Usage page's /api/usage gets the top
    100 (it was sent all 84k, 19 MB, which it never draws) plus a new
    sessionCount. /v1/magpie/usage still lists every session, and magpie
    usage says "top 10 of <sessionCount>".

Timings, CPU (the box was at load 130-190 on 14 cores, so wall is
inflated; min of repeated runs), before -> after:
  Requests today            6.0 s  -> 20 ms
  Requests 7d               5.8 s  -> 93 ms
  Requests 30d              ~6 s   -> 362 ms
  Requests all              12.4 s -> 2.4 s first, ~8 ms again
  all, model filter         12.3 s -> 1.5 s
  all, agent filter         11.3 s -> 1.8 s
  30d, search "opus"        6.7 s  -> 353 ms
  day filter                6.0 s  -> ~0.1 s
  heatmap                   13.7 s -> ~2.3 s first
  summary today / all       6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again
  /api/usage?period=all     1.6 s + 19 MB JSON each time -> <1 ms, 53 KB
  TUI Summaries(all)        ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again
  TUI Summaries(today)      ~6 s   -> 29 ms
  Visit 7d (budget, codex)  5.9 s  -> 10 ms
The first read of the file after start costs ~5 s of CPU, once.

Tests (each seen red with its guarantee broken by hand):
- TestUsageOverBudgetHistoryIsReadOnce
- TestUsageSessionChunksStayInBudget
- TestUsageOverBudgetPageIsCached
- TestUsagePageAskedTwiceIsWorkedOutOnce
- TestUsageLedgerReadsTheIndexNotTheFile
- TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached)
- TestDirectCountsOnlySessionFileCalls, now with a request-id match,
  checks that Direct/Summaries equal the ledger's.

Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and
GOOS=windows go vet on the touched packages.
2026-10-11 04:44:13 +08:00
yetone 6d3bc9183d usage: the Usage and Requests pages count any days picked, from a Custom opt after All that opens a month to pick them on (#1492, nianlee-official)
The period bar had only Today, 7 days, 30 days and All. A Custom opt now
follows them. It opens the app's own menu (no native select): Yesterday,
This month, Last month and 90 days a click away, and a month of days to
pick the first day on, then the last. Days after today can't be picked;
arrows walk the days and Escape closes. Once picked, the opt names the
days ("Oct 1 – Oct 7"), and narrow windows show only its icon until then.

The backend takes the days as period "2026-10-01..2026-10-07", both
included, in the local time zone (usage.RangeOf, Period.Known/Until).
The summary, the Requests page (index and ledger fallback), Direct and the
CSV name count only calls from the first day's midnight up to the
midnight after the last. The chart is an hour each for one day, a day each
up to 60 days, and a week each from a Monday past that. A picked range is
summarised afresh each time, so ranges never pile up in the summary cache.
The credits-per-day card follows the days picked. New strings in zh,
zh-TW, ja and de.

Run:
- go test -tags nogui ./internal/usage ./internal/gui (sandbox HOME): ok.
- TestPickedDaysArePeriod with Until returning zero (no range end):
  FAIL, Summarize 5 calls / QueryPage 5 rows / LedgerOf 5 rows, want 3.
- usage-range.test.cjs, Chromium and WebKit, en and zh, at 390px: 4/4.
- Every GUI test touching period or the Usage view (87 files): Chromium
  388/388; WebKit 386/388, the two purpose-filter's Routing focus check
  (scrollTop off by 1px after a wheel), which then passed 52 of 56 lone
  runs here and 25 of 25 on origin/main; nothing in this change runs on
  the Routing page. gui-de, gui-ja, gui-zh-tw, i18n-keys: pass.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on both pkgs.
2026-10-10 19:15:12 +08:00
木子不是木子狸 c9b8263378 sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the
gateway (from the usage ledger, read-only, a native session of the same id
wins), and shows in gateway mode. A Sessions switch, off by default and
confirmed before it turns on, records each gateway exchange's text under
the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly).
Settings sync and restore can't turn it on; POST /api/sessions/recording
turns it on or off and can clear what was kept.

Why: users of magpie as a gateway (gateway mode, LAN clients) had no way
to see their conversations; the owner chose this design on the PR.

Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md
(kept main's placeMenu text, took the PR's Sessions in gateway mode) and
settings_keep_test.go (main's fields plus GatewayConversations).

Run: go build ./..., go vet on gateway, gui, sessions, settings, usage;
go test -race -timeout 900s on those five packages: all ok.
2026-10-10 04:24:18 +08:00
forever e961836fb0 usage, gateway, gui, provider, cli: the tests pass when a run crosses midnight, and a usage answer reads the clock once (#1046)
* usage: the usage tests pass at any time of day, midnight included

The usage tests stamped their calls with the machine's time and then
asked for today, 7 or 30 days, or a cached answer, which the code
worked out from its own time.Now a moment later. A minute after
midnight a call made "a minute ago" was yesterday's, and when midnight
fell between the test's read and the code's, the call and the period
were of two days. magpie usage, the TUI's Usage page, the two Codex
cache-write tests and the computers' shared days failed in the first
minutes after midnight (the TUI's after midnight UTC, the zone its
package's tests run in since 1caea638), and 28 more failed when
midnight fell inside them.

usage.Clock is now the time every period is read by: the start of
today, 7 days and 30 days (LedgerOf, Summarize, Direct, QueryPage), the
hours or days of the chart (LedgerSeries, QueryPage), the day a cached
summary or page is for, the time Append gives a call that has none,
the days davsync shares and the date in an exported CSV's name. It is
time.Now, as before, and a variable for the tests, like LogCalls. Each
test that built its calls from the time now holds Clock at noon on
2026-09-30 (holdClock; holdUsageClock in gui and the CLI; three lines
in tui and davsync) and stamps its calls from that instant, among them
TestReasoningReplyTimedByItsAnswer, whose timeline rows 117b6c7f made
at time.Now. TestPeriodsReadTheClock checks that every one of these
reads goes through Clock. TestQueryPageSourceAndIdentityInvalidation is
held too; that it fails when run alone is fixed apart from this, in
#1045.

Seven held tests could not fail at midnight before, and are held so
that the tests read one clock: TestUsageSameSizeAndMtimeRewrite (All's
totals), TestDirectCountsOnlySessionFileCalls (30 days around its own
noon), TestQueryPageIOOutsideCacheLock (a file two days old), gui's
TestUsageLedgerDayRoutes (7 days hold its calls from either day),
TestLedgerSingleSnapshotAndLocalSession and
TestLedgerNamesModelAtProvider (their calls are stamped after the code
reads the time), and TestUsageRawAndPricedChunksShareBudget, which
fails only when the midnight in it starts a new week of All's chart, on
a Sunday night; at.sh sets the time of day and not the weekday, so that
one was not shown.

Verified with at.sh, a scratch script that runs a test binary under a
zone made with zic, so that the local time of day is the one asked for
as the run starts (HOME in a sandbox, Go's caches pinned). The runs were
first made on c5a54bc7, and those marked (698da36f) again on 698da36f,
with the same results. The tui package runs in UTC since 1caea638, a
zone at.sh doesn't move, so its runs on 698da36f used copies of both
trees whose TestMain keeps the zone TZ sets.

Before, at 00:00:30, 00:01:30 and 12:00:00 (698da36f):
  TestUsageShowsCallsNotThroughMagpie, 00:00:30:
    usage_cli_test.go:95: no calls today · route an agent through
    magpie and its usage shows up here
  00:01:30: "5 tokens today · 1 call · no price", without the calls
  not through magpie; TestUsagePageShowsCallsNotThroughMagpie (tui)
  fails the same two ways at usage_test.go:138
  --- FAIL: TestCodexCacheWriteNotInInput (00:00:30)
    codex_cache_write_test.go:104: rows []
  --- FAIL: TestCodexCacheWriteMatchesGatewayCall (00:01:30)
    codex_cache_write_test.go:73: filter {...}: 0 rows, 0 calls, want
    the gateway's 2: []
  --- FAIL: TestUsageSharedBetweenComputers (00:01:30)
    usage_share_test.go:134: a's days on the server:
    [...-2026-10-05 ...-2026-10-06 ...-2026-10-07]
  12:00:00: PASS

Midnight inside a test, in scratch copies of the head. Started at
23:59:59.3 with the code's first period read held 1.5s, so that it
reads after midnight what the test stamped before it, 16 usage tests,
3 gui tests and TestUsageCSV FAIL, among them
  ledger_test.go:257: today: 0
  review_test.go:69: chart counted 0
  incremental_log_test.go:202: concurrent append lost
  TestCachedSummaryRemainsCallerOwned: panic: runtime error: index out
  of range [0] with length 0
  usage_test.go:121: second page: {... Period:today Rows:[] ...
  Total:0 ...}
  usage_test.go:311: "": magpie-requests-7d-2026-10-06
Started at 23:59:55 with the test waiting past midnight between two of
its reads, 7 more FAIL:
  request_day_test.go:45: selecting a day changed the chart or its
  legend
  cache_bounds_test.go:84: uncached today summary stale
  growing_rewrite_test.go:71: today summary stale
  cache_bounds_test.go:153: page key changed instead of exercising the
  same cache
  priced_blocks_test.go:55, caller_provider_test.go:129 and :172: page
  differs
TestReasoningReplyTimedByItsAnswer, with a scratch 1.5s sleep before
its LedgerSeries, started at 23:59:59.3 (698da36f):
  usage_test.go:255: part: {Calls:0 Tokens:0 Cost:0 Timed:0 TTFT:0
  DecodeMs:0 DecodeOut:0}

After: the same at.sh runs PASS at 00:00:30, 00:01:30 and 12:00:00
(698da36f); the same scratch copies made of this change PASS, each
test taking 1.5s or 5.2s, so midnight did fall inside it (698da36f for
TestReasoningReplyTimedByItsAnswer's); and every changed test PASS at
23:59:59.9, 00:00:30 and 12:00:00 (698da36f).

Without the change (698da36f): with the reads put back on time.Now, 21
usage tests, 6 gui, 2 CLI, the tui and the davsync test fail, among
them
  --- FAIL: TestPeriodsReadTheClock
    clock_test.go:55: Direct(Today): 0 calls since 2026-10-06 00:00:00
    -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT
    clock_test.go:63: Summarize(Today) the next day: 1 calls, want 0
  --- FAIL: TestReasoningReplyTimedByItsAnswer
    usage_test.go:255: part: {Calls:0 Tokens:0 ...}
Each of the eleven reads put back alone fails a test:
TestPeriodsReadTheClock for the nine in usage (LedgerSeries:
"clock_test.go:52: LedgerSeries(Today): 0 calls, want 2"; the page's
cache key: "clock_test.go:66: QueryPage(Today) the next day: 1 rows,
want 0"), TestCSVStamp for the CSV's name (usage_test.go:325: "":
magpie-requests-7d-2026-10-06) and TestUsageSharedBetweenComputers for
davsync (usage_share_test.go:224: all computers: 4 rows, 707 in; want
5, 737).

On this commit: go test -tags nogui -count=1 . ./internal/usage
./internal/tui ./internal/davsync ./internal/gui ok; -race -count=20
over the changed tests of each of these packages ok; gofmt -l prints
nothing, and go vet -tags nogui on the five packages finds nothing.

* usage: pages, CSVs and magpie usage asked at midnight show one day

An answer about usage read the time more than once. The Requests page
read it for the day it is kept for, for the period its log and session
files are read over, for the period of its rows and for its chart's
hours; the page from the ledger (QueryPage's path when LogCalls is
set, as in the tests) for its rows and for its chart; Direct for its
period and for its rows; a CSV for its rows and for its name;
magpie usage and the TUI's Usage page for Summarize and then for
Direct. Most of these reads have the log and the session files read
between them, seconds on a large log, and when midnight fell between
two of them the answer was of two days: yesterday's calls listed over
today's empty chart, Direct starting yesterday and counting none of
yesterday's calls, the calls not through magpie left out of magpie
usage and the Usage page (they were the new day's, none yet), and
yesterday's calls saved as magpie-requests-today-<the new day>.csv.

Each answer now reads Clock once and passes that moment down. queryPage
reads it for its key, its sources, its rows and its chart
(buildRequestBlocks takes it); the page from the ledger reads its rows
and its chart at it (LedgerOfAt, ledgerSeriesAt); Direct reads the
ledger at the moment of its period. usage.Summaries(p) is Summarize(p)
and Direct(p) at one moment, and magpie usage and the TUI's Usage page,
when a period is picked and when it is read again, ask for it: one
exported name, the clock left inside usage and one line changed at
each caller, where SummarizeAt and DirectAt would be two names and
each caller would read the clock itself. The CSV download and export
read their rows with the new usage.LedgerOfAt at the moment their file
is named for, which csvStamp now takes; the rows and the name are read
in two packages, so LedgerOfAt is exported. LedgerOf, LedgerSeries,
Summarize, Direct and QueryPage keep their signatures, each reading
Clock once.

The new tests set Clock to read a tenth of a second before midnight
the first time and a tenth of a second after it from then on, set
again for each answer. The midnight is the one that starts 2026-10-01,
local time: a past instant, at midnight because that is what is
tested, and the day before it is the 2026-09-30 the held tests use.
TestAnswerReadsTheClockOnce asks QueryPage(Today) from the indexed log
and from the ledger: its 3 rows, one from a session file written that
day at 23:00, are under that day's chart, and asked again after
midnight the page is the next day's, not the one kept for the day
before; Direct(Today) counts the call and starts that day.
TestUsageAskedAtMidnight (magpie usage today), TestUsagePageAtMidnight
(the TUI's Usage page, today picked and read again) and
TestUsageCSVAtMidnight (download and export) check that the calls
through magpie and those not through it, or the rows and the file's
name, are of the day asked on. TestCSVStamp passes its time.

Verified on the previous commit, at.sh as there. The runs were first
made on c5a54bc7, when the tui package's tests still ran in the local
zone, and those marked (698da36f) again on 698da36f, with the same
results.

Before: the new tests on the previous commit, at any time of day
(at.sh at 12:00:00 too) (698da36f):
  --- FAIL: TestAnswerReadsTheClockOnce
    clock_test.go:131: QueryPage(Today): 0 rows, 0 in a chart from
    2026-10-01 00:00:00 -0700 PDT; want 3 under one from 2026-09-30
    00:00:00 -0700 PDT
    clock_test.go:141: QueryPage(Today): 3 rows, 0 in a chart from
    2026-10-01 ...; want 3 under one from 2026-09-30 ...
    clock_test.go:145: Direct(Today): 0 calls since 2026-09-30
    00:00:00 -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT
  --- FAIL: TestUsageAskedAtMidnight
    usage_cli_test.go:154: 5 tokens today · 1 call · no price ...,
    with no part for the calls not through magpie
  --- FAIL: TestUsagePageAtMidnight
    usage_test.go:184: today picked: ... (the same)
    usage_test.go:187: read again: ...
  --- FAIL: TestUsageCSVAtMidnight
    usage_test.go:367: download: 200, attachment;
    filename="magpie-requests-today-2026-10-01.csv" with 2 rows
    (<nil>), want magpie-requests-today-2026-09-30.csv with 2
    usage_test.go:378: export: 200
    {"path":"~/Downloads/magpie-requests-today-2026-10-01.csv",
    "rows":1}, want magpie-requests-today-2026-09-30.csv with 1 row

With the real clock, in scratch copies of both trees: scratch tests
held one of Clock's reads 1.5s after it was made, as reading a large
log does (the first; for one of them the page's third, its chart's),
and at.sh started each at 23:59:59.3. Before, all 9 FAIL, among them
  asked 23:59:59.564, answered 00:00:01.068
  Direct(Today): 0 calls since 2026-10-05 00:00:00 -0940 MID, want 1
  since 2026-10-05 00:00:00 -0940 MID
  QueryPage(Today): 2 rows, 0 in a chart from 2026-10-06 ...; want 2
  under one from 2026-10-05 ...
  download: attachment; filename="magpie-requests-today-2026-10-06.csv"
  with a call of 2026-10-05 23:59
After, all 9 PASS, answered at 00:00:00.9 to 00:00:01.0, so midnight
fell inside each, except the chart's: its held read is gone with the
change. A scratch sleep before the chart shows that one: before "2
rows, 0 in a chart from 2026-10-06", after PASS, asked 23:59:59.344
and answered 00:00:00.941. At 12:00:00 all of them PASS in both trees.

After: every changed test PASS with at.sh at 23:59:59.9, 00:00:30 and
12:00:00 (698da36f).

Without the change (698da36f): with the production put back to the
previous commit's (gui/usage.go only so far that TestCSVStamp compiles:
csvStamp takes the time, read apart from the rows as before), go test
-count=1 . ./internal/usage ./internal/tui ./internal/gui fails the four
new tests and no other, with the lines above. Each of the 16 places put
back alone fails one of them: the page's key (clock_test.go:134: "3
rows, 3 in a chart from 2026-09-30 ...; want 0 under one from 2026-10-01
..."), its sources (:131: "2 rows"), its rows (:131: "0 rows"), its
chart (:131), the ledger page's rows and chart (:141), LedgerOfAt (:141,
:145), ledgerSeriesAt (:141), Direct (:145); Summaries, indexedSummary
and magpie usage (usage_cli_test.go:154); Summaries and the TUI's period
key and reload (usage_test.go:184, :187); the CSV's download and export
(usage_test.go:367, :378).

On this commit: go test -tags nogui -count=1 . ./internal/usage
./internal/gui ./internal/tui ./internal/davsync ./internal/gateway ok;
-race -count=20 over the changed tests of each package ok; gofmt -l
prints nothing, and go vet -tags nogui finds nothing.

* gateway: the key-limit tests pass when a run crosses local midnight

A go test run that crossed local midnight could fail the gateway's
key-limit tests. keyLimited and the /v1/magpie/limit endpoint each read
time.Now() when they check a key, and access.Window turns that into a
calendar window (a day from midnight, a week from Monday, a month from
the 1st). The tests seed "yesterday" from their own time.Now() and then
make several calls, so a run that crossed midnight saw its calls split
over two windows: the second call of a 350-token day was let in, or a
restart counted nothing.

The gateway's key-limit path now reads limitClock, a variable for the
tests like ruleClock and idClock, and production behaviour is unchanged
(it is time.Now). TestKeyLimitRefusesBeforeUpstream,
TestKeyLimitHoldsParallelRequests and TestKeyLimitWindowResets pin it
at 2026-09-30 12:00 local and seed "yesterday" from that instant. Calls
are still recorded at the real time, after the pinned one, and a window
counts every call from its start, so they all count in the pinned
window; the "tomorrow's window" check in TestKeyLimitWindowResets stays
on the real now, the first window with none of those calls in it. No
other test sets a key limit with records in its window (the gateway-key
CLI test and the GUI caller-key tests count 0 calls or have no limit).

TestKeyLimitRefusesBeforeUpstream now also checks that the 429's
Retry-After and X-Magpie-Limit-Reset name the next midnight after the
check, and that the limit endpoint's week starts on the pinned
Monday.

Verified with at.sh, a scratch script that runs the test binary under
a zone made with zic, so that the local time of day is the one asked
for as the run starts:
- before, at.sh at 23:59:59 with COUNT=500/300 and FRAC 0.3/0.6/0.8:
  3 of 6 runs of each test failed with
  key_limit_test.go:217: spent key let in
  key_limit_test.go:117: a restart forgot what the key used 200
  key_limit_test.go:121: status &{Period:day Start:2026-10-06 ...
  Calls:0 Tokens:0 ...}
- after, the same 6 runs (COUNT=500, both tests) print PASS, and so do
  ^TestKeyLimit at 12:00:00 and 00:00:00 with COUNT=20.
- go test -tags nogui -count=1 ./internal/gateway: ok (79.5s);
  -race -count=20 -run '^TestKeyLimit' ./internal/gateway: ok.
- gofmt -l prints nothing; go vet -tags nogui ./internal/gateway is
  clean.

The month boundary (TestKeyLimitHoldsParallelRequests) and Monday can't
be reproduced by changing the time of day; the pinned clock covers them
the same way.

Fails without the change (tests pinned, keyLimited back on time.Now):
--- FAIL: TestKeyLimitRefusesBeforeUpstream
    key_limit_test.go:107: headers map[... Retry-After:[80228]
    X-Magpie-Limit-Reset:[2026-10-07T00:00:00-07:00] ...]
and with only the limit endpoint back on time.Now:
--- FAIL: TestKeyLimitRefusesBeforeUpstream
    key_limit_test.go:159: limit endpoint {... "period":"week",
    "start":"2026-10-05T00:00:00-07:00" ...}

* gateway: the routing history tests pass when a run crosses midnight

TestHistoryKeepsDaysAndDropsOld and TestRemoteMagpieGroupHistory took
now := time.Now() and saved routes at now and now+1s. saveRoute files a
route by its own day (r.Time.Local()), so a test started at 23:59:59 put
the +1s route in tomorrow's file and History(today) found one route
less. TestHistoryKeepsSessionAndTokenTiers raced the other clock:
saveRoute prunes by time.Now(), so when the day turned between the
test's time.Now() and the first saveRoute, the prune gzipped "today"
after the first route, the second went to a new .jsonl, and the test's
own pruneHistory gzipped that over the first .gz, losing route 1.

saveRoute now prunes by historyClock (time.Now outside the tests). The
three tests take historyNoon(t), which holds that clock at
2026-09-30 12:00 local and returns it as their now, restored with
t.Cleanup. Every route, day file and prune is then on that one past day.
The fixture can't be a fixed past day without the clock: pruning by
the real today gzips that day's file at once (and, a month on, drops
it as too old).

The other history tests keep the real clock:
TestHistoryRouteOutsideDayLimit writes its day files itself from one
now and the code under test reads no clock, and
TestHistoryRouteDayAndNoLock already uses a fixed day.

Verified with at.sh, a scratch script that sets the local time of day
through a zone made with zic as the run starts:
- before, at.sh ./internal/gateway at 23:59:59:
  --- FAIL: TestHistoryKeepsDaysAndDropsOld
      history_test.go:50: days [{2026-10-06 1} {2026-10-05 1} {2026-10-04 1}]
  --- FAIL: TestRemoteMagpieGroupHistory
      remote_group_served_test.go:144: routes [... only ID 1 ...]
  and, with a 2s sleep after now := time.Now() standing in for the turn
  of the day, --- FAIL: TestHistoryKeepsSessionAndTokenTiers
      history_test.go:22: compressed history lost accounting: [only ID 2]
  12:00:00 control: PASS.
- after: the three tests PASS at 23:59:59, 23:59:59.9 (FRAC=0.9),
  12:00:00, and 23:59:59 with the same 2s sleep; all TestHistory* and
  TestRemoteMagpieGroupHistory PASS at 23:59:59 with -test.count=3.
- with saveRoute pruning by time.Now() again (the fixtures still pinned),
  at any time of day:
  --- FAIL: TestHistoryKeepsSessionAndTokenTiers
      history_test.go:32: compressed history lost accounting: [only ID 2]
- go test -tags nogui -count=1 ./internal/gateway: ok;
  -race -count=20 on the three tests: ok; gofmt -l and
  go vet -tags nogui ./internal/gateway print nothing.

* gateway, davsync: the request archive tests pass when a run crosses UTC midnight

The archive names a call "<date>/<id>" from the call's own start, in
UTC (archiving in archive.go). TestArchiveOn read time.Now().UTC()
before posting and TestRequestArchiveToS3 read it before post(), and
each expected that read's date. A run where UTC midnight (17:00 PDT)
fell between the test's read and the request's start expected the day
before the one the archive used, and failed.

Both tests now take the date from the Time the call carries
(s.Recent()[0].Time, the same start the archive's name is made from),
in UTC, so nothing is read from the clock a second time. No production
code changes. The other archive tests already go by the call's Archive
name, and internal/gui's archive test uses a fixed name; no other test
in internal/gateway, internal/davsync or internal/gui predicts an
archive key or a UTC-dated name from its own clock.

Verified: at.sh only moves the local time of day, and this is a UTC
crossing (UTC midnight was ~16h away), so it was shown in a scratch
copy whose serve starts each request 0.2s after the next UTC midnight,
as a request does when the test read the clock just before it. There
the old tests fail:
  archive_test.go:115: call archive "2026-10-07/000000-f4690de23ee8a859",
  want "2026-10-06/000000-f4690de23ee8a859"
  archive_test.go:93: nothing at
  "team x+y/magpie/archive/2026-10-06/000000-0e74a87816ef6a56.json"
and the new ones pass. Unshifted, under at.sh at local 23:59:59,
00:00:00 and 12:00:00, both pass, as the old ones do at 23:59:59 and
00:00:00 (local time doesn't enter the name). With archiving naming by
start.Format (local) instead of start.UTC().Format, both new tests fail
under at.sh at local 23:00:00, where the local date is a day behind
UTC's:
  --- FAIL: TestArchiveOn ... archive_test.go:116: call archive
  "2026-10-05/082500-7322712bd89f71da", want
  "2026-10-06/082500-7322712bd89f71da"
  --- FAIL: TestRequestArchiveToS3 ... archive_test.go:95: nothing at
  "team x+y/magpie/archive/2026-10-06/082500-3587ab4192da2cd5.json"
and pass at 12:00:00. go test -tags nogui -count=1 ./internal/gateway
./internal/davsync passes in a sandbox HOME; -race -count=20 -run
'^(TestArchiveOn|TestRequestArchiveToS3)$' passes; gofmt -l and go vet
-tags nogui on both packages are clean.

* gui: TestWhatsNewTodayRoute passes when the run crosses local midnight

TestWhatsNewTodayRoute posts {"on":true} to /api/whatsnew/today, which
writes today() to whatsnew-quiet-day, then checks quietToday(), which
compares the file with a second today(). A run that crossed local
midnight between the two read different days and failed with
"on: 204 false". The neighbouring TestWhatsNewQuietAfterRestartToUpdate
already pins today; this test didn't.

The test now pins today to 2026-09-30 (restored with t.Cleanup), so the
post and the check read the same day. The other What's new tests start
from an empty folder, so quietToday finds no file and never reads
today().

Verified: with a temporary 1s sleep between the post and the check, the
unpinned test under at.sh (local time of day set by a zone) started at
local 23:59:59.5 failed with "whatsnew_test.go:237: on: 204 false" and
passed at 12:00:00; pinned, it passes at 23:59:59.5 (same sleep), and,
without the sleep, at 23:59:59, 00:00:00 and 12:00:00. With
setQuietToday writing time.Now().Format("2006-01-02") instead of
today(), the test fails: "--- FAIL: TestWhatsNewTodayRoute ...
whatsnew_test.go:239: on: 204 false". go test -tags nogui -count=1
./internal/gui passes in a sandbox HOME; -race -count=20 -run
'^TestWhatsNewTodayRoute$' passes; gofmt -l and go vet -tags nogui
./internal/gui are clean.

* provider: TestZCodeStartSentAsTheApp passes when the run crosses midnight

A ZCode Start Plan request opens with a context prefix that says
"Today's date is <day>" (zcodeDateReminder), the day zcodeStartRequest
took from its own time.Now(). TestZCodeStartSentAsTheApp sent the
request, then built the expected prefix from a second time.Now(). A run
that crossed midnight between the two failed on "the context prefix",
the request holding the day before.

zcodeStartRequest now takes the time from zcodeClock (a package
variable, time.Now outside tests, as gateway's ruleClock), and the test
pins it to 2026-09-30 12:00 local, restored with t.Cleanup, and expects
"Today's date is 2026-09-30." The test sets TZ=Asia/Shanghai, which
moves time.Local only when nothing has read it yet; a mid-day instant in
time.Local formats to the same day either way. The other calls to
zcodeStartBody in the test check shaping only, not the day.

No other provider test builds a day string from a second clock: the
WorkBuddy credits, daily warm-up and check-in tests pass fixed times to
code that takes now as an argument, and TestQoderCheckinOnTheCard's day
is only carried, not compared.

Verified with at.sh (local time of day set by a zone, run as
-run '^(TestDailyCredits|TestZCodeStartSentAsTheApp)$' so that
time.Local is read before the test's t.Setenv("TZ"), as in a full run;
alone, Local becomes Asia/Shanghai): with a temporary 1s sleep after the
request, the unpinned test started at local 23:59:59.5 failed with
"zcode_client_test.go:195: the context prefix: ... Today's date is
2026-10-05." and passed at 12:00:00; pinned, it passes at 23:59:59.5
(same sleep) and, without the sleep, at 23:59:59, 00:00:00 and 12:00:00.
With zcodeStartRequest back on time.Now(), the pinned test fails:
"--- FAIL: TestZCodeStartSentAsTheApp ... zcode_client_test.go:196: the
context prefix: ... Today's date is 2026-10-06." go test -tags nogui
-count=1 ./internal/provider passes in a sandbox HOME; -race -count=20
-run '^TestZCodeStartSentAsTheApp$' passes; gofmt -l and go vet -tags
nogui ./internal/provider are clean.

* accounts, quota: a window's reset reads against one time per listing; TestQuotaCell passes across midnight

quotaCell, a window in `magpie accounts` and `magpie quota`, read the
clock three times: whether the reset had passed, how long until it, and
ResetClock's label, which names the calendar day ("tomorrow 02:13" or
"02:13"). TestQuotaCell set the reset 2h13m30s from time.Now() and
built the expected label from yet another time.Now(); a run that crossed
local midnight between quotaCell's read and the test's got "tomorrow
02:13" from one and "02:13" from the other and failed.

quotaCell now takes now. accountsCmd and quotaCmd take one time.Now()
just before printing and pass it to every window's cell, so a listing's
windows agree on what "today" is. The test passes a fixed 2026-09-30
12:00 local and expects "↻2h13m 14:13", and for a reset the next day
"↻14h13m tomorrow 02:13"; no zone in tzdata 2026c changes its clock
between those instants, so both read the same in any TZ. resetsCell's
label, quotaReadingCell's expired check and quotaResetCmd's prompt
still read time.Now(); no test compares them against a second clock.
internal/tui's quotaCell and quotaLines already take now, and their
tests pass a fixed one.

Verified with at.sh (local time of day set by a zone): with a temporary
1s sleep between quotaCell and the check, the old test started at local
23:59:59.5 failed with "accounts_cli_test.go:128: \"5h 42% ↻2h13m
tomorrow 02:13\"" and passed at 12:00:00; the new one passes at
23:59:59.5 (same sleep) and, without the sleep, at 23:59:59, 00:00:00
and 12:00:00. Putting any of quotaCell's three reads back on the wall
clock fails the test ("--- FAIL: TestQuotaCell"). ResetClock's now
alone fails the next-day case: "accounts_cli_test.go:134: tomorrow:
\"7d 42% ↻14h13m 02:13\"". The passed check alone, or all three:
"accounts_cli_test.go:129: \"5h 42% · reset time passed Sep 30
14:13\"". untilShort alone: "accounts_cli_test.go:129: \"5h 42% ↻now
14:13\"". go test -tags nogui -count=1 . passes in a sandbox HOME;
-race -count=20 -run '^TestQuotaCell$' passes; gofmt -l and go vet
-tags nogui . are clean.
2026-10-07 02:14:29 +08:00
Snowyy 7464ee5075 usage: bound retained chunks and invalidate same-stat rewrites (#563) 2026-10-02 22:00:10 +08:00
yetone 5332c0c638 usage: each subscription account's tokens and cost, by the account that answered (#557: 希望用量账本能按订阅账号统计,每个 Codex / Claude 账号各用了多少 token、多少钱) — a call's record named the upstream key it went out on (ProviderKeyID/Name, #500) but never the subscription account, so with two Codex accounts signed in, or a Claude account that took over after a failover, the ledger could say what Codex cost and not what each account did. A record now carries providerAccount, the account that answered as the Routing trace names it (Account.User: its email or login, never a token), set by the gateway at the try that went out (the candidate loop's last try, so a failover's answer is the account that took over and the refused try stays the first account's; an X-Magpie-Account pin is the pinned one), and on the decide, draw and video paths too. Record.Account() gives it, or for a record written before the field the account its host named (Where() has long written "chatgpt.com as dee@example.com" for an account), and otherwise "" — shown as "account not recorded", never inferred from today's sign-in. The summary groups calls by provider and account (Summary.Accounts, the same email on Codex and on Claude being two accounts), priced as every other group; the ledger's Filter has Account, the search finds a call by its account, the CSV has a provider_account column beside provider_key_name (the provider's identity columns together, the caller's still last), and the Requests page's packed rows keep it and offer the period's accounts. magpie usage prints an accounts table after the provider keys, and magpie usage --csv --account <name> keeps one account's calls. The app's Usage page lists Accounts on the Overview (tokens and cost per account, the provider under its name, an unrecorded one in the faint colour, no stripe down a row's side) and has an Account filter on Requests, each account noting the providers it answered for, which asks for and exports that account's calls without moving the page. OTLP export is an allowlist and does not carry the account. TestUsageNamesPinnedAccount (both pinned accounts on magpie's endpoint and on Codex's own, the trace's Who and the record agreeing, no token in usage.jsonl) and TestUsageNamesAccountThatTookOver (Ordered routing, the first account refusing: the answer recorded as the spare, the refusal as the first) fail without the gateway change; TestSummaryByAccount, TestLedgerByAccount and TestRequestPageByAccount cover the grouping, the host fallback, "not recorded", keyed providers kept out, the filter, the search, the CSV column and the packed rows; TestLedger and TestLedgerWithSessionLogCalls take the new column. usage-accounts.test.cjs (WebKit and Chromium, en and zh: the Overview's accounts and costs, the Account picker's notes, its request and export, All accounts clearing it, scrollTop unchanged) fails without the asset change; api-key-usage, click-scroll, panel-usage, request-archive-usage, tray-usages, claude-usage-asked and every usage-* test pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState failed once on its TempDir cleanup, passes alone). 2026-10-02 20:15:33 +08:00
Snowyy 9657d3e9d8 usage: reuse incremental log blocks and index CSV matches (#550) 2026-10-02 19:15:56 +08:00