diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 892376a61..be7b7ea2e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -39,8 +39,8 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). A sealed message (`Message Type: MESSAGE`, not a task) that nobody asked can open is left out instead, an `input_text` note naming its sender in its place (`withoutSealedMessages`, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (`NEW_TASK`, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. - A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Only a ChatGPT account's model can be set (`provider.SetCodexSubagentModel`), as nothing else reads the sealed task. When no ChatGPT account on in magpie serves it now, or a gateway key held to some models may not use it, the subagent goes on the model asked for. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved. - Rules and image inputs are handled here too. - - 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$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. The folder is read from the request only when a rule of the group has 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: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` 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 rule by folder matches it (unknown, never empty). A pause rule can't have folders. 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`, `routing-folder.test.cjs`. - - A pause rule (`Rule.Pause`, `pause=`; 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 and agents 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. `rules_pause_test.go`. + - 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$\` or `\\wsl.localhost\` 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: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` 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). 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 pause rule (`Rule.Pause`, `pause=`; 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= 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`. 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. 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 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 subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. 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. 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`). 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. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. 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 or response protection, 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` (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 for at most `replanRounds` (6) rounds and only while the group's `Patience` lasts, 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. A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. @@ -236,7 +236,7 @@ go test -tags nogui ./internal/gateway -run 'TestSearchMCP' go test -tags nogui ./internal/gateway ./internal/gui . -run 'TestSearchAPIAtItsOwnBaseURL|TestSearchKeyStaysAtItsBaseURL|TestSearchAPIBaseURLFromSettings|TestSearchCLI' go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts|TestRedactRuleEdit' go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag' -go test -tags nogui ./internal/provider ./internal/gateway -run 'TestFolderUnder|TestRuleFoldersCleaned|TestRuleMatchesByFolder|TestParseRuleFolders|TestWorkDir|TestRuleByFolder' +go test -tags nogui ./internal/provider ./internal/gateway -run 'TestFolderUnder|TestRuleFoldersCleaned|TestRuleMatchesByFolder|TestRuleMatchesExceptFolders|TestParseRuleFolders|TestParsePauseByFolder|TestWorkDir|TestRuleByFolder|TestPauseByFolder' go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM' ``` diff --git a/groups_rules_cli.go b/groups_rules_cli.go index eda1bce19..dbd274dfb 100644 --- a/groups_rules_cli.go +++ b/groups_rules_cli.go @@ -16,11 +16,12 @@ const ruleUsage = `usage: magpie group rule the group's rules magpie group rule add use= [tokens=] [images] [effort=on|low|medium|high|xhigh|max] [agents=a,b…] [intent=""] [compact] [time=HH:MM-HH:MM] [days=mon-fri] - [folders=,…] [classifier=] [at=] + [folders=,…] [except-folders=,…] [classifier=] [at=] a rule: a turn that matches it goes to , one of the group's (or group/, a group in it), first; a model in the group at an effort of its own is named with it (use=glm/glm-5.3-flash:high) - magpie group rule add pause= [time=HH:MM-HH:MM] [days=mon-fri] [agents=a,b…] [at=] + magpie group rule add pause= [time=HH:MM-HH:MM] [days=mon-fri] [agents=a,b…] + [folders=,…] [except-folders=,…] [at=] a pause: while it holds, is left out of the group — sent nothing, not even when the others fail or a conversation was on it magpie group rule rm remove rule n @@ -32,7 +33,7 @@ const ruleUsage = `usage: Rules are looked at top first when you send a message (a new turn); the first that matches puts its model first, and the group's others stay behind it if it fails. A pause is looked at on every request and leaves its model out while it holds; its - conditions are time, days and agents only. + conditions are time, days, agents, folders and except-folders only. The agent's tool results within the turn stay with the model the turn began on. Every condition given must hold: tokens the request is at least this long (200000, 200k, 1m): estimated from its size, or @@ -57,6 +58,11 @@ const ruleUsage = `usage: folder is the one the agent tells its model in the request (Claude Code, Codex, OpenCode, Pi); a request that doesn't tell it matches no folder. Quote a folder with a space: folders="~/My Project,~/oss" + except-folders + the agent works in none of these folders, nor a folder inside one. A request that doesn't + tell its folder isn't known to be in one, so it holds for it: pause= + except-folders=~/big-task keeps for the task in ~/big-task — every other request, + a subagent's or a small model's too when it doesn't tell its folder, goes elsewhere e.g. magpie group rule add opus-anywhere use=openrouter/google/gemini-3-pro tokens=200k magpie group rule add opus-anywhere use=a/vision-model images @@ -65,6 +71,7 @@ const ruleUsage = `usage: 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 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` // parseTokens reads 200000, 200k, 1.5m. diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index e283baa65..3420803e3 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -96,7 +96,7 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body return } // a model a pause rule holds for now is out, as for a chat - ms, paused := provider.PausedOut(g, ms, agentOf(r), ruleClock()) + ms, paused := provider.PausedOut(g, ms, agentOf(r), "", ruleClock()) if len(ms) == 0 && len(paused) > 0 { writeError(w, provider.Chat, http.StatusServiceUnavailable, pausedError(asked, paused)) return @@ -244,7 +244,7 @@ func (s *Server) askDecisionGroup(model string, intents []string, prev before, e return verdict{}, false, nil } g = g.Live() - ms, _ = provider.PausedOut(g, ms, RouterAgent, ruleClock()) + ms, _ = provider.PausedOut(g, ms, RouterAgent, "", ruleClock()) cs, _, _ := s.decideTries(g, ms) if len(cs) == 0 { return verdict{}, true, fmt.Errorf("no decision model of the group %s can be asked now", g.Name) diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index d3d076a83..589e1cf88 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -68,7 +68,7 @@ func (s *Server) retrieve(path, operation string) http.HandlerFunc { if isGroup { // a model a pause rule holds for now is left out, as for a chat var paused []provider.Paused - if ms, paused = provider.PausedOut(g.Live(), ms, agentOf(r), ruleClock()); len(ms) == 0 && len(paused) > 0 { + if ms, paused = provider.PausedOut(g.Live(), ms, agentOf(r), "", ruleClock()); len(ms) == 0 && len(paused) > 0 { msg := pausedError(asked, paused) call.Status, call.Error = 503, msg writeError(w, provider.Chat, 503, msg) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8951c7a20..5cd8cde35 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1453,7 +1453,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // model paused in its vendor's peak hours) var paused []provider.Paused if isGroup { - ms, paused = provider.PausedOut(g, ms, agent, ruleClock()) + // a pause by folder (#1606) reads the folder the agent says it + // works in; one that says none is outside every folder + folder := "" + if provider.PausesByFolder(g, ms) { + if req, err := parse(from, body); err == nil { + folder = workDir(req) + } + } + ms, paused = provider.PausedOut(g, ms, agent, folder, ruleClock()) if len(ms) == 0 && len(paused) > 0 { call.Status, call.Error = 503, "every model paused" writeError(w, from, 503, pausedError(call.Model, paused)) diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index 87e7b97ed..f31669d66 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -167,7 +167,7 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a if had && tr.input > q.Tokens { q.Tokens = tr.input // what the vendor counted last, a floor: the conversation only grew since } - if slices.ContainsFunc(g.Rules, func(r provider.Rule) bool { return len(r.Folders) > 0 }) { + if slices.ContainsFunc(g.Rules, provider.Rule.ByFolder) { q.Folder = workDir(req) } hit := &RuleHit{Turn: turn, Tokens: q.Tokens, Images: q.Images, Effort: q.Effort, Folder: q.Folder, Bare: len(g.Rules) == 0} diff --git a/internal/gateway/rules_pause_folder_test.go b/internal/gateway/rules_pause_folder_test.go new file mode 100644 index 000000000..87524c6cc --- /dev/null +++ b/internal/gateway/rules_pause_folder_test.go @@ -0,0 +1,93 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #1606 (Ti800): a subscription's quota kept for the long task in one +// folder. A pause outside that folder leaves the member out of every +// request from elsewhere — another project, or an agent that doesn't say +// its folder — not even as a fallback, while the task's own requests +// still reach it; a pause in some folders leaves it out of theirs only. +func TestPauseByFolder(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fixtures' folders are Unix paths") + } + group := func(body []byte) string { + var m map[string]any + if err := json.Unmarshal(body, &m); err != nil { + t.Fatal(err) + } + m["model"], m["stream"] = "group/r", false + delete(m, "thinking") + delete(m, "reasoning") + b, _ := json.Marshal(m) + return string(b) + } + elsewhere := func(name string) string { + return strings.ReplaceAll(group(fixture(t, name)), "/Users/me/work/proj", "/Users/me/scratch") + } + post := func(s *Server, path, body, session string) (int, string, Route) { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req.Header.Set("x-session-id", session) + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String(), lastRoute(s) + } + keep := provider.Rule{Use: "a/small", Pause: true, ExceptFolders: []string{"/Users/me/work/proj"}} + + // a/small is the subscription, kept for /Users/me/work/proj + s, _, _ := ruled(t, keep) + for _, tc := range []struct { + name, path, body, folder string + paused bool + }{ + {"claude code in the task", "/v1/messages", group(fixture(t, "claude-code-2.1.296.json")), "", false}, + {"codex in the task", "/v1/responses", group(fixture(t, "codex-0.162.0.json")), "", false}, + {"pi in the task", "/v1/chat/completions", group(fixture(t, "pi-1.1.0.json")), "", false}, + {"claude code elsewhere", "/v1/messages", elsewhere("claude-code-2.1.296.json"), "/Users/me/scratch/a&b 中文", true}, + {"codex elsewhere", "/v1/responses", elsewhere("codex-0.162.0.json"), "/Users/me/scratch/a&b 中文", true}, + {"no folder said", "/v1/chat/completions", chat("hi", nil, 0, ""), "", true}, + } { + code, out, r := post(s, tc.path, tc.body, tc.name) + want := map[bool]string{false: "from ka", true: "from kb"}[tc.paused] + if code != 200 || !strings.Contains(out, want) { + t.Errorf("%s: %d %.300s", tc.name, code, out) + continue + } + p := r.Group.Paused + if !tc.paused { + if len(p) != 0 { + t.Errorf("%s: paused %+v", tc.name, p) + } + continue + } + if len(p) != 1 || p[0].Member != "a/small" || !p[0].ByFolder || p[0].Folder != tc.folder || strings.Join(p[0].When, " · ") != "not folder /Users/me/work/proj" { + t.Errorf("%s: paused %+v", tc.name, p) + } + } + + // elsewhere, a/small isn't a fallback either + s, a, b := ruled(t, keep) + b.fail = 500 + if code, _, _ := post(s, "/v1/messages", elsewhere("claude-code-2.1.296.json"), "f"); code == 200 || a.n() != 0 { + t.Errorf("paused member asked as a fallback: %d, a asked %d", code, a.n()) + } + + // a pause in some folders: theirs only, never a request that says none + s, _, _ = ruled(t, provider.Rule{Use: "a/small", Pause: true, Folders: []string{"/Users/me/scratch"}}) + if code, out, _ := post(s, "/v1/messages", elsewhere("claude-code-2.1.296.json"), "g1"); code != 200 || !strings.Contains(out, "from kb") { + t.Errorf("in the paused folder: %d %.300s", code, out) + } + for i, body := range []string{group(fixture(t, "pi-1.1.0.json")), chat("hi", nil, 0, "")} { + if code, out, r := post(s, "/v1/chat/completions", body, "g2"+string(rune('a'+i))); code != 200 || !strings.Contains(out, "from ka") || len(r.Group.Paused) != 0 { + t.Errorf("outside the paused folder %d: %d %.300s", i, code, out) + } + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4dd61bdf9..20a978b9d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3068,7 +3068,11 @@ const I18N = { "goes first; the others stay behind it": "先发给它;其余的在它后面备用", "left out of the group: not tried, not a fallback": "移出分组:不会被调用,也不做备用", "left out of the group then: not tried, not a fallback": "这段时间移出分组:不会被调用,也不做备用", - "Rule {n}: a pause needs hours, days or agents": "第 {n} 条规则:暂停需要设时段、星期或 Agent", + "not in {folders}": "不在 {folders} 中", + "not in folder": "不在文件夹", + "The agent works in none of these folders, nor a folder inside one, as it tells the model; an agent that doesn't say counts as outside them": "Agent 的工作目录不是这些文件夹,也不在它们之中(以它告诉模型的为准);不说明工作目录的 Agent 算在它们之外", + "The agent didn't say which folder it works in.": "Agent 没有说明它的工作目录。", + "Rule {n}: a pause needs hours, days, agents or folders": "第 {n} 条规则:暂停需要设时段、星期、Agent 或文件夹", "{model} is paused by rule {n} ({when}), so it is left out until that ends.": "{model} 被规则 {n}({when})暂停,在此之前不会被调用。", "{model} is paused by rule {n} of {group} ({when}), so it is left out until that ends.": "{model} 被 {group} 的规则 {n}({when})暂停,在此之前不会被调用。", "asks for": "意图是", @@ -7342,7 +7346,11 @@ const I18N = { "goes first; the others stay behind it": "先發給它;其餘的在它後面備用", "left out of the group: not tried, not a fallback": "移出群組:不會被呼叫,也不做備用", "left out of the group then: not tried, not a fallback": "這段時間移出群組:不會被呼叫,也不做備用", - "Rule {n}: a pause needs hours, days or agents": "第 {n} 條規則:暫停需要設時段、星期或 Agent", + "not in {folders}": "不在 {folders} 中", + "not in folder": "不在資料夾", + "The agent works in none of these folders, nor a folder inside one, as it tells the model; an agent that doesn't say counts as outside them": "Agent 的工作目錄不是這些資料夾,也不在它們之中(以它告訴模型的為準);不說明工作目錄的 Agent 算在它們之外", + "The agent didn't say which folder it works in.": "Agent 沒有說明它的工作目錄。", + "Rule {n}: a pause needs hours, days, agents or folders": "第 {n} 條規則:暫停需要設時段、星期、Agent 或資料夾", "{model} is paused by rule {n} ({when}), so it is left out until that ends.": "{model} 被規則 {n}({when})暫停,在此之前不會被呼叫。", "{model} is paused by rule {n} of {group} ({when}), so it is left out until that ends.": "{model} 被 {group} 的規則 {n}({when})暫停,在此之前不會被呼叫。", "asks for": "意圖是", @@ -11633,7 +11641,11 @@ const I18N = { "goes first; the others stay behind it": "最初に送信し、ほかはその後ろで控える", "left out of the group: not tried, not a fallback": "グループから外す:使われず、フォールバックにもならない", "left out of the group then: not tried, not a fallback": "この間はグループから外す:使われず、フォールバックにもならない", - "Rule {n}: a pause needs hours, days or agents": "ルール {n}:一時停止には時間帯、曜日、またはエージェントが必要です", + "not in {folders}": "{folders} 以外", + "not in folder": "除外フォルダ", + "The agent works in none of these folders, nor a folder inside one, as it tells the model; an agent that doesn't say counts as outside them": "エージェントがモデルに伝える作業フォルダが、これらのフォルダでもその中でもないとき。伝えないエージェントはフォルダの外として扱います", + "The agent didn't say which folder it works in.": "エージェントは作業フォルダを伝えていません。", + "Rule {n}: a pause needs hours, days, agents or folders": "ルール {n}:一時停止には時間帯、曜日、エージェント、またはフォルダが必要です", "{model} is paused by rule {n} ({when}), so it is left out until that ends.": "{model} はルール {n}({when})で一時停止中のため、終わるまで使われません。", "{model} is paused by rule {n} of {group} ({when}), so it is left out until that ends.": "{model} は {group} のルール {n}({when})で一時停止中のため、終わるまで使われません。", "asks for": "インテント", @@ -15921,7 +15933,11 @@ const I18N = { "goes first; the others stay behind it": "kommt zuerst; die anderen bleiben dahinter", "left out of the group: not tried, not a fallback": "aus der Gruppe genommen: nicht versucht, kein Ausweichmodell", "left out of the group then: not tried, not a fallback": "in dieser Zeit aus der Gruppe genommen: nicht versucht, kein Ausweichmodell", - "Rule {n}: a pause needs hours, days or agents": "Regel {n}: eine Pause braucht Uhrzeiten, Tage oder Agenten", + "not in {folders}": "nicht in {folders}", + "not in folder": "nicht im Ordner", + "The agent works in none of these folders, nor a folder inside one, as it tells the model; an agent that doesn't say counts as outside them": "Der Agent arbeitet in keinem dieser Ordner und keinem Ordner darin, wie er es dem Modell sagt; ein Agent, der es nicht sagt, zählt als außerhalb", + "The agent didn't say which folder it works in.": "Der Agent hat nicht gesagt, in welchem Ordner er arbeitet.", + "Rule {n}: a pause needs hours, days, agents or folders": "Regel {n}: eine Pause braucht Uhrzeiten, Tage, Agenten oder Ordner", "{model} is paused by rule {n} ({when}), so it is left out until that ends.": "{model} ist durch Regel {n} ({when}) pausiert und wird bis dahin ausgelassen.", "{model} is paused by rule {n} of {group} ({when}), so it is left out until that ends.": "{model} ist durch Regel {n} von {group} ({when}) pausiert und wird bis dahin ausgelassen.", "asks for": "verlangt", diff --git a/internal/gui/assets/routing.css b/internal/gui/assets/routing.css index 9473919b5..34f2e4d03 100644 --- a/internal/gui/assets/routing.css +++ b/internal/gui/assets/routing.css @@ -529,6 +529,8 @@ button.rt-session { cursor: pointer; } .rt-cond.in input, .editor .rt-cond.in input[type="text"] { width: 24ch; } .rt-cond.fd { cursor: text; } .rt-cond.fd input, .editor .rt-cond.fd input[type="text"] { width: 24ch; } +.rt-cond.xf { cursor: text; } +.rt-cond.xf input, .editor .rt-cond.xf input[type="text"] { width: 24ch; } /* a rule's hours: two times in the pill, typed; one that isn't a time is marked */ .rt-cond.tm { cursor: text; } .rt-cond.tm input.clock, .editor .rt-cond.tm input.clock[type="text"] { width: 5.5ch; text-align: center; } diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 12c115c36..a7c1e21a7 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -523,6 +523,8 @@ out.push(p.group ? t("{model} is paused by rule {n} of {group} ({when}), so it is left out until that ends.", { model: p.member, n: p.rule, group: r.group?.subs?.find((s) => s.id === p.group)?.name || p.group, when }) : t("{model} is paused by rule {n} ({when}), so it is left out until that ends.", { model: p.member, n: p.rule, when })); + // a pause by folder (#1606) says the folder it read, or that none was said + if (p.byFolder) out[out.length - 1] += " " + (p.folder ? t("The agent works in {folder}.", { folder: p.folder }) : t("The agent didn't say which folder it works in.")); } const smart = (x) => !x.routing && (x.kind === "account" || x.known); const someKnown = r.order.some((x) => x.known); @@ -680,6 +682,7 @@ if (c === "compacting") return t("compacting"); if ((m = /^effort ≥ (\w+)$/.exec(c))) return t("reasoning ≥ {level}", { level: m[1] }); 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 @@ -3046,6 +3049,7 @@ if (r.compact) bits.push(t("compacting")); if (r.time) bits.push(timeText(r.time)); if (r.folders?.length) bits.push(t("in {folders}", { folders: r.folders.join(" / ") })); + if (r.exceptFolders?.length) bits.push(t("not in {folders}", { folders: r.exceptFolders.join(" / ") })); return bits.join(" · "); } const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); @@ -3069,7 +3073,7 @@ const group = (g) => ({ ...g, id: String(g.id ?? ""), name: typeof g.name === "string" && g.name ? g.name : String(g.id ?? ""), members: ids(g.members), memberInfo: objs(g.memberInfo), holds: ids(g.holds), offers: ids(g.offers), shared: ids(g.shared), patterns: objs(g.patterns), match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids), - rules: opt(g.rules, (rs) => objs(rs).map((r) => ({ ...r, agents: opt(r.agents, ids), folders: opt(r.folders, ids) }))) }); + rules: opt(g.rules, (rs) => objs(rs).map((r) => ({ ...r, agents: opt(r.agents, ids), folders: opt(r.folders, ids), exceptFolders: opt(r.exceptFolders, ids) }))) }); const refs = (v) => objs(v).filter((m) => typeof m.id === "string"); return { ...x, groups: objs(x.groups).filter((g) => typeof g.id === "string" && g.id).map(group), models: refs(x.models), deciders: refs(x.deciders), pools: objs(x.pools), @@ -3154,7 +3158,7 @@ // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -3398,7 +3402,7 @@ if (groupDirty() && !(await confirmDiscard())) return; const g = tp.group; gSel = null; - gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [], time: null })), classifier: g.classifier || "", effort: "", levels: [] } }; + gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [], exceptFolders: [], time: null })), classifier: g.classifier || "", effort: "", levels: [] } }; renderGroups(); const ed = gList.querySelector(".rt-gedit"); ed?.scrollIntoView({ block: "nearest" }); @@ -4273,11 +4277,21 @@ fi.oninput = () => { r.folders = fi.value.split(",").map((x) => x.trim()).filter(Boolean); fd.classList.toggle("on", r.folders.length > 0); }; fi.onkeydown = (e) => e.stopPropagation(); fd.append(el("span", "", t("in folder")), fi); - // a pause holds by hours, days and agents only: the others are - // about a request, and a pause keeps the model out of every one - const byRequest = [tk, im, ef, it, cp, fd]; + // outside folders (#1606, Ti800): a model kept for the task in one + // folder is paused for every other; an agent that doesn't say its + // folder isn't known to be in one, so it counts as outside + const xf = el("span", "rt-cond xf" + (r.exceptFolders?.length ? " on" : "")); + xf.onclick = () => xi.focus(); + const xi = input((r.exceptFolders || []).join(", "), "~/big-task"); + xf.title = t("The agent works in none of these folders, nor a folder inside one, as it tells the model; an agent that doesn't say counts as outside them"); + xi.oninput = () => { r.exceptFolders = xi.value.split(",").map((x) => x.trim()).filter(Boolean); xf.classList.toggle("on", r.exceptFolders.length > 0); }; + xi.onkeydown = (e) => e.stopPropagation(); + xf.append(el("span", "", t("not in folder")), xi); + // a pause holds by hours, days, agents and folders only: the others + // are about a request, and a pause keeps the model out of every one + const byRequest = [tk, im, ef, it, cp]; for (const c of byRequest) c.hidden = !!r.pause; - when.append(tk, im, ef, ag, it, cp, fd, tm, dayBtn); + when.append(tk, im, ef, ag, it, cp, fd, xf, tm, dayBtn); // the member it sends to const use = el("div", "rt-use"); const ub = el("button", "rt-cond on"); @@ -4308,7 +4322,7 @@ ], (v) => { r.pause = v === "pause"; // what a pause doesn't take is cleared, not kept out of sight - if (r.pause) Object.assign(r, { tokens: 0, images: false, effort: "", intent: "", compact: false, folders: [] }); + if (r.pause) Object.assign(r, { tokens: 0, images: false, effort: "", intent: "", compact: false }); drawRules(); }, r.pause ? "pause" : "send"); use.append(act, ub, hint); @@ -4325,7 +4339,7 @@ focusIntent = null; }; let focusIntent = null; - const newRule = () => ({ use: d.members[d.members.length - 1], pause: false, tokens: 0, images: false, effort: "", agents: [], intent: "", compact: false, folders: [], time: null }); + const newRule = () => ({ use: d.members[d.members.length - 1], pause: false, tokens: 0, images: false, effort: "", agents: [], intent: "", compact: false, folders: [], exceptFolders: [], time: null }); rAdd.onclick = () => { d.rules.push(newRule()); drawRules(); }; const addIntentRule = () => { asking = newRule(); @@ -4472,12 +4486,12 @@ : t("Rule {n}: the hours are two times like 09:00 and 18:00", { n: badTime + 1 }), "warn"); } // a folder is a whole path (provider.cleanFolder) - const badDir = d.rules.findIndex((r) => (r.folders || []).some((f) => !/^(~$|~[\\/]|\/|\\\\|[A-Za-z]:([\\/]|$))/.test(f))); + const badDir = d.rules.findIndex((r) => [...(r.folders || []), ...(r.exceptFolders || [])].some((f) => !/^(~$|~[\\/]|\/|\\\\|[A-Za-z]:([\\/]|$))/.test(f))); if (badDir >= 0) return status(t("Rule {n}: a folder is a whole path, like ~/work or /Users/me/work", { n: badDir + 1 }), "warn"); - const bare = d.rules.findIndex((r) => !r.pause && !r.tokens && !r.images && !r.effort && !r.agents.length && !r.intent && !r.compact && !r.time && !r.folders?.length); + const bare = d.rules.findIndex((r) => !r.pause && !r.tokens && !r.images && !r.effort && !r.agents.length && !r.intent && !r.compact && !r.time && !r.folders?.length && !r.exceptFolders?.length); if (bare >= 0) return status(t("Rule {n} needs a condition", { n: bare + 1 }), "warn"); - const bareP = d.rules.findIndex((r) => r.pause && !r.time && !r.agents.length); - if (bareP >= 0) return status(t("Rule {n}: a pause needs hours, days or agents", { n: bareP + 1 }), "warn"); + const bareP = d.rules.findIndex((r) => r.pause && !r.time && !r.agents.length && !r.folders?.length && !r.exceptFolders?.length); + if (bareP >= 0) return status(t("Rule {n}: a pause needs hours, days, agents or folders", { n: bareP + 1 }), "warn"); if (d.rules.some((r) => r.intent) && !d.classifier) return status(t("Choose the model that tells which intent a message is"), "warn"); if (d.effort === "auto" && !d.classifier) return status(t("Choose the model that rates how hard a turn is"), "warn"); if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); diff --git a/internal/gui/tests/routing-pause-folder.test.cjs b/internal/gui/tests/routing-pause-folder.test.cjs new file mode 100644 index 000000000..32249c3a6 --- /dev/null +++ b/internal/gui/tests/routing-pause-folder.test.cjs @@ -0,0 +1,187 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group's pause can hold by the folder the agent works in (#1606, +// Ti800: a subscription's quota kept for the long task in one folder). The +// group's rule reads "not in → pause "; the trace tells the +// model was paused and the folder the agent said, or that it said none; in +// the editor a pause shows the folder conditions (in folder, not in folder) +// and keeps them when it is picked, a folder that isn't a whole path is +// refused, a pause with no condition left is refused, and it is saved as +// pause:true with exceptFolders:[…]. In every language, and at a phone's +// width the conditions stay inside the editor. +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/opus", name: "opus", providerName: "A", icon: "generic", context: 1000000, ready: true }, + { id: "b/opus", name: "opus", providerName: "B", icon: "generic", context: 1000000, ready: true }, +]; +const groups = () => ({ + models, + groups: [{ id: "main", name: "Main", members: ["a/opus", "b/opus"], routing: "order", ready: true, + memberInfo: [{ id: "a/opus", ready: true, context: 1000000 }, { id: "b/opus", ready: true, context: 1000000 }], + rules: [{ use: "a/opus", pause: true, exceptFolders: ["~/big-task"] }] }], + pools: [], +}); +const now = Date.now(); +const routeFrom = (folder) => ({ + id: 7, seq: 7, time: new Date(now - 2000).toISOString(), agent: "claude", model: "main", provider: "b", done: true, status: 200, ms: 900, tokens: 9000, + group: { id: "main", name: "Main", members: ["b/opus"], paused: [{ member: "a/opus", rule: 1, use: "a/opus", when: ["not folder ~/big-task"], byFolder: true, ...(folder ? { folder } : {}) }] }, + order: [{ id: "b", provider: "b", name: "B", kind: "key", model: "opus", known: true }], + tries: [{ id: "b", model: "opus", start: new Date(now - 2000).toISOString(), done: true, ms: 800, status: 200 }], +}); + +const words = { + en: { cond: "not in ~/big-task", dir: "The agent works in /Users/me/scratch.", none: "The agent didn't say which folder it works in.", label: "not in folder", in: "in folder", + aside: "a/opus is paused by rule 1 (not in ~/big-task), so it is left out until that ends. The agent works in /Users/me/scratch.", + bad: "Rule 1: a folder is a whole path, like ~/work or /Users/me/work", bare: "Rule 1: a pause needs hours, days, agents or folders", edit: "Edit", save: "Save", pause: "pause", send: "send to" }, + zh: { cond: "不在 ~/big-task 中", dir: "Agent 的工作目录是 /Users/me/scratch。", none: "Agent 没有说明它的工作目录。", label: "不在文件夹", in: "项目文件夹", + bad: "规则 1:文件夹需是完整路径,如 ~/work 或 /Users/me/work", bare: "第 1 条规则:暂停需要设时段、星期、Agent 或文件夹", edit: "编辑", save: "保存", pause: "暂停", send: "先发给" }, + "zh-TW": { cond: "不在 ~/big-task 中", dir: "Agent 的工作目錄是 /Users/me/scratch。", none: "Agent 沒有說明它的工作目錄。", label: "不在資料夾", in: "專案資料夾", + bad: "規則 1:資料夾需是完整路徑,如 ~/work 或 /Users/me/work", bare: "第 1 條規則:暫停需要設時段、星期、Agent 或資料夾", edit: "編輯", save: "儲存", pause: "暫停", send: "先發給" }, + ja: { cond: "~/big-task 以外", dir: "エージェントの作業フォルダは /Users/me/scratch です。", none: "エージェントは作業フォルダを伝えていません。", label: "除外フォルダ", in: "フォルダ", + bad: "ルール 1:フォルダは ~/work や /Users/me/work のような完全なパスで指定してください", bare: "ルール 1:一時停止には時間帯、曜日、エージェント、またはフォルダが必要です", edit: "編集", save: "保存", pause: "一時停止", send: "送信先" }, + de: { cond: "nicht in ~/big-task", dir: "Der Agent arbeitet in /Users/me/scratch.", none: "Der Agent hat nicht gesagt, in welchem Ordner er arbeitet.", label: "nicht im Ordner", in: "im Ordner", + bad: "Regel 1: Ein Ordner ist ein ganzer Pfad, etwa ~/work oder /Users/me/work", bare: "Regel 1: eine Pause braucht Uhrzeiten, Tage, Agenten oder Ordner", edit: "Bearbeiten", save: "Speichern", pause: "pausieren", send: "senden an" }, +}; + +function serve(lang, posts, route) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + let first = true; + 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 + const routes = first ? [route] : []; + first = false; + return json({ mine: true, now: new Date().toISOString(), seq: 7, totals: { requests: 1, rerouted: 0, errors: 0 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) { + posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") }); + return json(groups()); + } + 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, width, folder) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts, routeFrom(folder))); + await page.goto("http://magpie.test/?view=routing"); + const group = page.locator(".rt-group").first(); + await group.waitFor(); + return { page, group, errors, posts }; +} + +// the view wheeled down to a button, as the reader would (the page keeps +// still for any other scroll), and the button clicked where it is +async function press(page, b) { + await page.mouse.move(Math.min(550, page.viewportSize().width / 2), 600); + for (let i = 0; i < 10 && (await b.boundingBox()).y > 1400 - 160; i++) { + await page.mouse.wheel(0, 300); + await page.waitForTimeout(150); + } + const bb = await b.boundingBox(); + await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: a pause outside a folder`, async (t) => { + const { page, group, errors, posts } = await open(t, engine, lang, 1100, "/Users/me/scratch"); + + // the trace: paused outside the folder, and the folder the agent said + await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.dir); + const said = await page.evaluate(() => document.documentElement.innerText); + assert(said.includes(w.cond), `the pause's folders are told: ${said.slice(0, 2000)}`); + if (w.aside) assert(said.includes(w.aside), `the paused reason: ${said.slice(0, 2000)}`); + + // the group's rule, in words + const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); + assert(title.includes(`1. ${w.cond} → ${w.pause}`), `the rule reads by its folders: ${title}`); + + // the editor: a pause shows both folder conditions, the request's are hidden + await group.locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + const row = ed.locator(".rt-rule").first(); + const xf = row.locator(".rt-cond.xf"); + await xf.waitFor(); + assert.equal(await xf.getAttribute("class"), "rt-cond xf on"); + assert.equal(await xf.locator("span").first().textContent(), w.label); + assert.equal(await row.locator(".rt-cond.fd").isVisible(), true, "in folder on a pause"); + assert.equal(await row.locator(".rt-cond.fd span").first().textContent(), w.in); + assert.equal(await row.locator(".rt-cond.tk").isVisible(), false, "no tokens on a pause"); + const box = xf.locator("input"); + assert.equal(await box.inputValue(), "~/big-task"); + + // not a whole path: refused, nothing saved + await box.fill("big-task"); + const saveBtn = ed.locator("button.primary", { hasText: w.save }); + await press(page, saveBtn); + await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.bad); + assert.equal(posts.filter((p) => p.path === "/api/groups/save").length, 0); + + // emptied, the pause has no condition left: refused + await box.fill(""); + assert.equal(await xf.getAttribute("class"), "rt-cond xf"); + await press(page, saveBtn); + await page.waitForFunction((s) => document.querySelector("#status")?.textContent === s, w.bare); + assert.equal(posts.filter((p) => p.path === "/api/groups/save").length, 0); + + // turned to send-to and back to a pause, the folders typed are kept + await box.fill("~/big-task , ~/My Task/,"); + await press(page, row.locator(".rt-act")); + assert.equal(await page.locator("select").count(), 0, "the app menu, not a native select"); + await page.locator("#list li").filter({ hasText: w.send }).first().click(); + assert.equal(await ed.locator(".rt-rule").first().locator(".rt-cond.tk").isVisible(), true, "a send-to rule's tokens"); + await press(page, ed.locator(".rt-rule").first().locator(".rt-act")); + await page.locator("#list li").filter({ hasText: w.pause }).first().click(); + const xf2 = ed.locator(".rt-rule").first().locator(".rt-cond.xf"); + assert.equal(await xf2.getAttribute("class"), "rt-cond xf on"); + assert.equal(await xf2.locator("input").inputValue(), "~/big-task, ~/My Task/"); + + await press(page, saveBtn); + 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.use, !!r.pause, r.exceptFolders]), [["a/opus", true, ["~/big-task", "~/My Task/"]]]); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: a pause outside a folder at a phone's width, the agent saying none`, async (t) => { + const { page, group, errors } = await open(t, engine, lang, 390, ""); + await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.none); + await press(page, group.locator("button", { hasText: w.edit })); // the group is below the fold here + const row = page.locator(".rt-gedit .rt-rule").first(); + const xf = row.locator(".rt-cond.xf"); + await xf.waitFor(); + const r = await row.boundingBox(); + for (const c of [xf, row.locator(".rt-cond.fd")]) { + const b = await c.boundingBox(); + assert(b.x >= r.x - 1 && b.x + b.width <= r.x + r.width + 1, `the folders' condition stays in its rule: ${JSON.stringify([b, r])}`); + } + const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(wide <= 0, `no sideways scroll: ${wide}px`); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/routing-pause.test.cjs b/internal/gui/tests/routing-pause.test.cjs index db0ad947e..e359784b9 100644 --- a/internal/gui/tests/routing-pause.test.cjs +++ b/internal/gui/tests/routing-pause.test.cjs @@ -5,7 +5,7 @@ // group's rule reads as "→ pause "; the trace tells the model was // paused, by which rule and when; in the editor the rule's action is picked // from the app menu, a pause shows only the conditions it holds by (hours, -// days, agents), isn't saved without one, and is saved as pause:true. In +// days, agents, folders), isn't saved without one, and is saved as pause:true. In // every language the page has, at a narrow width with nothing run past // the side. const assert = require("node:assert/strict"); @@ -36,8 +36,8 @@ const route = { }; const words = { - en: { aside: "a/glm is paused by rule 1 (14:00–18:00 Mon–Fri), so it is left out until that ends.", title: "1. 14:00–18:00 Mon–Fri → pause A · glm", pause: "pause", send: "send to", edit: "Edit", add: "Add a rule", save: "Save", bare: "Rule 2: a pause needs hours, days or agents", warn: "left out of the group then: not tried, not a fallback" }, - zh: { aside: "a/glm 被规则 1(周一–周五 14:00–18:00)暂停,在此之前不会被调用。", title: "1. 周一–周五 14:00–18:00 → 暂停 A · glm", pause: "暂停", send: "先发给", edit: "编辑", add: "添加规则", save: "保存", bare: "第 2 条规则:暂停需要设时段、星期或 Agent", warn: "这段时间移出分组:不会被调用,也不做备用" }, + en: { aside: "a/glm is paused by rule 1 (14:00–18:00 Mon–Fri), so it is left out until that ends.", title: "1. 14:00–18:00 Mon–Fri → pause A · glm", pause: "pause", send: "send to", edit: "Edit", add: "Add a rule", save: "Save", bare: "Rule 2: a pause needs hours, days, agents or folders", warn: "left out of the group then: not tried, not a fallback" }, + zh: { aside: "a/glm 被规则 1(周一–周五 14:00–18:00)暂停,在此之前不会被调用。", title: "1. 周一–周五 14:00–18:00 → 暂停 A · glm", pause: "暂停", send: "先发给", edit: "编辑", add: "添加规则", save: "保存", bare: "第 2 条规则:暂停需要设时段、星期、Agent 或文件夹", warn: "这段时间移出分组:不会被调用,也不做备用" }, "zh-TW": { pause: "暫停", send: "先發給", edit: "編輯", add: "新增規則", save: "儲存" }, ja: { pause: "一時停止", send: "送信先" }, de: { pause: "pausieren", send: "senden an" }, diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index 04fac42c9..a300f6b58 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -29,7 +29,8 @@ type SharedGroup struct { // effort, context, levels, fast and off members. A group holds no key or // account of its own, only provider/model ids, so nothing secret goes with // it; what is derived (the models its patterns match now, found, hidden, -// switched off) stays behind, and so do the rules that hold by a folder: +// switched off) stays behind, and so do the rules that hold by a folder, +// in it or outside it: // a folder is a path on the sharer's own machine, which names their // projects and means nothing on another. func ShareGroup(id string) (string, error) { @@ -51,7 +52,7 @@ func ShareGroup(id string) (string, error) { g.Members, g.Match = ownMembers(g) g.Matched = nil g.Auto, g.Hidden, g.Disabled = false, false, false - g.Rules = slices.DeleteFunc(g.Rules, func(r Rule) bool { return len(r.Folders) > 0 }) + g.Rules = slices.DeleteFunc(g.Rules, Rule.ByFolder) out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g}) return string(out), err } @@ -210,7 +211,7 @@ func ImportGroup(text string) (Imported, error) { use = memberHere(entries, all, r.Use) } // a folder is the sharer's path, never this machine's - if use == "" || !slices.Contains(in, use) || (r.Intent != "" && g.Classifier == "") || len(r.Folders) > 0 { + if use == "" || !slices.Contains(in, use) || (r.Intent != "" && g.Classifier == "") || r.ByFolder() { res.Rules++ continue } diff --git a/internal/provider/group_share_test.go b/internal/provider/group_share_test.go index 6e12af866..f2607cf65 100644 --- a/internal/provider/group_share_test.go +++ b/internal/provider/group_share_test.go @@ -45,6 +45,7 @@ func TestSharedGroupRoundTrip(t *testing.T) { {Use: "a/x:high", Tokens: 50000, Agents: []string{"codex"}}, {Use: "b/x", Time: &TimeWindow{From: "22:00", To: "08:00", Days: []string{"fri"}}}, {Use: "a/small", Folders: []string{"~/work/acme-secret"}}, + {Use: "a/small", Pause: true, ExceptFolders: []string{"~/work/big-secret"}}, }} if err := SaveGroup(g); err != nil { t.Fatal(err) @@ -53,7 +54,7 @@ func TestSharedGroupRoundTrip(t *testing.T) { if err != nil { t.Fatal(err) } - if strings.Contains(text, secret) || strings.Contains(text, "127.0.0.1") || strings.Contains(text, "acme-secret") { + if strings.Contains(text, secret) || strings.Contains(text, "127.0.0.1") || strings.Contains(text, "acme-secret") || strings.Contains(text, "big-secret") { t.Fatalf("the shared text carries a provider's key or address, or the sharer's folder: %s", text) } if !strings.Contains(text, `"magpie":"routing-group"`) || !strings.Contains(text, `"version":1`) { @@ -73,8 +74,8 @@ func TestSharedGroupRoundTrip(t *testing.T) { got.Routing != src.Routing || got.Affinity != src.Affinity || got.Patience != src.Patience || got.Classifier != src.Classifier { t.Fatalf("imported %+v\nfrom %+v", got, src) } - // all but the rule by the sharer's folder - a, _ := json.Marshal(src.Rules[:len(src.Rules)-1]) + // all but the rules by the sharer's folders + a, _ := json.Marshal(src.Rules[:len(src.Rules)-2]) b, _ := json.Marshal(got.Rules) if string(a) != string(b) { t.Fatalf("rules %s, want %s", b, a) @@ -98,6 +99,7 @@ func TestSharedGroupMissingMembers(t *testing.T) { {Use: "relay/x", Agents: []string{"claude"}}, {Use: "relay/x", Intent: "hard"}, {Use: "relay/x", Folders: []string{"/home/them/proj"}}, + {Use: "relay/x", Pause: true, ExceptFolders: []string{"/home/them/big"}}, }, }}) res, err := ImportGroup(string(text)) @@ -110,8 +112,8 @@ func TestSharedGroupMissingMembers(t *testing.T) { if want := []string{"relay/x → mine/x"}; !slices.Equal(res.Instead, want) { t.Errorf("instead %v, want %v", res.Instead, want) } - if res.Rules != 3 { - t.Errorf("rules left out %d, want 3: the one to gone/y, the one by intent and the one by their folder", res.Rules) + if res.Rules != 4 { + t.Errorf("rules left out %d, want 4: the one to gone/y, the one by intent and the two by their folders", res.Rules) } g := sharedAt(t, res.ID) if !slices.Equal(g.Members, []string{"mine/x"}) || len(g.Off) != 0 || g.Classifier != "" || len(g.Rules) != 1 || g.Rules[0].Use != "mine/x" { diff --git a/internal/provider/grouprule.go b/internal/provider/grouprule.go index 743661924..58db2c337 100644 --- a/internal/provider/grouprule.go +++ b/internal/provider/grouprule.go @@ -19,7 +19,9 @@ package provider // A pause rule (Rule.Pause) sends nothing first: while it holds, the // member it names is out of the group altogether — not first, not a // failover, not where a conversation was — as a member switched off is -// (Group.Off), but only at its hours, on its days or for its agents. It is +// (Group.Off), but only at its hours, on its days, for its agents or in its +// folders (or outside them: #1606, an account's quota kept for the long +// task in one project). It is // looked at on every request, not as a turn begins: a paused model is // paid nothing in its hours, so a turn on it moves when they begin. @@ -67,10 +69,18 @@ type Rule struct { // "C:\work"; WSL's /mnt/c/work is C:\work. When the agent doesn't // say its folder, it doesn't match. Folders []string `json:"folders,omitempty"` + // ExceptFolders: the request's working folder is none of these nor + // inside one, as Folders reads them. A request whose agent doesn't say + // its folder is not known to be in one, so it holds for it: a pause + // "except in ~/big-task" keeps the model for requests known to come + // from there (#1606), never for one that may come from elsewhere. + ExceptFolders []string `json:"exceptFolders,omitempty"` // Pause: rather than sending to Use first, the rule leaves Use out of // the group while it holds (John on Discord: a model paused in a - // vendor's peak hours). Only Time and Agents can be its conditions, - // what is known of every request before it is read. + // vendor's peak hours). Only Time, Agents, Folders and ExceptFolders + // can be its conditions: the request's clock, its agent and the folder + // it says, never what it asks for — a pause keeps the model out of the + // request whatever it is. Pause bool `json:"pause,omitempty"` } @@ -250,6 +260,9 @@ func (r Rule) Conditions() []string { if len(r.Folders) > 0 { out = append(out, "folder "+strings.Join(r.Folders, "|")) } + if len(r.ExceptFolders) > 0 { + out = append(out, "not folder "+strings.Join(r.ExceptFolders, "|")) + } return out } @@ -264,20 +277,13 @@ func cleanRules(rules []Rule, members []string) ([]Rule, error) { r.Agents[j] = strings.ToLower(r.Agents[j]) } n := i + 1 - var folders []string - for _, p := range r.Folders { - if strings.TrimSpace(p) == "" { - continue - } - c, err := cleanFolder(p) - if err != nil { - return nil, fmt.Errorf("rule %d: %w", n, err) - } - if !slices.Contains(folders, c) { - folders = append(folders, c) - } + var err error + if r.Folders, err = cleanFolders(r.Folders); err != nil { + return nil, fmt.Errorf("rule %d: %w", n, err) + } + if r.ExceptFolders, err = cleanFolders(r.ExceptFolders); err != nil { + return nil, fmt.Errorf("rule %d: %w", n, err) } - r.Folders = folders if r.Time != nil { w := *r.Time if err := w.clean(); err != nil { @@ -301,8 +307,8 @@ func cleanRules(rules []Rule, members []string) ([]Rule, error) { return nil, fmt.Errorf("rule %d: an intent is at most %d characters", n, MaxIntent) case len(r.Conditions()) == 0: return nil, fmt.Errorf("rule %d: it needs a condition (tokens, images, effort, agents, intent, compacting, time or folders)", n) - case r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact || len(r.Folders) > 0): - return nil, fmt.Errorf("rule %d: a pause holds by hours, days or agents only", n) + case r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact): + return nil, fmt.Errorf("rule %d: a pause holds by hours, days, agents or folders only", n) } if len(r.Agents) == 0 { r.Agents = nil @@ -359,7 +365,7 @@ func (r Rule) MatchesBesidesIntent(q RuleRequest) bool { if r.Time != nil && !r.Time.Holds(q.At) { return false } - if len(r.Folders) > 0 && !slices.ContainsFunc(r.Folders, func(root string) bool { return FolderUnder(q.Folder, root) }) { + if !r.inFolders(q.Folder) { return false } switch r.Effort { @@ -460,11 +466,11 @@ func ruledEntry(e *Entry, g Group, ms []Member, entries []Entry) { if !ok || r.Pause { continue } - if r.Images && r.Tokens == 0 && r.Effort == "" && len(r.Agents) == 0 && r.Intent == "" && !r.Compact && r.Time == nil && len(r.Folders) == 0 && sees(x) && !e.Images && + if r.Images && r.Tokens == 0 && r.Effort == "" && len(r.Agents) == 0 && r.Intent == "" && !r.Compact && r.Time == nil && !r.ByFolder() && sees(x) && !e.Images && !slices.ContainsFunc(g.Rules[:i], func(b Rule) bool { y, ok := of(b.Use); return !b.Pause && (!ok || !sees(y)) }) { e.Images, e.ImageInput = true, x.ImageInput } - if r.Tokens == 0 || r.Images || r.Effort != "" || len(r.Agents) > 0 || r.Intent != "" || r.Compact || r.Time != nil || len(r.Folders) > 0 || x.Context <= e.Context { + if r.Tokens == 0 || r.Images || r.Effort != "" || len(r.Agents) > 0 || r.Intent != "" || r.Compact || r.Time != nil || r.ByFolder() || x.Context <= e.Context { continue // only a rule of length alone takes every long request } // every request up to the rule's length must fit whoever may get @@ -496,17 +502,46 @@ func ruledEntry(e *Entry, g Group, ms []Member, entries []Entry) { } // Pauses reports whether a pause rule holds for a request from agent at -// the time given. -func (r Rule) Pauses(agent string, at time.Time) bool { - if !r.Pause || r.Time == nil && len(r.Agents) == 0 { +// the time given, working in folder ("" when it didn't say). +func (r Rule) Pauses(agent, folder string, at time.Time) bool { + if !r.Pause || r.Time == nil && len(r.Agents) == 0 && !r.ByFolder() { return false } if r.Time != nil && !r.Time.Holds(at) { return false } + if !r.inFolders(folder) { + return false + } return len(r.Agents) == 0 || slices.Contains(r.Agents, strings.ToLower(agent)) } +// ByFolder reports whether the rule holds by the folder the agent works +// in, in some or outside them: the request's folder is then read for it. +func (r Rule) ByFolder() bool { return len(r.Folders) > 0 || len(r.ExceptFolders) > 0 } + +// inFolders reports whether folder ("" unknown) is as the rule's folders +// ask: in one of Folders, when it has some (an unknown folder is in none), +// and in none of ExceptFolders (an unknown folder is not known to be in +// one, so it is outside them). +func (r Rule) inFolders(folder string) bool { + under := func(root string) bool { return FolderUnder(folder, root) } + if len(r.Folders) > 0 && !slices.ContainsFunc(r.Folders, under) { + return false + } + return !slices.ContainsFunc(r.ExceptFolders, under) +} + +// PausesByFolder reports whether a pause rule of g, or of a group in it on +// the way to one of ms, holds by folder: the request's folder is then +// read before the pauses are looked at. +func PausesByFolder(g Group, ms []Member) bool { + byFolder := func(x Group) bool { + return slices.ContainsFunc(x.Rules, func(r Rule) bool { return r.Pause && r.ByFolder() }) + } + return byFolder(g) || slices.ContainsFunc(ms, func(m Member) bool { return slices.ContainsFunc(m.Via, byFolder) }) +} + // Paused is a model a pause rule left out of a request's group. type Paused struct { Member string `json:"member"` // "provider/model[:effort]" @@ -514,12 +549,19 @@ type Paused struct { Rule int `json:"rule"` // the rule, from 1 Use string `json:"use"` // the member the rule names: the model, or a group in the group When []string `json:"when"` + // Folder: the folder the agent said it works in, when the rule holds + // by folder (ByFolder); "" when it said none, which is outside every + // folder of a rule's ExceptFolders. + Folder string `json:"folder,omitempty"` + ByFolder bool `json:"byFolder,omitempty"` } -// PausedOut leaves out of ms the models a pause rule holds for now: the -// group's own, or those of a group in it on the way to them. A rule naming -// a group in the group pauses every model of it. -func PausedOut(g Group, ms []Member, agent string, at time.Time) (kept []Member, paused []Paused) { +// PausedOut leaves out of ms the models a pause rule holds for now, for a +// request from agent working in folder ("" when it didn't say, or wasn't +// read: see PausesByFolder): the group's own, or those of a group in it on +// the way to them. A rule naming a group in the group pauses every model +// of it. +func PausedOut(g Group, ms []Member, agent, folder string, at time.Time) (kept []Member, paused []Paused) { if !slices.ContainsFunc(g.Rules, func(r Rule) bool { return r.Pause }) && !slices.ContainsFunc(ms, func(m Member) bool { return slices.ContainsFunc(m.Via, func(v Group) bool { return slices.ContainsFunc(v.Rules, func(r Rule) bool { return r.Pause }) }) @@ -534,8 +576,11 @@ func PausedOut(g Group, ms []Member, agent string, at time.Time) (kept []Member, by, in = m.Via[d-1], m.Via[d-1].ID } for i, r := range by.Rules { - if d < len(m.Path) && pathNames(m.Path[d:], r.Use) && r.Pauses(agent, at) { - hit = &Paused{Member: WithMemberEffort(m.Provider.ID+"/"+m.Model, m.Effort), Group: in, Rule: i + 1, Use: r.Use, When: r.Conditions()} + if d < len(m.Path) && pathNames(m.Path[d:], r.Use) && r.Pauses(agent, folder, at) { + hit = &Paused{Member: WithMemberEffort(m.Provider.ID+"/"+m.Model, m.Effort), Group: in, Rule: i + 1, Use: r.Use, When: r.Conditions(), ByFolder: r.ByFolder()} + if r.ByFolder() { + hit.Folder = folder + } break } } diff --git a/internal/provider/grouprule_pause_test.go b/internal/provider/grouprule_pause_test.go index d3283c1f7..9fe760041 100644 --- a/internal/provider/grouprule_pause_test.go +++ b/internal/provider/grouprule_pause_test.go @@ -46,7 +46,7 @@ func TestPauseRuleCleanAndMatch(t *testing.T) { {rules[1], "claude", 10, false}, {Rule{Use: "a/x", Time: peak}, "claude", 10, false}, // a send-to rule pauses nothing } { - if got := c.r.Pauses(c.agent, at(2, c.hour, 0)); got != c.want { + if got := c.r.Pauses(c.agent, "", at(2, c.hour, 0)); got != c.want { t.Errorf("%+v %s %d: %v", c.r, c.agent, c.hour, got) } } @@ -94,17 +94,17 @@ func TestPausedOut(t *testing.T) { } // the group's own model, at its effort, and a group in it's own pause g := Group{ID: "top", Rules: []Rule{{Use: "b/y", Pause: true, Time: peak}}} - kept, paused := PausedOut(g, ms, "claude", at(2, 10, 0)) + kept, paused := PausedOut(g, ms, "claude", "", at(2, 10, 0)) if strings.Join(names(kept), ",") != "a/x,c/m" || len(paused) != 2 || paused[0].Member != "d/m" || paused[0].Group != "cheap" || paused[1].Member != "b/y:high" || paused[1].Group != "" { t.Fatalf("%v %+v", names(kept), paused) } // a group in the group named: all its models g.Rules = []Rule{{Use: "group/cheap", Pause: true, Time: peak}} - if kept, _ = PausedOut(g, ms, "claude", at(2, 10, 0)); strings.Join(names(kept), ",") != "a/x,b/y" { + if kept, _ = PausedOut(g, ms, "claude", "", at(2, 10, 0)); strings.Join(names(kept), ",") != "a/x,b/y" { t.Fatal(names(kept)) } // outside the hours, nobody - if kept, paused = PausedOut(g, ms, "claude", at(2, 19, 0)); len(kept) != 4 || len(paused) != 0 { + if kept, paused = PausedOut(g, ms, "claude", "", at(2, 19, 0)); len(kept) != 4 || len(paused) != 0 { t.Fatal(names(kept), paused) } } diff --git a/internal/provider/rulefolder.go b/internal/provider/rulefolder.go index ca496657f..0733e94b8 100644 --- a/internal/provider/rulefolder.go +++ b/internal/provider/rulefolder.go @@ -10,6 +10,7 @@ import ( "path" "regexp" "runtime" + "slices" "strings" ) @@ -85,3 +86,21 @@ func cleanFolder(p string) (string, error) { } return p, nil } + +// cleanFolders checks a rule's folders, each once, none blank. +func cleanFolders(in []string) ([]string, error) { + var out []string + for _, p := range in { + if strings.TrimSpace(p) == "" { + continue + } + c, err := cleanFolder(p) + if err != nil { + return nil, err + } + if !slices.Contains(out, c) { + out = append(out, c) + } + } + return out, nil +} diff --git a/internal/provider/rulefolder_test.go b/internal/provider/rulefolder_test.go index 2f1e5fe96..4c02ed14f 100644 --- a/internal/provider/rulefolder_test.go +++ b/internal/provider/rulefolder_test.go @@ -4,6 +4,7 @@ import ( "slices" "strings" "testing" + "time" ) func folderEnv(t *testing.T, fold bool, home string) { @@ -70,7 +71,7 @@ func TestFolderUnder(t *testing.T) { } // A rule's folders are whole paths, kept as typed but for a trailing -// slash; a pause rule can't have them; folders alone are a condition. +// slash; folders alone are a condition. func TestRuleFoldersCleaned(t *testing.T) { members := []string{"a/m", "b/m"} out, err := cleanRules([]Rule{{Use: "b/m", Folders: []string{" ~/work/acme/ ", "", "~/work/acme", `C:\work\`, "/", `C:\`}}}, members) @@ -86,8 +87,8 @@ func TestRuleFoldersCleaned(t *testing.T) { for _, bad := range []Rule{ {Use: "b/m", Folders: []string{"work/acme"}}, {Use: "b/m", Folders: []string{"~work"}}, - {Use: "b/m", Pause: true, Folders: []string{"/x"}}, - {Use: "b/m", Folders: []string{" "}}, // nothing left: no condition + {Use: "b/m", Pause: true, Folders: []string{"/x"}, Tokens: 1000}, // a pause holds by folder, not by length + {Use: "b/m", Folders: []string{" "}}, // nothing left: no condition } { if _, err := cleanRules([]Rule{bad}, members); err == nil { t.Errorf("%+v was taken", bad) @@ -146,9 +147,114 @@ func TestParseRuleFolders(t *testing.T) { if r, _, _, err := ParseRule(g, RuleWords(`use=x folder=~/a`)); err != nil || r.Line() != "use=b/x folders=~/a" { t.Errorf("%q %v", r.Line(), err) } - for _, bad := range []string{`use=x folders=`, `use=x folders=work`, `pause=x time=09:00-18:00 folders=/a`} { + for _, bad := range []string{`use=x folders=`, `use=x folders=work`, `pause=x folders=/a tokens=1k`, `use=x except-folders=`, `pause=x except-folders=work`} { if _, _, _, err := ParseRule(g, RuleWords(bad)); err == nil { t.Errorf("%s was taken", bad) } } } + +// #1606 (Ti800): a pause by folder. Outside some folders it holds for +// every request not known to be in one — another folder, or an agent that +// doesn't say — so the member is kept for the task there; in some folders +// it holds for theirs only. Its other conditions hold with it. +func TestPauseByFolderRule(t *testing.T) { + folderEnv(t, false, "/home/me") + keep := Rule{Use: "claude/opus", Pause: true, ExceptFolders: []string{"~/big-task"}} + in := Rule{Use: "claude/opus", Pause: true, Folders: []string{"~/scratch"}} + night := Rule{Use: "claude/opus", Pause: true, Folders: []string{"~/scratch"}, Time: &TimeWindow{From: "22:00", To: "08:00"}} + at := time.Date(2026, 10, 12, 10, 0, 0, 0, time.Local) + for _, tc := range []struct { + name string + r Rule + folder string + want bool + }{ + {"keep: the task", keep, "/home/me/big-task", false}, + {"keep: inside the task", keep, "/home/me/big-task/web", false}, + {"keep: another project", keep, "/home/me/small", true}, + {"keep: a name that starts the same", keep, "/home/me/big-task-2", true}, + {"keep: no folder said", keep, "", true}, + {"in: the folder", in, "/home/me/scratch/x", true}, + {"in: elsewhere", in, "/home/me/big-task", false}, + {"in: no folder said", in, "", false}, + {"in, at night: by day", night, "/home/me/scratch", false}, + {"a send-to rule pauses nothing", Rule{Use: "claude/opus", ExceptFolders: []string{"~/big-task"}}, "/x", false}, + } { + if got := tc.r.Pauses("claude", tc.folder, at); got != tc.want { + t.Errorf("%s: %v", tc.name, got) + } + } + + members := []string{"claude/opus", "openrouter/opus"} + out, err := cleanRules([]Rule{{Use: "claude/opus", Pause: true, ExceptFolders: []string{"~/big-task/", "~/big-task"}}}, members) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(out[0].ExceptFolders, []string{"~/big-task"}) || !slices.Equal(out[0].Conditions(), []string{"not folder ~/big-task"}) { + t.Errorf("cleaned %+v %q", out[0], out[0].Conditions()) + } + for _, bad := range []Rule{ + {Use: "claude/opus", Pause: true, ExceptFolders: []string{"big-task"}}, + {Use: "claude/opus", Pause: true, ExceptFolders: []string{"~/x"}, Images: true}, + } { + if _, err := cleanRules([]Rule{bad}, members); err == nil { + t.Errorf("%+v was taken", bad) + } + } + + g := Group{ID: "g", Rules: []Rule{keep}} + ms := []Member{{ID: "claude/opus", Provider: Provider{ID: "claude"}, Model: "opus", Path: []string{"claude/opus"}}, + {ID: "openrouter/opus", Provider: Provider{ID: "openrouter"}, Model: "opus", Path: []string{"openrouter/opus"}}} + if !PausesByFolder(g, ms) || PausesByFolder(Group{Rules: []Rule{{Use: "claude/opus", Folders: []string{"/x"}}}}, ms) { + t.Error("PausesByFolder: a pause by folder reads the folder, a send-to rule's doesn't") + } + kept, paused := PausedOut(g, ms, "claude", "/home/me/small", at) + if len(kept) != 1 || kept[0].ID != "openrouter/opus" || len(paused) != 1 || paused[0].Folder != "/home/me/small" || !paused[0].ByFolder { + t.Errorf("elsewhere: kept %+v paused %+v", kept, paused) + } + if kept, paused = PausedOut(g, ms, "claude", "/home/me/big-task", at); len(kept) != 2 || len(paused) != 0 { + t.Errorf("in the task: kept %+v paused %+v", kept, paused) + } +} + +// A send-to rule outside some folders matches every request not known to +// be in one, as a pause's does. +func TestRuleMatchesExceptFolders(t *testing.T) { + folderEnv(t, false, "/home/me") + r := Rule{Use: "b/m", ExceptFolders: []string{"~/work/acme"}} + for folder, want := range map[string]bool{"/home/me/work/acme": false, "/home/me/work/acme/web": false, "/home/me/oss": true, "": true} { + if got := r.Matches(RuleRequest{Folder: folder}); got != want { + t.Errorf("%q: %v", folder, got) + } + } + both := Rule{Use: "b/m", Folders: []string{"~/work"}, ExceptFolders: []string{"~/work/acme"}} + if !both.Matches(RuleRequest{Folder: "/home/me/work/x"}) || both.Matches(RuleRequest{Folder: "/home/me/work/acme/y"}) || both.Matches(RuleRequest{}) { + t.Error("in ~/work but not ~/work/acme") + } +} + +// pause= takes folders= and except-folders=, typed and read back the same. +func TestParsePauseByFolder(t *testing.T) { + g := Group{ID: "auto-claude-opus-5-5", Members: []string{"claude/claude-opus-5-5", "openrouter/anthropic/claude-opus-5-5"}} + r, _, _, err := ParseRule(g, RuleWords(`pause=claude/claude-opus-5-5 except-folders="~/big-task,~/My Task"`)) + if err != nil { + t.Fatal(err) + } + if !r.Pause || r.Use != "claude/claude-opus-5-5" || !slices.Equal(r.ExceptFolders, []string{"~/big-task", "~/My Task"}) { + t.Fatalf("%+v", r) + } + line := r.Line() + if line != `pause=claude/claude-opus-5-5 except-folders="~/big-task,~/My Task"` { + t.Errorf("line %s", line) + } + if back, _, _, err := ParseRule(g, RuleWords(line)); err != nil || !slices.Equal(back.ExceptFolders, r.ExceptFolders) || !back.Pause { + t.Errorf("read back %+v: %v", back, err) + } + if r, _, _, err := ParseRule(g, RuleWords(`pause=claude/claude-opus-5-5 folders=/tmp agents=claude`)); err != nil || r.Line() != "pause=claude/claude-opus-5-5 agents=claude folders=/tmp" { + t.Errorf("%q %v", r.Line(), err) + } + if _, _, _, err := ParseRule(g, RuleWords(`pause=claude/claude-opus-5-5`)); err == nil { + t.Error("a pause with no condition was taken") + } +} diff --git a/internal/provider/ruleparse.go b/internal/provider/ruleparse.go index 680ff0c51..00b1b3cbe 100644 --- a/internal/provider/ruleparse.go +++ b/internal/provider/ruleparse.go @@ -2,8 +2,9 @@ package provider // A rule as it is typed: use= tokens=200k images effort=high // agents=a,b intent="…" compact time=09:00-18:00 days=mon-fri -// folders=~/work,"~/My Project", or -// pause= time=… days=… agents=… — by magpie group rule and the +// folders=~/work,"~/My Project" except-folders=~/work/old, or +// pause= time=… days=… agents=… folders=… except-folders=… — by +// magpie group rule and the // TUI's routing page. import ( @@ -157,19 +158,23 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err } r.Time.Days = days case "folders", "folder", "in", "project", "projects": - for _, p := range strings.Split(v, ",") { - if p = strings.TrimSpace(p); p == "" { - continue - } - c, err := cleanFolder(p) - if err != nil { - return r, 0, "", err - } - r.Folders = append(r.Folders, c) + fs, err := parseFolders(v) + if err != nil { + return r, 0, "", err } - if len(r.Folders) == 0 { + if len(fs) == 0 { return r, 0, "", fmt.Errorf("folders names the working folders it holds in: folders=~/work/acme,~/oss") } + r.Folders = append(r.Folders, fs...) + case "except-folders", "except-folder", "exceptfolders", "not-in", "outside": + fs, err := parseFolders(v) + if err != nil { + return r, 0, "", err + } + if len(fs) == 0 { + return r, 0, "", fmt.Errorf("except-folders names the working folders it doesn't hold in: except-folders=~/big-task") + } + r.ExceptFolders = append(r.ExceptFolders, fs...) case "classifier", "classify", "by": if classifier = strings.TrimSpace(v); classifier == "" { return r, 0, "", fmt.Errorf("classifier=: the model that tells which intent a message is") @@ -181,17 +186,17 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err } at = n default: - return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, pause, tokens, images, effort, agents, intent, compact, time, days, folders, classifier, at)", w) + return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, pause, tokens, images, effort, agents, intent, compact, time, days, folders, except-folders, classifier, at)", w) } } if r.Use == "" { return r, 0, "", fmt.Errorf("use= (or pause=) is missing: one of %s", strings.Join(g.Members, ", ")) } - if r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact || len(r.Folders) > 0) { - return r, 0, "", fmt.Errorf("pause= holds by time=, days= or agents= only") + if r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact) { + return r, 0, "", fmt.Errorf("pause= holds by time=, days=, agents=, folders= or except-folders= only") } - if r.Pause && r.Time == nil && len(r.Agents) == 0 { - return r, 0, "", fmt.Errorf("pause= needs time=, days= or agents=: when the model is left out") + if r.Pause && r.Time == nil && len(r.Agents) == 0 && !r.ByFolder() { + return r, 0, "", fmt.Errorf("pause= needs time=, days=, agents=, folders= or except-folders=: when the model is left out") } if r.Intent != "" && classifier == "" && g.Classifier == "" { return r, 0, "", fmt.Errorf("a rule with an intent needs the group's classifier, the model that tells which intent a message is: add classifier=, best a small fast one") @@ -291,12 +296,33 @@ func (r Rule) Line() string { out = append(out, "days="+strings.ReplaceAll(strings.ToLower(r.Time.DaysText()), "–", "-")) } } - if len(r.Folders) > 0 { - v := strings.ReplaceAll(strings.Join(r.Folders, ","), `"`, "") + folders := func(k string, fs []string) { + if len(fs) == 0 { + return + } + v := strings.ReplaceAll(strings.Join(fs, ","), `"`, "") if strings.ContainsAny(v, " \t") { v = `"` + v + `"` } - out = append(out, "folders="+v) + out = append(out, k+"="+v) } + folders("folders", r.Folders) + folders("except-folders", r.ExceptFolders) return strings.Join(out, " ") } + +// parseFolders reads a typed list of folders, comma separated. +func parseFolders(v string) ([]string, error) { + var out []string + for _, p := range strings.Split(v, ",") { + if p = strings.TrimSpace(p); p == "" { + continue + } + c, err := cleanFolder(p) + if err != nil { + return nil, err + } + out = append(out, c) + } + return out, nil +} diff --git a/internal/tui/routing.go b/internal/tui/routing.go index 86e249d0d..f092afc6e 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -282,8 +282,8 @@ func (m *model) openClassifier(g provider.Group) { // ruleHint is what a rule is typed as. const ruleHint = `use=, and any of: tokens=200k · images · effort=on|low|medium|high|xhigh|max · agents=codex,claude intent="a quick question" (the group's classifier= tells it) · compact -time=09:00-18:00 (local; 22:00-08:00 runs past midnight) · days=mon-fri · folders=~/work/acme,~/oss · at= for its place -or pause= time=… days=… agents=…: the model is left out of the group then, not even a fallback` +time=09:00-18:00 (local; 22:00-08:00 runs past midnight) · days=mon-fri · folders=~/work/acme,~/oss · except-folders=~/old · at= for its place +or pause= time=… days=… agents=… folders=… except-folders=…: the model is left out of the group then, not even a fallback` // openRule asks for a rule: a new one, or rule i (from 0) typed again. func (m *model) openRule(g provider.Group, i int) { diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index eb8cc3f8e..2802aab76 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -221,6 +221,7 @@ magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=# /compact の要約は安いモデルへ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,"~/My Project" # これらのプロジェクトのターンはまずこのモデルへ magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri # その時間帯は外す +magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # ~/big-task のタスク専用:ほかのフォルダでは外す magpie group set coder models+=group/opus-anywhere # グループの中のグループ magpie group rule opus-anywhere # ルール一覧。rule rm|mv <n>、rule classifier <group> <model> magpie group copy opus-anywhere "Opus test" # モデル・ルーティング・ルールが同じ複製。別々に変更できる diff --git a/site/public/docs/start.html b/site/public/docs/start.html index fb611bc61..58a276dcf 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -221,6 +221,7 @@ magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=# /compact summaries to a cheap model magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,"~/My Project" # turns in those projects to it first magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri # left out in those hours +magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # the model kept for the task in ~/big-task: left out of every other folder magpie group set coder models+=group/opus-anywhere # a group in a group magpie group rule opus-anywhere # its rules; rule rm|mv <n>, rule classifier <group> <model> magpie group copy opus-anywhere "Opus test" # the same models, routing and rules, to change on its own diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index 13ea82bc0..185e1503f 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -221,6 +221,7 @@ magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=# /compact 的总结交给便宜的模型 magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,"~/My Project" # 这些项目里的对话先发给它 magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri # 这段时间不用它 +magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # 只留给 ~/big-task 里的任务:其他文件夹不用它 magpie group set coder models+=group/opus-anywhere # 路由组里放路由组 magpie group rule opus-anywhere # 查看规则;rule rm|mv <n>,rule classifier <组> <模型> 换判断模型 magpie group copy opus-anywhere "Opus test" # 复制一份:模型、路由方式和规则都一样,可单独修改