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 @@
Currency
+
+
Day starts at
+
+