Skip to content

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

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

yetonec888ef272576
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 735d46dde..c6cc10b40 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -116,6 +116,7 @@ recorded as a prediction failure (`noPrediction`).
- A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\<distro>` or `\\wsl.localhost\<distro>` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: <path>` (its `<`/`>` as entities; ` (was <old>)` after a change dropped), Codex's `<environment_context>` `<cwd>`, Pi's `<cwd>` in the system prompt, and OpenCode's `Working directory:` inside its `<env>` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule).
- A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-<name>` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`.
- A pause rule (`Rule.Pause`, `pause=<model>`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause=<model> except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`.
+ - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`.
3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`); otherwise a capped or barred set returns `cappedError` or `barredError`. Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why.
4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap <id> 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap <id> off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap <id> 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`).
5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retries `passing` gives the last one left. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`).
diff --git a/internal/cli/groups_rules_cli.go b/internal/cli/groups_rules_cli.go
index bd70b7ac2..93f30cdf8 100644
--- a/internal/cli/groups_rules_cli.go
+++ b/internal/cli/groups_rules_cli.go
@@ -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
}
diff --git a/internal/cli/groups_rules_cli_test.go b/internal/cli/groups_rules_cli_test.go
index 6ff998551..d4540dfcd 100644
--- a/internal/cli/groups_rules_cli_test.go
+++ b/internal/cli/groups_rules_cli_test.go
@@ -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)
+ }
+}
diff --git a/internal/gateway/rules_time_test.go b/internal/gateway/rules_time_test.go
index 969c5c731..fd11925a0 100644
--- a/internal/gateway/rules_time_test.go
+++ b/internal/gateway/rules_time_test.go
@@ -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())
+ }
+}
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index 641360932..da94a01d3 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -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,
diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js
index d33d40cd4..77184d28b 100644
--- a/internal/gui/assets/plugins/routing/i18n.js
+++ b/internal/gui/assets/plugins/routing/i18n.js
@@ -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}",
diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css
index 2323cf2d1..ab35f4d77 100644
--- a/internal/gui/assets/plugins/routing/routing.css
+++ b/internal/gui/assets/plugins/routing/routing.css
@@ -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; }
diff --git a/internal/gui/groups.go b/internal/gui/groups.go
index 37e0a7f31..0ff7a7b33 100644
--- a/internal/gui/groups.go
+++ b/internal/gui/groups.go
@@ -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
diff --git a/internal/gui/tests/routing-time-zone.test.cjs b/internal/gui/tests/routing-time-zone.test.cjs
new file mode 100644
index 000000000..2f00990d4
--- /dev/null
+++ b/internal/gui/tests/routing-time-zone.test.cjs
@@ -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, []);
+ });
+ }
+}
diff --git a/internal/gui/tests/routing-time.test.cjs b/internal/gui/tests/routing-time.test.cjs
index 6c8249cdf..c6a2a7461 100644
--- a/internal/gui/tests/routing-time.test.cjs
+++ b/internal/gui/tests/routing-time.test.cjs
@@ -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, []);
});
diff --git a/internal/provider/grouprule.go b/internal/provider/grouprule.go
index 9085f8841..406f51a88 100644
--- a/internal/provider/grouprule.go
+++ b/internal/provider/grouprule.go
@@ -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
}
diff --git a/internal/provider/grouprule_zone_test.go b/internal/provider/grouprule_zone_test.go
new file mode 100644
index 000000000..9c066a5b2
--- /dev/null
+++ b/internal/provider/grouprule_zone_test.go
@@ -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)
+ }
+}
diff --git a/internal/provider/ruleparse.go b/internal/provider/ruleparse.go
index 087eb56c8..26838c4c1 100644
--- a/internal/provider/ruleparse.go
+++ b/internal/provider/ruleparse.go
@@ -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 {
diff --git a/internal/tui/routing.go b/internal/tui/routing.go
index cbbaa5986..6907d9212 100644
--- a/internal/tui/routing.go
+++ b/internal/tui/routing.go
@@ -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
}