routing: a rule's hours are kept in the zone they were set in (gaubeebangeel on X)

magpie on a cloud server in UTC read a routing group's rule hours on the
server's clock, so a Beijing user's 09:00-18:00 held at 17:00-02:00
Beijing time, with nothing saying so.

- provider.TimeWindow carries the IANA zone its hours were set in
  ("zone": "Asia/Shanghai", omitempty). Holds reads From, To and Days in
  that zone (time.LoadLocation, cached; Go's embedded tzdata, so Windows
  knows them too). A window with no zone, every one saved before this,
  stays on magpie's own clock (time.Local) as before. A zone magpie
  doesn't know is refused on save (clean); one in a file edited by hand
  makes the window never hold, so the rule is as if absent, never always
  on and never hours off. Text() adds " (Zone)"; Line() writes tz=.
- GUI: changing a rule's hours or days in the editor saves the browser's
  zone (Intl resolvedOptions().timeZone); hours left alone keep theirs.
  /api/groups gives magpie's clock (clock: zone, offset in seconds), and
  when its offset differs from the hours' zone the Routing page tells the
  zone beside them, on the group's rules and in the editor: "Asia/Shanghai
  time" (zh "Asia/Shanghai 时间"), or "server time, UTC+0" (zh "服务器时间
  UTC+0") for hours with no zone. Nothing is added when the clocks agree.
  zh, zh-TW, ja, de.
- CLI and TUI: time=09:00-18:00@Asia/Shanghai or tz=Asia/Shanghai; with
  none, this computer's zone ($TZ, time.Local, the /etc/localtime link)
  when it has an IANA name, otherwise none (magpie's clock). An unknown
  zone is refused with what one looks like; tz= alone needs time= or
  days=. Usage text updated.
- docs/subsystems/gateway-routing.md: the zone rules.

Older magpie reading a shared or synced group ignores zone and reads the
hours on its own clock, as before.

Run in a sandbox HOME with pinned Go caches, first at base 9277c2567,
then again after the rebase onto origin/main d58053720 (vet, builds, the five packages,
routing-time-zone and i18n-keys all ok again there; then rebased onto
11907448e, which changes migrate_side.go and sessions only, and
internal/provider ok again, 139s):
- gofmt -l on the changed files: nothing. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: clean. go build, GOOS=linux
  go build -tags nogui, GOOS=windows go build: ok.
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli
  ./internal/tui ./internal/gui ./internal/gateway: all ok (provider 170s,
  cli 64s, tui 30s, gui 192s, gateway 513s; after the rebase 180s, 62s,
  25s, 181s, 568s); logs kept whole and grepped, no FAIL.
- New tests: TestRuleTimeWindowInItsZone (window, past midnight and days
  in a zone, instants in UTC), TestRuleTimeWindowWithoutZoneIsLocal,
  TestRuleTimeWindowUnknownZone, TestParseRuleTimeZone, TestRuleInZoneHere,
  TestGroupRuleTimeZoneCmd, TestRuleTimeWindowInItsZoneAtTurnStart
  (gateway, ruleClock in UTC). Run under TZ=UTC, TZ=Asia/Shanghai and
  TZ=America/Los_Angeles: ok. The zone used is Asia/Shanghai, or
  America/New_York on a computer on Beijing's clock, so they are red on
  any machine.
- GUI (playwright 1.62.0, chromium and webkit): routing-time-zone (new:
  en, zh, zh-TW, ja, de, 420px wide, browser in Asia/Shanghai, server in
  UTC and in Asia/Shanghai) 14 of 14; routing-time with the browser in
  Asia/Shanghai, the typed rule saved with its zone; routing-time-went,
  routing-day-window, routing-save, routing-rules-line, i18n-keys: ok;
  TestCoreScriptBudget ok.

Broken by hand: Holds reading at.Local() instead of the zone made
TestRuleTimeWindowInItsZone red under TZ=UTC (Shanghai's 10:00 not held,
18:00 held) and under TZ=Asia/Shanghai (with New York), and
TestRuleTimeWindowInItsZoneAtTurnStart red (10:00 Beijing went to the
group's order). routing-time-zone.test.cjs run against origin/main's
client is red (no zone told beside the hours).

Reds not from this change, the same on an untouched origin/main 99de8e1ad
worktree: routing-pause chromium 7 of 7 (#3410); routing-time webkit "Add
a rule" outside the viewport, 1 of 3 runs on main too (#3465);
routing-rules-line webkit zh 1100 once under load, passes alone on both
(#3593, filed now).

Not tried: a real cloud server in UTC with a browser in Beijing (the GUI
test sets the browser's zone and the server's clock instead); the Windows
box; the whole GUI suite.
This commit is contained in:
yetone
2026-10-25 18:18:02 +08:00
parent 11907448e3
commit c888ef2725
14 changed files with 683 additions and 41 deletions
File diff suppressed because one or more lines are too long
+11 -4
View File
@@ -15,7 +15,7 @@ import (
const ruleUsage = `usage:
magpie group rule <group> the group's rules
magpie group rule add <group> use=<model> [use-effort=low|medium|high|xhigh|max] [tokens=<n>] [images] [effort=on|low|medium|high|xhigh|max] [agents=a,b…]
[intent="<what the message asks for>"] [compact] [time=HH:MM-HH:MM] [days=mon-fri]
[intent="<what the message asks for>"] [compact] [time=HH:MM-HH:MM] [days=mon-fri] [tz=<zone>]
[folders=<folder>,…] [except-folders=<folder>,…] [classifier=<model>] [at=<n>]
a rule: a turn that matches it goes to <model>, one of the group's
(or group/<id>, a group in it), first; a model in the group at an
@@ -25,7 +25,7 @@ const ruleUsage = `usage:
use-effort= is the reasoning <model> is asked for on the requests
the rule sends it, whatever the agent asked: at the model's nearest
level, or as the agent asked when its levels aren't known
magpie group rule add <group> pause=<model> [time=HH:MM-HH:MM] [days=mon-fri] [agents=a,b…]
magpie group rule add <group> pause=<model> [time=HH:MM-HH:MM] [days=mon-fri] [tz=<zone>] [agents=a,b…]
[folders=<folder>,…] [except-folders=<folder>,…] [at=<n>]
a pause: while it holds, <model> is left out of the group — sent
nothing, not even when the others fail or a conversation was on it
@@ -54,10 +54,13 @@ const ruleUsage = `usage:
OpenCode's, Pi's, Gemini CLI's, Qwen Code's, Kimi's): a cheaper, faster model can write the
summary. The request is as long as the conversation, so a model known to take less is passed
over; it is not the turn's model, and the requests after it go on as before
time the turn begins within these hours, on this computer's clock (09:00-18:00; 22:00-08:00
runs past midnight) — a provider's peak-price hours sent to another, say
time the turn begins within these hours (09:00-18:00; 22:00-08:00 runs past midnight) — a
provider's peak-price hours sent to another, say
days only on these days (mon-fri, sat,sun); with time, a window past midnight is of the day it
begins on. Days alone hold all day
tz the time zone time and days are in, an IANA name: tz=Asia/Shanghai, or
time=09:00-18:00@Asia/Shanghai. Without it, this computer's zone ($TZ, or the system's),
so magpie on a server in another zone keeps your hours
folders the agent works in one of these folders, or a folder inside one (~/work/acme, ~/oss;
C:\work, which is /mnt/c/work in WSL): a project, or every project under a folder. The
folder is the one the agent tells its model in the request (Claude Code, Codex, OpenCode,
@@ -75,6 +78,7 @@ const ruleUsage = `usage:
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact
magpie group rule add cheap use=glm/glm-5.3 time=14:00-18:00 days=mon-fri
magpie group rule add cheap pause=glm/glm-5.3 time=14:00-18:00 days=mon-fri
magpie group rule add cheap pause=glm/glm-5.3 time=09:00-18:00 days=mon-fri tz=Asia/Shanghai
magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss
magpie group rule add auto-claude-opus-5-5 pause=claude/claude-opus-5-5 except-folders=~/big-task
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash intent="a quick question" classifier=groq/llama-3.1-8b-instant
@@ -90,6 +94,9 @@ func parseRule(g provider.Group, words []string) (provider.Rule, int, string, er
if err != nil && strings.HasPrefix(err.Error(), provider.UnknownRuleWord) {
err = fmt.Errorf("%w\n\n%s", err, ruleUsage)
}
if err == nil {
r.InZoneHere()
}
return r, at, classifier, err
}
+54
View File
@@ -227,3 +227,57 @@ func TestGroupRuleSeveralModelsCmd(t *testing.T) {
t.Fatalf("a rule left with no model kept: %+v", rs)
}
}
// A rule's hours typed with no zone are this computer's ($TZ here), kept
// as its IANA name so a server on another clock reads them as meant; a
// zone typed is kept, and one magpie doesn't know is refused.
func TestGroupRuleTimeZoneCmd(t *testing.T) {
groupsHome(t)
t.Setenv("TZ", "Asia/Shanghai")
if _, err := addGroup("Peak", []string{"models=a/claude-opus-5-5,b/gpt-5.5"}); err != nil {
t.Fatal(err)
}
for _, words := range [][]string{
{"add", "peak", "pause=claude-opus-5-5", "time=09:00-18:00", "days=mon-fri"},
{"add", "peak", "use=gpt-5.5", "time=22:00-08:00@Europe/Berlin"},
{"add", "peak", "use=gpt-5.5", "days=sat", "tz=America/New_York"},
} {
if err := ruleCmd(words); err != nil {
t.Fatalf("%v: %v", words, err)
}
}
g, err := findGroup("peak")
if err != nil {
t.Fatal(err)
}
var zones []string
for _, r := range g.Rules {
zones = append(zones, r.Time.Zone)
}
if got := strings.Join(zones, " "); got != "Asia/Shanghai Europe/Berlin America/New_York" {
t.Fatalf("zones %q", got)
}
if got := g.Rules[0].Line(); got != "pause=a/claude-opus-5-5 time=09:00-18:00 days=mon-fri tz=Asia/Shanghai" {
t.Errorf("line %q", got)
}
for _, words := range [][]string{
{"add", "peak", "use=gpt-5.5", "time=09:00-18:00", "tz=Beijing"},
{"add", "peak", "use=gpt-5.5", "time=09:00-18:00@Asia/Shangai"},
{"add", "peak", "use=gpt-5.5", "tz=Asia/Shanghai"},
} {
if err := ruleCmd(words); err == nil {
t.Errorf("%v: saved", words)
}
}
if g, _ = findGroup("peak"); len(g.Rules) != 3 {
t.Errorf("%d rules after the refused ones", len(g.Rules))
}
// with no zone name to be had, none is kept: magpie's clock, as before
t.Setenv("TZ", "UTC+8")
if err := ruleCmd([]string{"add", "peak", "use=gpt-5.5", "time=01:00-02:00"}); err != nil {
t.Fatal(err)
}
if g, _ = findGroup("peak"); g.Rules[3].Time.Zone != "" {
t.Errorf("zone %q from TZ=UTC+8", g.Rules[3].Time.Zone)
}
}
+52
View File
@@ -62,3 +62,55 @@ func TestRuleTimeWindowAtTurnStart(t *testing.T) {
t.Fatalf("a %d b %d", a.n(), b.n())
}
}
// A rule's hours set in a zone hold at that zone's hours, on a server
// whose clock reads UTC (gaubeebangeel on X: magpie on a cloud server, its
// user in Beijing, the hours 8 off): the instants here are UTC, as such a
// server has them, and the zone is one hours away from this computer's.
func TestRuleTimeWindowInItsZoneAtTurnStart(t *testing.T) {
zone, loc := "", (*time.Location)(nil)
for _, name := range []string{"Asia/Shanghai", "America/New_York"} {
l, err := time.LoadLocation(name)
if err != nil {
t.Fatal(err)
}
_, a := time.Date(2026, 9, 29, 12, 0, 0, 0, l).Zone()
_, b := time.Date(2026, 9, 29, 12, 0, 0, 0, l).In(time.Local).Zone()
if d := a - b; d >= 4*3600 || d <= -4*3600 {
zone, loc = name, l
break
}
}
if loc == nil {
t.Fatal("no zone far from this computer's")
}
now := time.Date(2026, 9, 29, 10, 0, 0, 0, loc).UTC() // Tuesday 10:00 there
ruleClock = func() time.Time { return now }
t.Cleanup(func() { ruleClock = time.Now })
s, a, b := ruled(t, provider.Rule{Use: "b/big", Time: &provider.TimeWindow{From: "09:00", To: "18:00", Days: []string{"mon", "tue", "wed", "thu", "fri"}, Zone: zone}})
post := func(session string) (string, Route) {
t.Helper()
code, out := postAs(t, s, session, chat("hello", nil, 0, ""))
if code != 200 {
t.Fatalf("%d %s", code, out)
}
return out, lastRoute(s)
}
out, r := post("s1")
if !strings.Contains(out, "from kb") || r.Rule == nil || r.Rule.N != 1 || strings.Join(r.Rule.When, " · ") != "time 09:00–18:00 Mon–Fri ("+zone+")" {
t.Fatalf("10:00 in %s: %s %+v", zone, out, r.Rule)
}
// 8:30 there is outside, whatever the server's clock says
now = time.Date(2026, 9, 29, 8, 30, 0, 0, loc).UTC()
if out, r = post("s2"); !strings.Contains(out, "from ka") || r.Rule.N != 0 {
t.Fatalf("08:30 in %s: %s %+v", zone, out, r.Rule)
}
// 17:30 there is inside
now = time.Date(2026, 9, 29, 17, 30, 0, 0, loc).UTC()
if out, r = post("s3"); !strings.Contains(out, "from kb") || r.Rule.N != 1 {
t.Fatalf("17:30 in %s: %s %+v", zone, out, r.Rule)
}
if a.n() != 1 || b.n() != 2 {
t.Fatalf("a %d b %d", a.n(), b.n())
}
}
+50 -11
View File
@@ -946,14 +946,15 @@ function routingPage(part) {
if ((m = /^agent (.+)$/.exec(c))) return m[1].split("|").map(agentName).join(" / ");
if ((m = /^not folder (.+)$/.exec(c))) return t("not in {folders}", { folders: m[1].split("|").join(" / ") });
if ((m = /^folder (.+)$/.exec(c))) return t("in {folders}", { folders: m[1].split("|").join(" / ") });
if ((m = /^time (all day|(\d\d:\d\d)–(\d\d:\d\d))(?: (.+))?$/.exec(c))) {
// the days as the gateway writes them: Mon–Fri, Sat,Sun, Mon,Wed–Fri
if ((m = /^time (all day|(\d\d:\d\d)–(\d\d:\d\d))(?: ([^ (]+))?(?: \(([^)]+)\))?$/.exec(c))) {
// the days as the gateway writes them: Mon–Fri, Sat,Sun, Mon,Wed–Fri;
// the zone the hours are in after them, in brackets, when they have one
const days = [];
for (const part of (m[4] || "").split(",").filter(Boolean)) {
const [a, b] = part.split("–").map((d) => WEEK.indexOf(d.toLowerCase()));
for (let i = a; i >= 0 && i <= (b >= 0 ? b : a); i++) days.push(WEEK[i]);
}
return timeText({ from: m[2] || "00:00", to: m[3] || "00:00", days });
return timeText({ from: m[2] || "00:00", to: m[3] || "00:00", days, zone: m[5] || "" });
}
return c;
}
@@ -976,7 +977,37 @@ function routingPage(part) {
function timeText(w) {
const hours = w.from === w.to ? t("all day") : t("{from}–{to}", { from: w.from, to: w.to });
const days = daysText(w.days);
return days ? t("{hours} {days}", { hours, days }) : hours;
const text = days ? t("{hours} {days}", { hours, days }) : hours;
const zone = zoneNote(w);
return zone ? t("{hours} ({zone})", { hours: text, zone }) : text;
}
// A rule's hours are in the zone they were set in (provider.TimeWindow
// Zone): the browser's, saved with them. magpie on a server in another
// zone (gaubeebangeel on X: a cloud box in UTC, its user in Beijing)
// reads them there, and the zone is told beside them; hours set before
// zones were kept are on the server's clock, told with its offset. When
// the clocks agree nothing is added.
const browserZone = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch { return ""; } };
// zoneOffset is how far zone is ahead of UTC now, in minutes; null when
// this browser doesn't know it
function zoneOffset(zone, at = new Date()) {
try {
const p = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" })
.formatToParts(at).map((x) => [x.type, x.value]));
return Math.round((Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour % 24, +p.minute, +p.second) - Math.floor(at.getTime() / 1000) * 1000) / 60000);
} catch { return null; }
}
const utcText = (min) => "UTC" + (min < 0 ? "−" : "+") + Math.floor(Math.abs(min) / 60) + (Math.abs(min) % 60 ? ":" + String(Math.abs(min) % 60).padStart(2, "0") : "");
function zoneNote(w) {
let clock;
try { clock = groups?.clock; } catch { return ""; } // before the groups are in
if (!clock || typeof clock.offset !== "number") return "";
const server = Math.round(clock.offset / 60);
if (w.zone) {
const off = zoneOffset(w.zone);
return off === server ? "" : t("{zone} time", { zone: w.zone });
}
return -new Date().getTimezoneOffset() === server ? "" : t("server time, {offset}", { offset: utcText(server) });
}
// "9:5" is no time; "9:05" is 09:05
const clockOf = (s) => {
@@ -5753,15 +5784,19 @@ function routingPage(part) {
wrap("exceptFolders", xf);
if (mine === "exceptFolders") focus = () => xi.focus({ preventScroll: true });
}
// hours of the day, on this computer's clock (a vendor's peak
// hours of the day, in the browser's time zone (a vendor's peak
// hours, say): typed as 09:00 and 18:00, past midnight when the
// second comes first; the days are picked like the agents, and
// days alone are all day
// days alone are all day. Hours changed here are in this browser's
// zone, saved with them; hours left alone keep theirs
if (kinds.includes("time")) {
const tm = el("span", "rt-cond tm");
const tw = () => r.time || (r.time = { from: "", to: "", days: [] });
// a change to the hours or days: they are now in this browser's zone
const zoned = () => { const w = tw(), z = browserZone(); if (z) w.zone = z; return w; };
const tFrom = input(r.time?.from || "", "09:00"), tTo = input(r.time?.to || "", "18:00");
tm.title = t("The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say");
tm.title = t("The turn begins within these hours, in your time zone — a provider's peak-price hours sent to another, say");
const zoneTag = el("span", "rt-zone");
tm.onclick = (e) => { if (e.target === tm || e.target.tagName === "SPAN") (tFrom.value ? tTo : tFrom).focus({ preventScroll: true }); };
const dayBtn = el("button", "rt-cond");
const drawTime = () => {
@@ -5771,13 +5806,17 @@ function routingPage(part) {
tm.classList.toggle("bad", [[tFrom, w?.from], [tTo, w?.to]].some(([b, v]) => v && !clockOf(v) && document.activeElement !== b));
dayBtn.textContent = daysText(w?.days) || t("every day");
dayBtn.classList.toggle("on", !!daysText(w?.days));
// the zone the hours are in, when the server's clock is another
zoneTag.textContent = w && (w.from || w.to || w.days?.length) ? zoneNote(w) : "";
zoneTag.hidden = !zoneTag.textContent;
zoneTag.title = zoneTag.textContent;
};
for (const [box, key] of [[tFrom, "from"], [tTo, "to"]]) {
box.className = "clock";
box.maxLength = 5;
box.inputMode = "numeric";
box.oninput = () => { tw()[key] = box.value.trim(); drawTime(); warn(); };
box.onblur = () => { const v = clockOf(box.value); if (v) { box.value = v; tw()[key] = v; } drawTime(); warn(); };
box.oninput = () => { zoned()[key] = box.value.trim(); drawTime(); warn(); };
box.onblur = () => { const v = clockOf(box.value); if (v) { box.value = v; if (tw()[key] !== v) zoned()[key] = v; } drawTime(); warn(); };
box.onkeydown = (e) => e.stopPropagation();
}
tm.append(el("span", "", t("from")), tFrom, el("span", "", t("to")), tTo);
@@ -5786,14 +5825,14 @@ function routingPage(part) {
...presets.map(([v, label, ds]) => ({ value: "=" + v, label: t(label), note: ds.length ? daysText(ds) : t("not a condition") })),
...WEEK.map((d) => ({ value: d, label: t(DAY_NAMES[d]), note: r.time?.days?.includes(d) ? "✓" : "" })),
], (v) => {
const w = tw();
const w = zoned();
if (v.startsWith("=")) w.days = [...presets.find(([id]) => "=" + id === v)[2]];
else w.days = w.days.includes(v) ? w.days.filter((x) => x !== v) : WEEK.filter((x) => x === v || w.days.includes(x));
if (w.days.length === 7) w.days = [];
drawTime(); warn();
});
drawTime();
wrap("time", tm, dayBtn);
wrap("time", tm, dayBtn, zoneTag);
if (mine === "time") focus = () => tFrom.focus({ preventScroll: true });
}
// the quiet + that adds a condition: what the rule doesn't show yet,
+16 -4
View File
@@ -197,7 +197,10 @@ magpie.strings({
"The agent works in {folder}.": "Agent 的工作目录是 {folder}。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Agent 的工作目录是这些文件夹之一或其子文件夹(以它告诉模型的为准:Claude Code、Codex、OpenCode、Pi);不说明工作目录的 Agent 不匹配",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "规则 {n}:文件夹需是完整路径,如 ~/work 或 /Users/me/work",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "本轮在此时段内(按本机时间)开始时生效,例如把某家高峰计价时段的请求转给另一家",
"The turn begins within these hours, in your time zone — a provider's peak-price hours sent to another, say": "本轮在此时段内(按你的时区)开始时生效,例如把某家高峰计价时段的请求转给另一家",
"{hours} ({zone})": "{hours}({zone})",
"{zone} time": "{zone} 时间",
"server time, {offset}": "服务器时间 {offset}",
"weekends": "周末",
"{from}–{to}": "{from}–{to}",
"{hours} {days}": "{days} {hours}",
@@ -756,7 +759,10 @@ magpie.strings({
"The agent works in {folder}.": "Agent 的工作目錄是 {folder}。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Agent 的工作目錄是這些資料夾之一或其子資料夾(以它告訴模型的為準:Claude Code、Codex、OpenCode、Pi);不說明工作目錄的 Agent 不符合",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "規則 {n}:資料夾需是完整路徑,如 ~/work 或 /Users/me/work",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "本輪在此時段內(按本機時間)開始時生效,例如把某家高峰計價時段的請求轉給另一家",
"The turn begins within these hours, in your time zone — a provider's peak-price hours sent to another, say": "本輪在此時段內(按你的時區)開始時生效,例如把某家高峰計價時段的請求轉給另一家",
"{hours} ({zone})": "{hours}({zone})",
"{zone} time": "{zone} 時間",
"server time, {offset}": "伺服器時間 {offset}",
"weekends": "週末",
"{from}–{to}": "{from}–{to}",
"{hours} {days}": "{days} {hours}",
@@ -1313,7 +1319,10 @@ magpie.strings({
"The agent works in {folder}.": "エージェントの作業フォルダは {folder} です。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "エージェントがモデルに伝える作業フォルダ(Claude Code、Codex、OpenCode、Pi)がこれらのフォルダかその中にあるとき。伝えないエージェントは一致しません",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "ルール {n}:フォルダは ~/work や /Users/me/work のような完全なパスで指定してください",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "ターンがこの時間帯(このコンピューターの時刻)に始まったとき — たとえば、あるプロバイダのピーク料金の時間帯を別のプロバイダへ送るなど",
"The turn begins within these hours, in your time zone — a provider's peak-price hours sent to another, say": "ターンがこの時間帯(あなたのタイムゾーン)に始まったとき — たとえば、あるプロバイダのピーク料金の時間帯を別のプロバイダへ送るなど",
"{hours} ({zone})": "{hours}({zone})",
"{zone} time": "{zone} 時間",
"server time, {offset}": "サーバー時刻 {offset}",
"weekends": "週末",
"{from}–{to}": "{from}–{to}",
"{hours} {days}": "{days} {hours}",
@@ -1872,7 +1881,10 @@ magpie.strings({
"The agent works in {folder}.": "Der Agent arbeitet in {folder}.",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Der Agent arbeitet in einem dieser Ordner oder einem Ordner darin, wie er es dem Modell sagt (Claude Code, Codex, OpenCode, Pi); ein Agent, der es nicht sagt, passt nicht",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "Regel {n}: Ein Ordner ist ein ganzer Pfad, etwa ~/work oder /Users/me/work",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "Die Runde beginnt in diesen Stunden, nach der Uhr dieses Computers – etwa um die Spitzenpreis-Stunden eines Anbieters an einen anderen zu geben",
"The turn begins within these hours, in your time zone — a provider's peak-price hours sent to another, say": "Die Runde beginnt in diesen Stunden, in deiner Zeitzone – etwa um die Spitzenpreis-Stunden eines Anbieters an einen anderen zu senden",
"{hours} ({zone})": "{hours} ({zone})",
"{zone} time": "{zone}-Zeit",
"server time, {offset}": "Serverzeit, {offset}",
"weekends": "am Wochenende",
"{from}–{to}": "{from}–{to}",
"{hours} {days}": "{hours} {days}",
@@ -742,6 +742,8 @@ button.rt-session { cursor: pointer; }
.rt-cond.tm { cursor: text; }
.rt-cond.tm input.clock, .editor .rt-cond.tm input.clock[type="text"] { width: 5.5ch; text-align: center; }
.rt-cond.tm.bad { border-style: solid; border-color: var(--amber, var(--muted)); }
/* the time zone a rule's hours are in, when the server's clock is another */
.rt-zone { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.rt-cond[hidden] { display: none; }
.rt-classifier { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; }
.rt-classifier[hidden] { display: none; }
+15 -1
View File
@@ -31,6 +31,11 @@ type groupsJSON struct {
// Templates: groups for common needs made of the user's own models,
// which the page adds in a click (provider.Templates)
Templates []provider.Template `json:"templates"`
// Clock: this computer's time zone, which the gateway reads a rule's
// hours on when they name no zone of their own; the page tells a rule's
// zone beside its hours when the two differ (gaubeebangeel on X: magpie
// on a server in UTC, its user in Beijing)
Clock clockJSON `json:"clock"`
// Shared: share's answer, the group as text to paste into another
// magpie (provider.ShareGroup)
Shared string `json:"shared,omitempty"`
@@ -221,8 +226,17 @@ func keyPools(p provider.Provider) []poolJSON {
return out
}
// clockJSON is a computer's time zone: its IANA name when it has one,
// and how far ahead of UTC it is now, in seconds.
type clockJSON struct {
Zone string `json:"zone,omitempty"`
Offset int `json:"offset"`
}
func groupsState() groupsJSON {
out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates()}
_, offset := time.Now().Zone()
out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates(),
Clock: clockJSON{Zone: provider.LocalZone(), Offset: offset}}
for i := range out.Templates {
if out.Templates[i].Group.Members == nil {
out.Templates[i].Group.Members = []string{} // one that can't be made has none
@@ -0,0 +1,157 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A rule's hours are kept in the zone they were set in (gaubeebangeel on
// X: magpie on a cloud server in UTC, its user in Beijing, the hours 8
// off). When magpie's clock (/api/groups' clock) is in another zone than
// the hours, the zone is told beside them: on the group's rules and in the
// editor, the zone's name for hours that have one, the server's offset for
// hours set before zones were kept. Hours changed in the editor take the
// browser's zone and are saved with it; hours left alone keep theirs. When
// the clocks agree nothing is added. At a narrow width, in every language.
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 assets = path.resolve(__dirname, "../assets");
const models = [
{ id: "a/glm", name: "glm", providerName: "A", icon: "generic", context: 200000, ready: true },
{ id: "b/other", name: "other", providerName: "B", icon: "generic", context: 200000, ready: true },
];
const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri"];
const groups = (clock) => ({
models,
groups: [{ id: "main", name: "Main", members: ["a/glm", "b/other"], routing: "order", ready: true,
memberInfo: [{ id: "a/glm", ready: true, context: 200000 }, { id: "b/other", ready: true, context: 200000 }],
rules: [
{ use: "b/other", time: { from: "09:00", to: "18:00", days: WEEKDAYS, zone: "Asia/Shanghai" } },
{ use: "b/other", time: { from: "22:00", to: "08:00" } },
] }],
pools: [],
clock,
});
const UTC = { zone: "Etc/UTC", offset: 0 };
const BEIJING = { zone: "Asia/Shanghai", offset: 8 * 3600 };
// what each language says: the zone's name, the server's offset, and the
// first rule's hours on the group (no zone added when the clocks agree)
const words = {
en: { zone: "Asia/Shanghai time", server: "server time, UTC+0", rule1: "1. 09:00–18:00 Mon–Fri (Asia/Shanghai time) →", rule2: "2. 22:00–08:00 (server time, UTC+0) →", plain1: "1. 09:00–18:00 Mon–Fri →", edit: "Edit", save: "Save" },
zh: { zone: "Asia/Shanghai 时间", server: "服务器时间 UTC+0", rule1: "1. 周一–周五 09:00–18:00(Asia/Shanghai 时间) →", rule2: "2. 22:00–08:00(服务器时间 UTC+0) →", plain1: "1. 周一–周五 09:00–18:00 →", edit: "编辑", save: "保存" },
"zh-TW": { zone: "Asia/Shanghai 時間", server: "伺服器時間 UTC+0" },
ja: { zone: "Asia/Shanghai 時間", server: "サーバー時刻 UTC+0" },
de: { zone: "Asia/Shanghai-Zeit", server: "Serverzeit, UTC+0" },
};
function serve(lang, clock, posts) {
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json(groups(clock));
if (url.pathname.startsWith("/api/groups/")) {
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
return json(groups(clock));
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
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 r.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(t, engine, lang, clock, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 1200 }, timezoneId: "Asia/Shanghai" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, clock, posts));
await page.goto("http://magpie.test/?view=routing");
const group = page.locator(".rt-group").first();
await group.waitFor();
const titles = () => group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n"));
return { page, group, errors, posts, titles };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: a rule's hours on a server in another zone`, async (t) => {
const { page, group, errors, posts, titles } = await open(t, engine, lang, UTC, 420);
// the group's rules: the zone each one's hours are in
await page.waitForFunction(() => document.querySelector(".rt-group [title]"));
const said = await titles();
assert(said.includes(w.rule1), `the first rule's zone is told: ${said}`);
assert(said.includes(w.rule2), `the second rule's hours are the server's: ${said}`);
// the editor: beside each rule's hours, in its row
await group.locator("button", { hasText: w.edit }).click();
const rows = page.locator(".rt-gedit .rt-rule");
await rows.nth(1).waitFor();
const tag = (i) => rows.nth(i).locator(".rt-zone");
assert.equal(await tag(0).textContent(), w.zone);
assert.equal(await tag(1).textContent(), w.server);
for (const i of [0, 1]) {
assert.equal(await tag(i).isVisible(), true);
const [z, row] = [await tag(i).boundingBox(), await rows.nth(i).boundingBox()];
assert(z.x >= row.x - 1 && z.x + z.width <= row.x + row.width + 1, `the zone stays in its row at 420px: ${JSON.stringify([z, row])}`);
}
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no page scrolls sideways");
// the second rule's hours changed here: now in this browser's zone
const from2 = rows.nth(1).locator(".rt-cond.tm input").first();
await from2.fill("23:00");
await from2.blur();
assert.equal(await tag(1).textContent(), w.zone);
const saveBtn = page.locator(".rt-gedit button.primary", { hasText: w.save });
await saveBtn.evaluate((b) => b.click()); // past the fold at this width; the click is not what is tested
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
const save = posts.find((p) => p.path === "/api/groups/save");
assert(save, `saved: ${JSON.stringify(posts)}`);
assert.deepEqual(save.body.rules.map((r) => r.time), [
{ from: "09:00", to: "18:00", days: WEEKDAYS, zone: "Asia/Shanghai" }, // left alone: its own
{ from: "23:00", to: "08:00", days: [], zone: "Asia/Shanghai" }, // changed: this browser's
]);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: nothing added when magpie's clock is the hours' zone`, async (t) => {
const { page, group, errors, titles } = await open(t, engine, lang, BEIJING, 420);
await page.waitForFunction(() => document.querySelector(".rt-group [title]"));
const said = await titles();
assert(said.includes(w.plain1), `the hours alone: ${said}`);
assert(!said.includes("Asia/Shanghai") && !said.includes("UTC"), `no zone told: ${said}`);
await group.locator("button", { hasText: w.edit }).click();
const rows = page.locator(".rt-gedit .rt-rule");
await rows.nth(1).waitFor();
for (const i of [0, 1]) assert.equal(await rows.nth(i).locator(".rt-zone").isVisible(), false);
assert.deepEqual(errors, []);
});
}
// the other languages: the words beside the hours
for (const lang of ["zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: the zone in its words`, async (t) => {
const { page, errors, titles } = await open(t, engine, lang, UTC, 420);
await page.waitForFunction(() => document.querySelector(".rt-group [title]"));
const said = await titles();
assert(said.includes(words[lang].zone), `${lang}: ${said}`);
assert(said.includes(words[lang].server), `${lang}: ${said}`);
assert.deepEqual(errors, []);
});
}
}
+4 -3
View File
@@ -5,7 +5,8 @@
// tells the rule that matched by them; in the editor the hours are two
// times typed into one pill, past midnight noted, the days picked like the
// agents, a time that isn't one marked, nothing moved by a click, and they
// are saved as time:{from,to,days}. In English and Chinese.
// are saved as time:{from,to,days}, with the browser's zone when typed.
// In English and Chinese.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -75,7 +76,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
test(`${engine} ${lang}: a rule for hours of the day`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 } })).newPage();
const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, timezoneId: "Asia/Shanghai" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
@@ -174,7 +175,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert(save, `saved: ${JSON.stringify(posts)}`);
assert.deepEqual(save.body.rules.map((r) => [r.use, r.time]), [
["b/other", { from: "22:00", to: "08:00", days: WEEKDAYS }],
["b/other", { from: "09:00", to: "18:00", days: [...WEEKDAYS, "sat"] }],
["b/other", { from: "09:00", to: "18:00", days: [...WEEKDAYS, "sat"], zone: "Asia/Shanghai" }], // typed here: in this browser's zone
]);
assert.deepEqual(errors, []);
});
+86 -11
View File
@@ -5,7 +5,8 @@ package provider
// image, how hard the agent asked the model to think, which agent sent it.
// Those are never guessed: the same request is always routed the same way,
// and the trace tells which rule did it. A rule may also hold only at some
// hours of the day (a vendor's peak-price hours, say), on magpie's clock. The one exception is a rule with
// hours of the day (a vendor's peak-price hours, say), in the time zone
// they were set in (magpie's clock when they name none). The one exception is a rule with
// an intent (what the user asks for, in the user's words): as a turn
// begins, a model the group names (its Classifier) is asked which of the
// intents the user's message is, once, and the trace tells what it said.
@@ -28,9 +29,11 @@ package provider
import (
"fmt"
"os"
"slices"
"strconv"
"strings"
"sync"
"time"
)
@@ -77,8 +80,9 @@ type Rule struct {
// Codex's, OpenCode's, Pi's…) — which a cheaper, faster model can do
// in place of the one the conversation is on.
Compact bool `json:"compact,omitempty"`
// Time: the turn begins within these hours of the day, local time — a
// vendor's peak-price hours sent to another, say.
// Time: the turn begins within these hours of the day, in the window's
// zone (TimeWindow.Zone) — a vendor's peak-price hours sent to another,
// say.
Time *TimeWindow `json:"time,omitempty"`
// Folders: the request's working folder, as the agent states it in
// the request, is one of these or inside one — a project, or every
@@ -152,15 +156,74 @@ func (r Rule) Without(m string) (Rule, bool) {
// Names reports whether the rule sends to m.
func (r Rule) Names(m string) bool { return r.Use == m || slices.Contains(r.More, m) }
// TimeWindow is hours of the day, local time: From until To, "HH:MM" each,
// past midnight when To comes before From (22:00–08:00), the whole day
// when they are the same. Days, when set, are the days it holds on ("mon"
// … "sun"); a window past midnight is of the day it begins on, so Friday's
// TimeWindow is hours of the day: From until To, "HH:MM" each, past
// midnight when To comes before From (22:00–08:00), the whole day when
// they are the same. Days, when set, are the days it holds on ("mon" …
// "sun"); a window past midnight is of the day it begins on, so Friday's
// 22:00–08:00 takes Saturday's early hours too.
type TimeWindow struct {
From string `json:"from"`
To string `json:"to"`
Days []string `json:"days,omitempty"`
// Zone: the IANA time zone the hours and days were set in
// ("Asia/Shanghai"): the browser's on the Routing page, the terminal's
// for magpie group rule. magpie on a server in UTC keeps a Beijing
// user's 09:00–18:00 at Beijing's 09:00 (gaubeebangeel on X). A window
// with none — every one set before zones were kept — is on this
// computer's clock, as it was.
Zone string `json:"zone,omitempty"`
}
// zones are the zones windows were read in, each loaded once: Holds is
// asked on every request a pause rule may hold for.
var zones sync.Map // name → *time.Location
// zoneOf is the window's zone: time.Local when it names none; false when
// it names one this magpie doesn't know.
func zoneOf(name string) (*time.Location, bool) {
if name == "" {
return time.Local, true
}
if l, ok := zones.Load(name); ok {
return l.(*time.Location), true
}
l, err := time.LoadLocation(name)
if err != nil {
return nil, false // not kept: a file's text can be anything
}
zones.Store(name, l)
return l, true
}
// ValidZone reports whether name is a time zone a window can be in: an
// IANA name this magpie knows, or "" for this computer's clock.
func ValidZone(name string) bool {
_, ok := zoneOf(name)
return ok
}
// LocalZone is the IANA name of this computer's time zone, as a window
// set here records it: $TZ when it names one, else what /etc/localtime
// links to (macOS, Linux). "" when neither says (Windows, a TZ of "UTC+8"
// that names no zone): the window is then on the clock of whichever
// computer runs the gateway, as before.
func LocalZone() string {
if tz, ok := os.LookupEnv("TZ"); ok {
tz = strings.TrimPrefix(tz, ":")
if tz != "" && tz != "Local" && ValidZone(tz) {
return tz
}
return ""
}
if n := time.Local.String(); n != "Local" && n != "" && ValidZone(n) {
return n
}
if dst, err := os.Readlink("/etc/localtime"); err == nil {
if _, name, ok := strings.Cut(dst, "zoneinfo/"); ok && name != "" && ValidZone(name) {
return name
}
}
return ""
}
// Weekdays are the days a TimeWindow names, as time.Weekday counts them.
@@ -226,17 +289,25 @@ func (w *TimeWindow) clean() error {
if len(w.Days) == len(dayOrder) {
w.Days = nil
}
w.Zone = strings.TrimSpace(w.Zone)
if !ValidZone(w.Zone) {
return fmt.Errorf("the time zone %q is not one magpie knows: an IANA name such as Asia/Shanghai or America/New_York", w.Zone)
}
return nil
}
// Holds reports whether at is within the window, on the machine's clock.
// Holds reports whether at is within the window, in its zone. A zone
// this magpie doesn't know (a file edited by hand; saving refuses one)
// is an unknown clock, and the window doesn't hold: the rule is as if it
// weren't there, rather than at hours that may be a day's half off.
func (w TimeWindow) Holds(at time.Time) bool {
from, ok1 := clockMinutes(w.From)
to, ok2 := clockMinutes(w.To)
if at.IsZero() || !ok1 || !ok2 {
loc, ok3 := zoneOf(w.Zone)
if at.IsZero() || !ok1 || !ok2 || !ok3 {
return false
}
at = at.Local()
at = at.In(loc)
m, day := at.Hour()*60+at.Minute(), at.Weekday()
switch {
case from == to: // the whole day
@@ -282,7 +353,8 @@ func (w TimeWindow) DaysText() string {
return strings.Join(out, ",")
}
// Text is the window as a rule's conditions show it: "09:00–18:00 Mon–Fri".
// Text is the window as a rule's conditions show it: "09:00–18:00 Mon–Fri",
// its zone after it when it has one: "09:00–18:00 (Asia/Shanghai)".
func (w TimeWindow) Text() string {
s := w.From + "–" + w.To
if w.From == w.To {
@@ -291,6 +363,9 @@ func (w TimeWindow) Text() string {
if d := w.DaysText(); d != "" {
s += " " + d
}
if w.Zone != "" {
s += " (" + w.Zone + ")"
}
return s
}
+192
View File
@@ -0,0 +1,192 @@
package provider
import (
"encoding/json"
"os"
"strings"
"testing"
"time"
)
// farZone is a zone whose clock is hours off this computer's at the week
// the tests use: Asia/Shanghai (gaubeebangeel on X: magpie on a server in
// UTC, its user in Beijing), or America/New_York on a computer that keeps
// Beijing's time, so a window read on the computer's clock is visibly wrong.
func farZone(t *testing.T) (string, *time.Location) {
t.Helper()
for _, name := range []string{"Asia/Shanghai", "America/New_York"} {
loc, err := time.LoadLocation(name)
if err != nil {
t.Fatal(err)
}
at := time.Date(2026, 9, 28, 12, 0, 0, 0, loc)
_, a := at.Zone()
_, b := at.In(time.Local).Zone()
if d := a - b; d >= 4*3600 || d <= -4*3600 {
return name, loc
}
}
t.Fatal("no zone far from this computer's")
return "", nil
}
// A window set in a zone holds at its hours there, whatever the clock of
// the computer magpie runs on: the instant is given in UTC, as a server in
// UTC reads it.
func TestRuleTimeWindowInItsZone(t *testing.T) {
name, loc := farZone(t)
// wall is a time on the zone's own clock, the week of Monday 2026-09-28
// (day 0 is Sunday), as a server in UTC has it
wall := func(day, hour, min int) time.Time { return time.Date(2026, 9, 27+day, hour, min, 0, 0, loc).UTC() }
day := TimeWindow{From: "09:00", To: "18:00", Days: []string{"mon", "tue", "wed", "thu", "fri"}, Zone: name}
night := TimeWindow{From: "22:00", To: "08:00", Days: []string{"fri"}, Zone: name}
monday := TimeWindow{From: "00:00", To: "00:00", Days: []string{"mon"}, Zone: name}
for _, c := range []struct {
w TimeWindow
at time.Time
want bool
}{
{day, wall(2, 10, 0), true}, // Tuesday 10:00 in the zone
{day, wall(2, 9, 0), true}, // as it opens
{day, wall(2, 8, 59), false}, // before: not 8 hours off
{day, wall(2, 18, 0), false}, // as it ends
{day, wall(2, 17, 59), true}, // before it ends
{day, wall(6, 10, 0), false}, // Saturday there
{night, wall(5, 23, 0), true}, // Friday night there
{night, wall(6, 3, 0), true}, // Saturday's early hours: Friday's window
{night, wall(6, 8, 0), false}, // as it ends
{night, wall(5, 3, 0), false}, // Friday's early hours: Thursday's window
{monday, wall(1, 0, 30), true}, // Monday just begun there, Sunday in UTC
{monday, wall(1, 23, 30), true}, // Monday's end there, Tuesday in UTC for New York
{monday, wall(0, 23, 30), false},
{monday, wall(2, 0, 30), false},
} {
if got := c.w.Holds(c.at); got != c.want {
t.Errorf("%s at %s there (%s UTC): %v, want %v", c.w.Text(), c.at.In(loc).Format("Mon 15:04"), c.at.Format("Mon 15:04"), got, c.want)
}
}
// a pause rule set there holds at the same instants
p := Rule{Use: "a/x", Pause: true, Time: &day}
if !p.Pauses("claude", "", wall(2, 10, 0)) || p.Pauses("claude", "", wall(2, 19, 0)) {
t.Errorf("pause in %s: not at its hours", name)
}
}
// A window with no zone — every one saved before zones were kept — is on
// this computer's clock, as it was.
func TestRuleTimeWindowWithoutZoneIsLocal(t *testing.T) {
w := TimeWindow{From: "09:00", To: "18:00", Days: []string{"tue"}}
if !w.Holds(time.Date(2026, 9, 29, 10, 0, 0, 0, time.Local).UTC()) || w.Holds(time.Date(2026, 9, 29, 8, 0, 0, 0, time.Local).UTC()) {
t.Error("a window without a zone is not on the computer's clock")
}
b, _ := json.Marshal(Rule{Use: "a/x", Time: &w})
if strings.Contains(string(b), "zone") {
t.Errorf("no zone written for none: %s", b)
}
}
// A zone magpie doesn't know (a file edited by hand) is an unknown clock:
// the window never holds — neither always nor at hours a day's half off —
// and saving one is refused.
func TestRuleTimeWindowUnknownZone(t *testing.T) {
w := TimeWindow{From: "00:00", To: "00:00", Days: []string{"mon", "tue", "wed", "thu", "fri", "sat"}, Zone: "Mars/Olympus_Mons"}
for d := range 7 {
for h := 0; h < 24; h += 3 {
if at := time.Date(2026, 9, 27+d, h, 0, 0, 0, time.UTC); w.Holds(at) {
t.Fatalf("an unknown zone holds at %s", at)
}
}
}
if _, err := cleanRules([]Rule{{Use: "a/x", Time: &TimeWindow{From: "09:00", To: "18:00", Zone: "Mars/Olympus_Mons"}}}, []string{"a/x"}); err == nil || !strings.Contains(err.Error(), "Mars/Olympus_Mons") {
t.Errorf("an unknown zone saved: %v", err)
}
rs, err := cleanRules([]Rule{{Use: "a/x", Time: &TimeWindow{From: "9:00", To: "18:00", Zone: " Asia/Shanghai "}}}, []string{"a/x"})
if err != nil || rs[0].Time.Zone != "Asia/Shanghai" {
t.Fatalf("%v %+v", err, rs)
}
if got := strings.Join(rs[0].Conditions(), " · "); got != "time 09:00–18:00 (Asia/Shanghai)" {
t.Errorf("conditions %q", got)
}
}
// Typed: tz=, or time=…@zone; read back as tz=. A zone magpie doesn't know
// is refused with what one looks like, and tz= alone names no hours.
func TestParseRuleTimeZone(t *testing.T) {
g := Group{ID: "g", Members: []string{"a/x", "b/y"}}
for _, c := range []struct{ line, want, cond string }{
{"pause=b/y time=09:00-18:00 days=mon-fri tz=Asia/Shanghai", "pause=b/y time=09:00-18:00 days=mon-fri tz=Asia/Shanghai", "time 09:00–18:00 Mon–Fri (Asia/Shanghai)"},
{"use=b/y time=09:00-18:00@Asia/Shanghai", "use=b/y time=09:00-18:00 tz=Asia/Shanghai", "time 09:00–18:00 (Asia/Shanghai)"},
{"use=b/y tz=Europe/Berlin days=sat,sun", "use=b/y days=sat,sun tz=Europe/Berlin", "time all day Sat,Sun (Europe/Berlin)"},
{"use=b/y days=mon time=22:00-08:00@UTC", "use=b/y time=22:00-08:00 days=mon tz=UTC", "time 22:00–08:00 Mon (UTC)"},
} {
r, _, _, err := ParseRule(g, RuleWords(c.line))
if err != nil {
t.Fatalf("%s: %v", c.line, err)
}
rs, err := cleanRules([]Rule{r}, g.Members)
if err != nil {
t.Fatalf("%s: %v", c.line, err)
}
if got := rs[0].Line(); got != c.want {
t.Errorf("%s: line %q, want %q", c.line, got, c.want)
}
if got := strings.Join(rs[0].Conditions(), " · "); got != c.cond {
t.Errorf("%s: %q, want %q", c.line, got, c.cond)
}
again, _, _, err := ParseRule(g, RuleWords(rs[0].Line()))
if err != nil || again.Time == nil || again.Time.Zone != rs[0].Time.Zone {
t.Errorf("%s: read back %v %+v", c.line, err, again.Time)
}
}
for _, c := range []struct{ line, says string }{
{"use=b/y time=09:00-18:00 tz=Beijing", "Beijing"},
{"use=b/y time=09:00-18:00@Asia/Shangai", "Asia/Shangai"},
{"use=b/y time=09:00-18:00 tz=", "IANA"},
{"use=b/y tokens=10 tz=Asia/Shanghai", "time= or days="},
} {
if _, _, _, err := ParseRule(g, RuleWords(c.line)); err == nil || !strings.Contains(err.Error(), c.says) {
t.Errorf("%s: %v, want it to say %q", c.line, err, c.says)
}
}
}
// A window typed with no zone takes this computer's ($TZ, or what
// /etc/localtime links to), and none when that has no IANA name.
func TestRuleInZoneHere(t *testing.T) {
g := Group{ID: "g", Members: []string{"a/x", "b/y"}}
typed := func(line string) string {
r, _, _, err := ParseRule(g, RuleWords(line))
if err != nil {
t.Fatal(err)
}
r.InZoneHere()
if r.Time == nil {
return "-"
}
return r.Time.Zone
}
t.Setenv("TZ", "Asia/Tokyo")
if z := typed("use=b/y time=09:00-18:00"); z != "Asia/Tokyo" {
t.Errorf("TZ=Asia/Tokyo: %q", z)
}
if z := typed("use=b/y time=09:00-18:00 tz=Europe/Berlin"); z != "Europe/Berlin" {
t.Errorf("a zone typed is kept: %q", z)
}
if z := typed("use=b/y tokens=5"); z != "-" {
t.Errorf("no hours, no window: %q", z)
}
t.Setenv("TZ", ":Europe/Paris")
if z := typed("use=b/y days=sat"); z != "Europe/Paris" {
t.Errorf("TZ=:Europe/Paris: %q", z)
}
for _, tz := range []string{"UTC+8", "Local", ""} {
t.Setenv("TZ", tz)
if z := typed("use=b/y time=09:00-18:00"); z != "" {
t.Errorf("TZ=%q names no zone: %q", tz, z)
}
}
os.Unsetenv("TZ") // t.Setenv puts it back
if z := LocalZone(); z != "" && !ValidZone(z) {
t.Errorf("the system's zone %q is not one magpie knows", z)
}
}
+41 -6
View File
@@ -1,7 +1,7 @@
package provider
// A rule as it is typed: use=<model>[,<model>…] use-effort=low tokens=200k images effort=high
// agents=a,b intent="…" compact time=09:00-18:00 days=mon-fri
// agents=a,b intent="…" compact time=09:00-18:00 days=mon-fri tz=Asia/Shanghai
// folders=~/work,"~/My Project" except-folders=~/work/old, or
// pause=<model> time=… days=… agents=… folders=… except-folders=… — by
// magpie group rule and the
@@ -67,19 +67,36 @@ func ParseDays(v string) ([]string, error) {
return out, nil
}
// ParseTimeWindow reads hours of the day: 09:00-18:00, 22:00-08:00.
// ParseTimeWindow reads hours of the day: 09:00-18:00, 22:00-08:00, and
// the time zone they are in after an @: 09:00-18:00@Asia/Shanghai.
func ParseTimeWindow(v string) (*TimeWindow, error) {
from, to, ok := strings.Cut(strings.ReplaceAll(strings.TrimSpace(v), "–", "-"), "-")
hours, zone, _ := strings.Cut(v, "@")
from, to, ok := strings.Cut(strings.ReplaceAll(strings.TrimSpace(hours), "–", "-"), "-")
if !ok {
return nil, fmt.Errorf("time is hours of the day, local time: time=09:00-18:00 (or 22:00-08:00, past midnight), not %q", v)
return nil, fmt.Errorf("time is hours of the day: time=09:00-18:00 (or 22:00-08:00, past midnight; 09:00-18:00@Asia/Shanghai in a time zone), not %q", v)
}
w := &TimeWindow{From: strings.TrimSpace(from), To: strings.TrimSpace(to)}
w := &TimeWindow{From: strings.TrimSpace(from), To: strings.TrimSpace(to), Zone: strings.TrimSpace(zone)}
if err := w.clean(); err != nil {
return nil, err
}
return w, nil
}
// InZoneHere puts a rule's window typed with no time zone in this
// computer's (LocalZone), as magpie group rule and the TUI read it: the
// hours are the ones the person typing them means. It stays without one
// when this computer's zone has no IANA name.
func (r *Rule) InZoneHere() {
if r.Time != nil && r.Time.Zone == "" {
r.Time.Zone = LocalZone()
}
}
// zoneErr is what a time zone magpie doesn't know is answered with.
func zoneErr(v string) error {
return fmt.Errorf("tz: %q is not a time zone magpie knows: an IANA name such as Asia/Shanghai, Europe/Berlin or America/New_York", v)
}
// UnknownRuleWord starts the error for a word ParseRule doesn't know.
const UnknownRuleWord = "unknown "
@@ -87,6 +104,7 @@ const UnknownRuleWord = "unknown "
// group's members. classifier is the group's classifier when one was
// given, at the place asked for (from 1) when one was.
func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err error) {
zone, zoned := "", false // tz=, or time=…@zone
for _, w := range words {
k, v, hasV := strings.Cut(w, "=")
k = strings.ToLower(strings.TrimSpace(k))
@@ -160,10 +178,18 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err
if err != nil {
return r, 0, "", err
}
if w.Zone != "" {
zone, zoned = w.Zone, true
}
if r.Time != nil {
w.Days = r.Time.Days
}
r.Time = w
case "tz", "zone", "timezone", "time-zone":
zone, zoned = strings.TrimSpace(v), true
if zone == "" || !ValidZone(zone) {
return r, 0, "", zoneErr(v)
}
case "days", "day":
days, err := ParseDays(v)
if err != nil {
@@ -202,9 +228,15 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err
}
at = n
default:
return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, use-effort, pause, tokens, images, effort, agents, intent, compact, time, days, folders, except-folders, classifier, at)", w)
return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, use-effort, pause, tokens, images, effort, agents, intent, compact, time, days, tz, folders, except-folders, classifier, at)", w)
}
}
if zoned {
if r.Time == nil {
return r, 0, "", fmt.Errorf("tz= is the time zone of time= or days=: give one of them too")
}
r.Time.Zone = zone
}
if r.Use == "" {
return r, 0, "", fmt.Errorf("use=<model> (or pause=<model>) is missing: one of %s", strings.Join(g.Members, ", "))
}
@@ -320,6 +352,9 @@ func (r Rule) Line() string {
if len(r.Time.Days) > 0 {
out = append(out, "days="+strings.ReplaceAll(strings.ToLower(r.Time.DaysText()), "–", "-"))
}
if r.Time.Zone != "" {
out = append(out, "tz="+r.Time.Zone)
}
}
folders := func(k string, fs []string) {
if len(fs) == 0 {
+2 -1
View File
@@ -295,7 +295,7 @@ func (m *model) openClassifier(g provider.Group) {
// ruleHint is what a rule is typed as.
const ruleHint = `use=<model>, and any of: tokens=200k · images · effort=on|low|medium|high|xhigh|max · agents=codex,claude
intent="a quick question" (the group's classifier=<model> tells it) · compact
time=09:00-18:00 (local; 22:00-08:00 runs past midnight) · days=mon-fri · folders=~/work/acme,~/oss · except-folders=~/old · at=<n> for its place
time=09:00-18:00 (22:00-08:00 runs past midnight) · days=mon-fri · tz=Asia/Shanghai (this computer's zone if none) · folders=~/work/acme,~/oss · except-folders=~/old · at=<n> for its place
use-effort=low|medium|high|xhigh|max: the reasoning the model is asked for, whatever the agent asked
or pause=<model> time=… days=… agents=… folders=… except-folders=…: the model is left out of the group then, not even a fallback`
@@ -327,6 +327,7 @@ func putRule(g *provider.Group, i int, line string) error {
if err != nil {
return err
}
r.InZoneHere()
if classifier != "" {
g.Classifier = classifier
}