diff --git a/docs/reference.md b/docs/reference.md
index 17dc6371e..d1e093f00 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -3838,6 +3838,7 @@ magpie settings get usageAlert
magpie settings set noBird on # checked and saved as the window saves it
magpie settings set redactWords acme,globex
magpie settings reset theme # back to its default
+magpie settings set dayStart 4 # a day starts at 4:00 (0 to 6): the Usage page and daily and monthly key caps cut days there; the Sessions page does not yet
magpie quota # what is left of every subscription, plan and key balance
magpie quota refresh codex # read Codex's cards again now (once per 30s)
diff --git a/internal/access/limit.go b/internal/access/limit.go
index 292554b76..7240d53a7 100644
--- a/internal/access/limit.go
+++ b/internal/access/limit.go
@@ -1,6 +1,9 @@
package access
import (
+ "github.com/yetone/magpie/internal/dayzone"
+ "github.com/yetone/magpie/internal/settings"
+
"errors"
"fmt"
"math"
@@ -275,8 +278,13 @@ func (l *Limit) Window(now time.Time) (start, reset time.Time) {
// Window is the calendar window of period that now is in, in now's
// location: its start and when the next begins.
func Window(period string, now time.Time) (start, reset time.Time) {
+ // a day that starts after midnight (settings.DayStart) moves the
+ // calendar: the week and the month begin at that hour too
+ home := now.Location()
+ loc := dayzone.Shift(home, settings.Shared().DayStart)
+ now = now.In(loc)
y, m, d := now.Date()
- loc := now.Location()
+ defer func() { start, reset = start.In(home), reset.In(home) }()
switch period {
case "week":
back := (int(now.Weekday()) + 6) % 7 // days since Monday
diff --git a/internal/access/limit_test.go b/internal/access/limit_test.go
index f33eda81f..66eae2f30 100644
--- a/internal/access/limit_test.go
+++ b/internal/access/limit_test.go
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/settings"
)
func TestLimitWindow(t *testing.T) {
@@ -499,3 +501,34 @@ func TestLimitTotal(t *testing.T) {
}
func v0(period string) *Limit { return &Limit{Period: period, Cost: 1} }
+
+// A day that starts at 4 moves every calendar window: at 02:00 on the 15th
+// the day is the 14th's from 04:00, the week and the month are those the
+// 14th is in, and with the start at 0 nothing moves.
+func TestLimitWindowFollowsTheDayStart(t *testing.T) {
+ t.Cleanup(func() { s := settings.Load(); s.DayStart = 0; settings.Save(s) })
+ loc := time.FixedZone("X", 8*3600)
+ at := func(d, h int) time.Time { return time.Date(2026, 9, d, h, 0, 0, 0, loc) }
+ cases := []struct {
+ period, start, name string
+ now, from, to time.Time
+ }{
+ {"day", "4", "day", at(15, 2), at(14, 4), at(15, 4)},
+ {"day", "4", "day after", at(15, 4), at(15, 4), at(16, 4)},
+ {"week", "4", "week starts Monday 4am", at(14, 2), at(7, 4), at(14, 4)}, // Mon 14th 02:00 is still Sunday's
+ {"month", "4", "month", at(1, 2), time.Date(2026, 8, 1, 4, 0, 0, 0, loc), at(1, 4)},
+ {"day", "0", "plain", at(15, 2), at(15, 0), at(16, 0)},
+ }
+ for _, c := range cases {
+ n := int(c.start[0] - '0')
+ s := settings.Load()
+ s.DayStart = n
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+ from, to := Window(c.period, c.now)
+ if !from.Equal(c.from) || !to.Equal(c.to) || from.Location() != loc {
+ t.Errorf("%s: Window(%s, %v) = %v..%v in %v, want %v..%v in %v", c.name, c.period, c.now, from, to, from.Location(), c.from, c.to, loc)
+ }
+ }
+}
diff --git a/internal/dayzone/dayzone.go b/internal/dayzone/dayzone.go
new file mode 100644
index 000000000..c06342a15
--- /dev/null
+++ b/internal/dayzone/dayzone.go
@@ -0,0 +1,146 @@
+// Package dayzone makes a time zone whose midnight falls at a chosen hour
+// of the real day, so that every place that cuts days by the zone's
+// midnight (the Usage page, a daily cap) cuts them there without knowing:
+// with a day that starts at 4, a call at 01:30 belongs to the day before
+// (ssharpcc on X: coding past 1am should count toward the day before).
+package dayzone
+
+import (
+ "encoding/binary"
+ "sync"
+ "time"
+)
+
+// MaxStart is the latest hour a day may start at.
+const MaxStart = 6
+
+type key struct {
+ loc *time.Location
+ hour int
+}
+
+var (
+ mu sync.Mutex
+ made = map[key]*time.Location{}
+ shifts sync.Map // *time.Location → time.Duration
+)
+
+// Shift is loc moved so that its midnight is the real day's hour:00: the
+// same offsets, hour hours less each, with the same changes of daylight
+// saving at the same instants. An hour outside 1 to MaxStart is loc itself.
+// The same location comes back for the same loc and hour, so a Filter
+// holding it is the same cache key each time.
+func Shift(loc *time.Location, hour int) *time.Location {
+ if hour < 1 || hour > MaxStart {
+ return loc
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ k := key{loc, hour}
+ if l, ok := made[k]; ok {
+ return l
+ }
+ l, err := time.LoadLocationFromTZData(loc.String()+"+"+string(rune('0'+hour)), tzif(loc, hour))
+ if err != nil {
+ return loc // never: the data is made here
+ }
+ made[k] = l
+ shifts.Store(l, time.Duration(hour)*time.Hour)
+ return l
+}
+
+// Offset is how far loc's midnight lies after the real midnight: the hour a
+// shifted zone's day starts at, 0 for any other.
+func Offset(loc *time.Location) time.Duration {
+ if d, ok := shifts.Load(loc); ok {
+ return d.(time.Duration)
+ }
+ return 0
+}
+
+// The changes of a zone are listed this many years either way from now.
+// Past the last one the zone keeps its last offset, as a version 1 zoneinfo
+// file does; the span is long against a run of magpie.
+const (
+ yearsBack = 4
+ yearsAhead = 4
+)
+
+// tzif writes loc's offsets, each hour hours less, as a version 1 zoneinfo
+// file Go reads back: the instants the offset changed in the span, and the
+// offset from each.
+func tzif(loc *time.Location, hour int) []byte {
+ type kind struct {
+ off int
+ dst bool
+ name string
+ }
+ var kinds []kind
+ at := func(t time.Time) int {
+ l := t.In(loc)
+ name, off := l.Zone()
+ k := kind{off - hour*3600, l.IsDST(), name}
+ for i, x := range kinds {
+ if x == k {
+ return i
+ }
+ }
+ kinds = append(kinds, k)
+ return len(kinds) - 1
+ }
+ y := time.Now().Year()
+ start := time.Date(y-yearsBack, time.January, 1, 0, 0, 0, 0, time.UTC)
+ end := time.Date(y+yearsAhead, time.January, 1, 0, 0, 0, 0, time.UTC)
+ prev := at(start)
+ var times []int32
+ var idx []byte
+ same := func(a, b time.Time) bool { return at(a) == at(b) }
+ for t := start.Add(time.Hour); t.Before(end); t = t.Add(time.Hour) {
+ if same(t, t.Add(-time.Hour)) {
+ continue
+ }
+ // the change is within the last hour: find its second
+ lo, hi := t.Add(-time.Hour).Unix(), t.Unix()
+ for hi-lo > 1 {
+ mid := (lo + hi) / 2
+ if same(time.Unix(mid, 0), t.Add(-time.Hour)) {
+ lo = mid
+ } else {
+ hi = mid
+ }
+ }
+ k := at(time.Unix(hi, 0))
+ if k == prev {
+ continue
+ }
+ prev = k
+ times = append(times, int32(hi))
+ idx = append(idx, byte(k))
+ }
+ var abbr []byte
+ pos := make([]byte, len(kinds))
+ for i, k := range kinds {
+ pos[i] = byte(len(abbr))
+ abbr = append(abbr, k.name...)
+ abbr = append(abbr, 0)
+ }
+ out := []byte("TZif")
+ out = append(out, 0)
+ out = append(out, make([]byte, 15)...)
+ for _, n := range []int{0, 0, 0, len(times), len(kinds), len(abbr)} {
+ out = binary.BigEndian.AppendUint32(out, uint32(n))
+ }
+ for _, t := range times {
+ out = binary.BigEndian.AppendUint32(out, uint32(t))
+ }
+ out = append(out, idx...)
+ for i, k := range kinds {
+ out = binary.BigEndian.AppendUint32(out, uint32(int32(k.off)))
+ d := byte(0)
+ if k.dst {
+ d = 1
+ }
+ out = append(out, d, pos[i])
+ }
+ return append(out, abbr...)
+}
diff --git a/internal/dayzone/dayzone_test.go b/internal/dayzone/dayzone_test.go
new file mode 100644
index 000000000..09b31bf0e
--- /dev/null
+++ b/internal/dayzone/dayzone_test.go
@@ -0,0 +1,60 @@
+package dayzone
+
+import (
+ "testing"
+ "time"
+)
+
+func mustLoad(t *testing.T, name string) *time.Location {
+ t.Helper()
+ l, err := time.LoadLocation(name)
+ if err != nil {
+ t.Skipf("no zone data for %s: %v", name, err)
+ }
+ return l
+}
+
+// The day starts at the hour: a call a minute before it belongs to the day
+// before, the hour itself to the new day, in a zone without daylight saving
+// and in ones that have it (north and south), across each of their changes.
+func TestDayStartsAtTheHour(t *testing.T) {
+ for _, name := range []string{"Asia/Shanghai", "America/New_York", "Australia/Sydney", "Pacific/Kiritimati", "UTC"} {
+ loc := mustLoad(t, name)
+ for _, hour := range []int{1, 4, 6} {
+ sh := Shift(loc, hour)
+ if Shift(loc, hour) != sh {
+ t.Fatalf("%s %d: not the same location twice", name, hour)
+ }
+ if got := Offset(sh); got != time.Duration(hour)*time.Hour {
+ t.Fatalf("%s %d: Offset = %v", name, hour, got)
+ }
+ y := time.Now().Year()
+ for d := time.Date(y-1, 1, 1, 12, 0, 0, 0, loc); d.Year() <= y+1; d = d.AddDate(0, 0, 1) {
+ start := time.Date(d.Year(), d.Month(), d.Day(), hour, 0, 0, 0, loc)
+ if start.Hour() != hour {
+ continue // that wall hour is skipped on this date
+ }
+ day := time.Date(d.Year(), d.Month(), d.Day(), 12, 0, 0, 0, time.UTC)
+ before, after := start.Add(-time.Minute).In(sh), start.In(sh)
+ if before.Format(time.DateOnly) != day.AddDate(0, 0, -1).Format(time.DateOnly) {
+ t.Fatalf("%s h%d: %v is in %s, want the day before %s", name, hour, start.Add(-time.Minute), before.Format(time.DateOnly), day.Format(time.DateOnly))
+ }
+ if after.Format(time.DateOnly) != day.Format(time.DateOnly) || after.Hour() != 0 || after.Minute() != 0 {
+ t.Fatalf("%s h%d: day start %v reads %v in the shifted zone", name, hour, start, after)
+ }
+ }
+ }
+ }
+}
+
+func TestNoShiftIsTheZoneItself(t *testing.T) {
+ loc := mustLoad(t, "Asia/Shanghai")
+ for _, h := range []int{-1, 0, MaxStart + 1} {
+ if Shift(loc, h) != loc {
+ t.Fatalf("hour %d shifted", h)
+ }
+ }
+ if Offset(loc) != 0 {
+ t.Fatal("a plain zone has an offset")
+ }
+}
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 8395ed907..5f91d0f79 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -20586,6 +20586,7 @@ function renderTrayUsage(s, keep) {
$("#unitsRow").hidden = locale !== "zh" && locale !== "zh-TW";
$("#unitsSegs").replaceChildren(segs([[false, t("K / M / B")], [true, t("万 / 亿")]], !!s.chineseUnits,
(v) => savePrefs({ ...keep, chineseUnits: v })));
+ $("#dayStartSegs").replaceChildren(segs([...Array(7).keys()].map((h) => [h, h + ":00"]), s.dayStart || 0, (v) => savePrefs({ ...keep, dayStart: v })));
renderAlerts(s, keep);
$("#plainNamesSegs").replaceChildren(suffixSegs());
sayNoNamesInSettings();
@@ -22741,7 +22742,7 @@ function prefsKeep(s) {
replyModel: s.replyModel || "", noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null, retryAfterCap: s.retryAfterCap ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayNoNumber: !!s.trayNoNumber, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", videoGen: s.videoGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
- chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
+ chineseUnits: !!s.chineseUnits, dayStart: s.dayStart || 0, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
turnDoneAlert: s.turnDoneAlert || 0, maskAlert: !!s.maskAlert };
}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 16c4bafca..2f0c64053 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -1419,6 +1419,7 @@ const I18N = {
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "仅手动:打开或刷新用量页、卡片上的刷新,以及 magpie quota 或 accounts 才会读取;在那之前,路由、菜单栏和提醒都按上次读到的额度。被厂商以额度为由拒绝的账号仍会读取。",
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每个周期显示已用额度或剩余额度,用量页、面板和菜单栏一致",
"Currency": "货币",
+ "Day starts at": "一天从几点开始",
"Number units": "数字单位",
"How a large count of tokens or requests is shortened on the Usage page and the panel": "用量页和面板上较大的 token 数、请求数用什么单位缩写",
"万 / 亿": "中文(万 / 亿)",
@@ -6549,6 +6550,7 @@ const I18N = {
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "僅手動:開啟或重新整理用量頁、卡片上的重新整理,以及 magpie quota 或 accounts 才會讀取;在那之前,路由、選單列和提醒都依上次讀到的額度。被廠商以額度為由拒絕的帳號仍會讀取。",
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每個週期顯示已用額度或剩餘額度,用量頁、面板和選單列一致",
"Currency": "貨幣",
+ "Day starts at": "一天從幾點開始",
"Number units": "數字單位",
"How a large count of tokens or requests is shortened on the Usage page and the panel": "用量頁和麵板上較大的 token 數、請求數用什麼單位縮寫",
"万 / 亿": "中文(萬 / 億)",
@@ -11640,6 +11642,7 @@ const I18N = {
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "手動のみ:使用状況ページを開くか更新したとき、カードの更新、magpie quota または accounts で読み込みます。それまでルーティング、メニューバー、通知は前回の値を使います。利用枠を理由にベンダーに断られたアカウントは引き続き読み込みます。",
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "使用量ページ、パネル、メニューバーで、各期間の使用済み量と残量のどちらを表示するか",
"Currency": "通貨",
+ "Day starts at": "1日の開始時刻",
"Number units": "数値の単位",
"How a large count of tokens or requests is shortened on the Usage page and the panel": "使用量ページとパネルで、大きなトークン数やリクエスト数をどの単位で短縮するか",
"万 / 亿": "万 / 億",
@@ -16766,6 +16769,7 @@ const I18N = {
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "Nur auf Anfrage: beim Öffnen oder Aktualisieren der Nutzungsseite, beim Aktualisieren einer Karte und mit magpie quota oder accounts; bis dahin richten sich Routing, Menüleiste und Hinweise nach dem zuletzt gelesenen Stand. Ein Konto, das ein Anbieter wegen seines Kontingents abweist, wird trotzdem gelesen.",
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "Wie viel jedes Zeitfensters verbraucht oder übrig ist, auf der Seite „Nutzung“, im Panel und in der Menüleiste",
"Currency": "Währung",
+ "Day starts at": "Der Tag beginnt um",
"Number units": "Zahleneinheiten",
"How a large count of tokens or requests is shortened on the Usage page and the panel": "Wie große Token- oder Anfragezahlen auf der Seite „Nutzung“ und im Panel abgekürzt werden",
"万 / 亿": "Chinesisch (万 / 亿)",
diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html
index c1966ba47..436487fa2 100644
--- a/internal/gui/assets/index.html
+++ b/internal/gui/assets/index.html
@@ -318,6 +318,10 @@
+
Number units
How a large count of tokens or requests is shortened on the Usage page and the panel
diff --git a/internal/gui/tests/day-start.test.cjs b/internal/gui/tests/day-start.test.cjs
new file mode 100644
index 000000000..aa921ac52
--- /dev/null
+++ b/internal/gui/tests/day-start.test.cjs
@@ -0,0 +1,110 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// The "Day starts at" setting (ssharpcc on X): the Settings page offers hours
+// 0 to 6, picking one saves dayStart without scrolling the page, and the
+// choice is still picked after a reload. No backend, the API is faked here.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+const { openPart } = require("./reader.cjs");
+
+const assets = path.resolve(__dirname, "../assets");
+
+const usage = {
+ calls: 5, errors: 0, input: 12000, output: 4000, cache_read: 500, cache_write: 100, reasoning: 200,
+ unpriced: 0, cost: 12.34, bucket: "day",
+ series: [{ label: "Mon", input: 6000, output: 2000, calls: 3, cost: 7 }],
+ agents: [{ name: "Claude Code", calls: 5, cost: 12.34 }],
+ models: [{ name: "claude-opus", calls: 5, cost: 12.34 }],
+};
+
+function settingsPayload(over) {
+ return {
+ theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd", dayStart: 0,
+ dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
+ codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
+ trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
+ version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
+ proxyNow: "none", proxySource: "none", login: false,
+ visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
+ fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
+ ...over,
+ };
+}
+
+function server(lang, saved) {
+ let cur = settingsPayload({ lang });
+ return async (route) => {
+ const req = route.request(), url = new URL(req.url());
+ const json = (data) => route.fulfill({ json: data });
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", dayStart: cur.dayStart }, fx: cur.fx });
+ if (url.pathname === "/api/settings") {
+ if (req.method() === "POST") { cur = { ...cur, ...req.postDataJSON() }; saved.push(req.postDataJSON()); }
+ return json(cur);
+ }
+ if (url.pathname === "/api/usage") return json(usage);
+ if (url.pathname === "/api/usage/quotas") return json([]);
+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
+ if (url.pathname.startsWith("/api/")) return json({});
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ await route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": the day starts at the hour picked", async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
+ await t.test(lang, async () => {
+ const errors = [], saved = [];
+ const context = await browser.newContext({ viewport: { width: 900, height: 480 }, reducedMotion: "reduce" });
+ const page = await context.newPage();
+ page.setDefaultTimeout(5000);
+ page.setDefaultNavigationTimeout(60000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server(lang, saved));
+
+ await page.goto("http://magpie.test/?view=usage");
+ await page.locator("#usageCost b").waitFor();
+ await page.locator("#prefs").click();
+ await openPart(page, "usage");
+ const segs = page.locator("#dayStartSegs .opt");
+ await segs.first().waitFor();
+ assert.equal(await segs.count(), 7);
+ assert.equal((await segs.nth(4).textContent()).trim(), "4:00");
+ assert.equal(await segs.nth(0).evaluate((b) => b.classList.contains("on")), true, "0:00 starts picked");
+
+ // a real wheel down, then back until the row is clear of the header
+ await page.locator("#dayStartSegs").hover();
+ for (let i = 0; i < 20 && !(await view(page)); i++) { await page.mouse.wheel(0, 200); await page.waitForTimeout(20); }
+ for (let i = 0; i < 40; i++) {
+ const box = await segs.nth(4).boundingBox();
+ if (box && box.y >= 60) break;
+ await page.mouse.wheel(0, -60);
+ await page.waitForTimeout(30);
+ }
+ const before = await view(page);
+ const box = await segs.nth(4).boundingBox();
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await page.locator("#dayStartSegs .opt.on", { hasText: "4:00" }).waitFor();
+ await page.waitForTimeout(400);
+ assert.equal(await view(page), before, "picking an hour must not scroll the settings page");
+ assert.equal(saved.at(-1).dayStart, 4, "the pick is saved");
+
+ await page.reload();
+ await page.locator("#prefs").click();
+ await openPart(page, "usage");
+ await segs.first().waitFor();
+ assert.equal(await page.locator("#dayStartSegs .opt", { hasText: "4:00" }).evaluate((b) => b.classList.contains("on")), true);
+ assert.deepEqual(errors, []);
+ });
+ }
+ });
+}
diff --git a/internal/provider/key_spend.go b/internal/provider/key_spend.go
index 7b41f7611..d24d25dec 100644
--- a/internal/provider/key_spend.go
+++ b/internal/provider/key_spend.go
@@ -18,6 +18,8 @@ package provider
import (
"fmt"
+ "github.com/yetone/magpie/internal/dayzone"
+ "github.com/yetone/magpie/internal/settings"
"math"
"strconv"
"strings"
@@ -48,8 +50,17 @@ const MaxSpendCap = 1_000_000
// Window is the period c counts over at now: when it began and when the
// next begins, zero for a cap in all, which never renews.
func (c SpendCap) Window(now time.Time) (start, reset time.Time) {
+ // a day that starts after midnight (settings.DayStart) moves the day
+ // and the month with it
+ home := now.Location()
+ loc := dayzone.Shift(home, settings.Shared().DayStart)
+ now = now.In(loc)
y, m, d := now.Date()
- loc := now.Location()
+ defer func() {
+ if c.Period != SpendTotal {
+ start, reset = start.In(home), reset.In(home)
+ }
+ }()
switch c.Period {
case SpendMonth:
return time.Date(y, m, 1, 0, 0, 0, 0, loc), time.Date(y, m+1, 1, 0, 0, 0, 0, loc)
diff --git a/internal/provider/key_spend_test.go b/internal/provider/key_spend_test.go
index 1b9c30a18..3e8ee09cc 100644
--- a/internal/provider/key_spend_test.go
+++ b/internal/provider/key_spend_test.go
@@ -4,6 +4,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/settings"
)
// A key's spend cap (sparkling_lemur_62868 on Discord) is set by the key's
@@ -132,3 +134,31 @@ func TestParseSpendCap(t *testing.T) {
}
}
}
+
+// A day that starts at 4 moves a spend cap's day and month: at 02:00 on the
+// 15th the cap's day began at 04:00 on the 14th.
+func TestSpendCapWindowFollowsTheDayStart(t *testing.T) {
+ t.Cleanup(func() { s := settings.Load(); s.DayStart = 0; settings.Save(s) })
+ loc := time.FixedZone("X", 8*3600)
+ at := func(m time.Month, d, h int) time.Time { return time.Date(2026, m, d, h, 0, 0, 0, loc) }
+ for hour, want := range map[int][2]time.Time{0: {at(9, 15, 0), at(9, 16, 0)}, 4: {at(9, 14, 4), at(9, 15, 4)}} {
+ s := settings.Load()
+ s.DayStart = hour
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+ from, to := SpendCap{USD: 1, Period: SpendDay}.Window(at(9, 15, 2))
+ if !from.Equal(want[0]) || !to.Equal(want[1]) || from.Location() != loc {
+ t.Errorf("start %d: day window %v..%v, want %v..%v", hour, from, to, want[0], want[1])
+ }
+ }
+ st := settings.Load()
+ st.DayStart = 4
+ if err := settings.Save(st); err != nil {
+ t.Fatal(err)
+ }
+ from, to := SpendCap{USD: 1, Period: SpendMonth}.Window(at(10, 1, 2))
+ if !from.Equal(at(9, 1, 4)) || !to.Equal(at(10, 1, 4)) {
+ t.Errorf("month window %v..%v, want September from 04:00", from, to)
+ }
+}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 59cce98f2..9d23f4637 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -96,6 +96,11 @@ type Settings struct {
// westernUnits, which asked for K/M/B: what that chose is now the
// default, so an old file's is left unread.
ChineseUnits bool `json:"chineseUnits,omitempty"`
+ // DayStart is the hour a day starts at in usage: 0 is midnight, and 1 to
+ // 6 count the small hours before it with the day before (ssharpcc on X,
+ // who codes past 1am). The Usage page, its daily cards and the gateway
+ // keys' daily and calendar caps cut their days there.
+ DayStart int `json:"dayStart,omitempty"`
// Dock keeps magpie in the Mac's Dock as well as the menu bar, for a
// menu bar too full to show its icon.
Dock bool `json:"dock,omitempty"`
@@ -2441,6 +2446,9 @@ func saveOwn(s Settings, recording, reads bool) error {
if s.BusyLoad < 0 || s.BusyLoad >= BusyLoadMost {
return fmt.Errorf("busy models go last over a load from 1 to %d%%, or 0 for off, not %d", BusyLoadMost-1, s.BusyLoad)
}
+ if s.DayStart < 0 || s.DayStart > 6 {
+ return fmt.Errorf("a day starts at an hour from 0 to 6, not %d", s.DayStart)
+ }
if s.UsageAlert < 0 || s.UsageAlert > 100 {
return fmt.Errorf("a usage alert is at a percentage from 1 to 100, or 0 for off, not %d", s.UsageAlert)
}
diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go
index 1dcc594ec..6f48a8dc6 100644
--- a/internal/settingsapi/settingsapi.go
+++ b/internal/settingsapi/settingsapi.go
@@ -35,7 +35,7 @@ var Keys = []string{
// the menu bar's allowance cards
"trayUsages", "trayUsage", "trayUsageEvery", "trayNoLogos", "trayNoBird", "trayNoNumber", "trayPace", "trayNoCost", "trayWindows",
// usage and alerts
- "currency", "chineseUnits", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert",
+ "currency", "chineseUnits", "dayStart", "usageAlert", "balanceAlert", "resetReminder", "turnDoneAlert", "maskAlert",
// network
"proxy", "pluginProxy", "updateProxy",
// privacy
@@ -66,6 +66,7 @@ var Choices = map[string][]string{
"codexWarmup": {"off", "week", "all"},
"claudeWarmup": {"off", "week", "all"},
"trayUsageEvery": ints(settings.TrayEvery),
+ "dayStart": {"0", "1", "2", "3", "4", "5", "6"},
"updateChannel": {settings.UpdateStable},
"updateEvery": ints(settings.UpdateEveries),
"searchFirst": {settings.SearchFirstModel, settings.SearchFirstAPI},
diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go
index 0429662cb..2b8a9fc68 100644
--- a/internal/usage/codex_identity.go
+++ b/internal/usage/codex_identity.go
@@ -627,7 +627,7 @@ func namedModelEffort(in map[string][]sessions.ModelEffort, alias func(string) s
func keptCodexModelEffort(p Period) map[string][]sessions.ModelEffort {
if LogCalls != nil { // synthetic logs carry no state to key on
- return codexModelEffort(codexEffortRows(p, Clock(), LogCalls))
+ return codexModelEffort(codexEffortRows(p, localNow(), LogCalls))
}
derivedUsed() // the kept answers go with the chunks' caches when idle
codexEffort.Lock()
@@ -639,7 +639,7 @@ func keptCodexModelEffort(p Period) map[string][]sessions.ModelEffort {
return value // read before the state is: that is most of an unchanged ask's cost
}
codexEffort.Unlock()
- now := Clock()
+ now := localNow()
st := readRequestState(now)
codexEffort.Lock()
e := codexEffort.periods[p]
diff --git a/internal/usage/daystart_test.go b/internal/usage/daystart_test.go
new file mode 100644
index 000000000..e795e1869
--- /dev/null
+++ b/internal/usage/daystart_test.go
@@ -0,0 +1,108 @@
+package usage
+
+import (
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+func startAt(t *testing.T, hour int) {
+ t.Helper()
+ s := settings.Load()
+ s.DayStart = hour
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// With a day that starts at 4 (ssharpcc on X, coding past 1am), a call at
+// 01:30 is the day before's: not in Today, on the day before in the week's
+// chart, the heatmap and a picked day, while one at 04:30 is today's, at
+// hour 04. Without it, both are today's. Every clock is held, in a zone
+// whatever this computer keeps; run under TZ=UTC and TZ=Pacific/Kiritimati.
+func TestDayStartsAfterMidnight(t *testing.T) {
+ pageHome(t)
+ loc, err := time.LoadLocation("Asia/Shanghai")
+ if err != nil {
+ t.Skip(err)
+ }
+ late := time.Date(2026, 9, 30, 1, 30, 0, 0, loc)
+ early := time.Date(2026, 9, 30, 4, 30, 0, 0, loc)
+ now := time.Date(2026, 9, 30, 5, 0, 0, 0, loc)
+ holdClock(t, late)
+ Append(Record{Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
+ holdClock(t, early)
+ Append(Record{Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
+ holdClock(t, now)
+
+ run := func(hour int) {
+ startAt(t, hour)
+ v := Zone("Asia/Shanghai")
+ f := Filter{Zone: v}
+ wantToday := 2
+ if hour == 4 {
+ wantToday = 1
+ }
+ if got := SummarizeTopIn(Today, 10, v).Calls; got != wantToday {
+ t.Errorf("start %d: Summary Today has %d calls, want %d", hour, got, wantToday)
+ }
+ if got := QueryPage(Today, f, 0, 10).Total; got != wantToday {
+ t.Errorf("start %d: Requests Today has %d, want %d", hour, got, wantToday)
+ }
+ if got := len(LedgerOf(Today, f).Rows); got != wantToday {
+ t.Errorf("start %d: ledger Today has %d rows, want %d", hour, got, wantToday)
+ }
+ days := map[string]int{}
+ for _, d := range HeatmapOf(f).Days {
+ days[d.Date] = d.Calls
+ }
+ wantDays := map[string]int{"2026-09-30": 2}
+ if hour == 4 {
+ wantDays = map[string]int{"2026-09-29": 1, "2026-09-30": 1}
+ }
+ if len(days) != len(wantDays) || days["2026-09-29"] != wantDays["2026-09-29"] || days["2026-09-30"] != wantDays["2026-09-30"] {
+ t.Errorf("start %d: heatmap days %v, want %v", hour, days, wantDays)
+ }
+ for date, want := range wantDays {
+ if got := QueryPage(All, Filter{Zone: v, Day: date}, 0, 10).Total; got != want {
+ t.Errorf("start %d: day %s has %d calls, want %d", hour, date, got, want)
+ }
+ }
+ w := SummarizeTopIn(Week, 10, v)
+ byLabel := map[string]int{}
+ for _, p := range w.Series {
+ if p.Calls > 0 {
+ byLabel[p.Label] = p.Calls
+ }
+ }
+ wantWeek := map[string]int{"Sep 30": 2}
+ if hour == 4 {
+ wantWeek = map[string]int{"Sep 29": 1, "Sep 30": 1}
+ }
+ if len(byLabel) != len(wantWeek) || byLabel["Sep 29"] != wantWeek["Sep 29"] || byLabel["Sep 30"] != wantWeek["Sep 30"] {
+ t.Errorf("start %d: the week's chart has %v, want %v", hour, byLabel, wantWeek)
+ }
+ // Today's chart is a point an hour, labelled by the real hour of the day
+ var hours []string
+ for _, p := range w.Series {
+ _ = p
+ }
+ for _, p := range SummarizeTopIn(Today, 10, v).Series {
+ if p.Calls > 0 {
+ hours = append(hours, p.Label)
+ }
+ }
+ if hour == 4 && (len(hours) != 1 || hours[0] != "04") {
+ t.Errorf("start 4: Today's chart hours %v, want [04]", hours)
+ }
+ if hour == 4 {
+ if first := SummarizeTopIn(Today, 10, v).Series[0].Label; first != "04" {
+ t.Errorf("start 4: Today's chart begins at %q, want 04", first)
+ }
+ }
+ }
+ run(0)
+ run(4)
+ run(0)
+}
diff --git a/internal/usage/direct.go b/internal/usage/direct.go
index 5cb6e82bc..9a8c452d9 100644
--- a/internal/usage/direct.go
+++ b/internal/usage/direct.go
@@ -16,7 +16,7 @@ import (
// their own (Kumo31 on Discord: Codex used outside magpie was on the
// window's Usage tab but not in magpie usage).
func Direct(p Period) Summary {
- now := Clock()
+ now := localNow()
return direct(p, now, directRows(p, now))
}
@@ -28,7 +28,7 @@ func Direct(p Period) Summary {
// few, and the summary of a long history is then kept rather than worked
// out again.
func Summaries(p Period) (Summary, Summary) {
- now := Clock()
+ now := localNow()
return topSummary(p, now, summaryCacheSessions), direct(p, now, directRows(p, now))
}
diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go
index 0be0f6d7b..b3f592559 100644
--- a/internal/usage/ledger.go
+++ b/internal/usage/ledger.go
@@ -6,6 +6,7 @@ package usage
import (
"encoding/csv"
+ "github.com/yetone/magpie/internal/dayzone"
"io"
"slices"
"sort"
@@ -771,7 +772,7 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
bucket = "hour"
for h := 0; h <= int(d.Hours()); h++ {
t := since.Add(time.Duration(h) * time.Hour)
- pts = append(pts, Point{Label: t.Format("15"), Time: t})
+ pts = append(pts, Point{Label: hourLabel(t), Time: t})
}
} else {
n = int(d.Hours())/24 + 1
@@ -837,7 +838,7 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
}
for h := 0; since.Add(time.Duration(h) * time.Hour).Before(end); h++ {
t := since.Add(time.Duration(h) * time.Hour)
- pts = append(pts, Point{Label: t.Format("15"), Time: t})
+ pts = append(pts, Point{Label: hourLabel(t), Time: t})
}
case "day":
for i := 0; i < n; i++ {
@@ -1232,7 +1233,7 @@ const seriesKeep = 24
// hour, day or week, for the chart over them. A row is of the point its
// time falls in; the rows are in any order.
func LedgerSeries(p Period, rows []Row) (bucket string, pts []SeriesPoint) {
- return ledgerSeriesAt(p, rows, Clock())
+ return ledgerSeriesAt(p, rows, localNow())
}
// ledgerSeriesAt is LedgerSeries with the period read at now, the moment the
@@ -1314,3 +1315,9 @@ func NewCoster() func(Record) (float64, bool) {
return t.Cost, t.Unpriced == 0
}
}
+
+// hourLabel is the hour of the real day a point stands for: in a zone whose
+// day starts later (dayzone), its clock is that many hours behind.
+func hourLabel(t time.Time) string {
+ return t.Add(dayzone.Offset(t.Location())).Format("15")
+}
diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go
index 0184a53f7..037160ea9 100644
--- a/internal/usage/request_page.go
+++ b/internal/usage/request_page.go
@@ -2357,7 +2357,7 @@ func sharesOf(m map[string]*Share) []Share {
return out
}
func buildRequestPage(p Period, f Filter, offset, limit int, gateway *rowChunk, chunks []*rowChunk) RequestPage {
- return buildRequestBlocks(p, f, offset, limit, Clock(), []*rowChunk{gateway}, chunks, nil, nil)
+ return buildRequestBlocks(p, f, offset, limit, localNow(), []*rowChunk{gateway}, chunks, nil, nil)
}
// Shared days are never matched to this computer's gateway or session calls.
@@ -2765,7 +2765,7 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time,
return out
}
func pageFromLedger(p Period, f Filter, offset, limit int, all Ledgered) RequestPage {
- return pageFromLedgerAt(p, f, offset, limit, all, Clock())
+ return pageFromLedgerAt(p, f, offset, limit, all, localNow())
}
// pageFromLedgerAt is the page of a ledger read at now, its chart over the
diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go
index 3bb2c5a7a..31efe097c 100644
--- a/internal/usage/summary_cache.go
+++ b/internal/usage/summary_cache.go
@@ -54,13 +54,13 @@ func ReadAhead() { SummarizeTopIn(Today, summaryCacheSessions, nil) }
// gives every one, works it out again each time. Over a long history
// (Vantiboo1ean, ~750k requests in ~84k sessions) that was every refresh of
// the Usage page and the TUI, and the page was sent all 84k.
-func SummarizeTop(p Period, n int) Summary { return topSummary(p, Clock(), n) }
+func SummarizeTop(p Period, n int) Summary { return topSummary(p, localNow(), n) }
// SummarizeTopIn is SummarizeTop with the period's days and the chart's
// hours read in zone (Zone gives it), the reader's: the Usage page's.
func SummarizeTopIn(p Period, n int, zone *time.Location) Summary {
if zone == nil {
- zone = time.Local
+ zone = Zone("")
}
return topSummary(p, Clock().In(zone), n)
}
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index dcfd2a905..e2fcd4385 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -1053,7 +1053,7 @@ type Summary struct {
// Summarize caches the four periods over an indexed log snapshot. Callers
// receive their own result slices, without retaining historical Records.
func Summarize(p Period) Summary {
- return indexedSummary(p, Clock())
+ return indexedSummary(p, localNow())
}
func summarize(p Period, now time.Time, recs []Record) Summary {
diff --git a/internal/usage/zone.go b/internal/usage/zone.go
index 7e3197c97..c3a9d88a4 100644
--- a/internal/usage/zone.go
+++ b/internal/usage/zone.go
@@ -3,6 +3,9 @@ package usage
import (
"sync"
"time"
+
+ "github.com/yetone/magpie/internal/dayzone"
+ "github.com/yetone/magpie/internal/settings"
)
// The Usage page buckets its calls by the reader's days and hours, not the
@@ -18,7 +21,15 @@ var zones sync.Map // name → *time.Location, one for each name
// keeps this computer's clock, the page on this computer, is time.Local,
// whose answers the tray and the TUI share. An empty name or one this
// computer doesn't know is time.Local: the computer's days, as before.
+//
+// With a day that starts after midnight (Settings' dayStart, ssharpcc on
+// X), the zone is that zone moved so its midnight is that hour (dayzone):
+// every day and hour the page cuts by it starts there.
func Zone(name string) *time.Location {
+ return dayzone.Shift(zoneNamed(name), settings.Shared().DayStart)
+}
+
+func zoneNamed(name string) *time.Location {
if name == "" || name == "Local" {
return time.Local
}
@@ -58,5 +69,9 @@ func (f Filter) loc() *time.Location {
if f.Zone != nil {
return f.Zone
}
- return time.Local
+ return Zone("")
}
+
+// localNow is now in this computer's days (Zone("")): where nothing names a
+// reader's zone, the TUI, the CLI and the tray.
+func localNow() time.Time { return Clock().In(Zone("")) }