diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 0b82db0e7..165addb25 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -40,6 +40,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - 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. Any model magpie serves can be set (`provider.SetCodexSubagentModel`, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (`sealedTaskIn`: a sealed agent message that isn't a `MESSAGE`, which `withoutSealedMessages` leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. 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 is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's ``, ``, ``, ``, `` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's ``, ``, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's ``; the Codex app's ``. The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`. + - A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`. - 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). 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 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. diff --git a/internal/gateway/classify_test.go b/internal/gateway/classify_test.go index de31d6234..9f5b5c9d2 100644 --- a/internal/gateway/classify_test.go +++ b/internal/gateway/classify_test.go @@ -264,6 +264,37 @@ func TestIntentClassifierFails(t *testing.T) { } } +// A classifier that fails, times out or rests on a turn whose conversation +// had an intent keeps that intent, marked as kept, rather than sending the +// turn to the group's first member (#1826: two timeouts in a row sent +// 复杂 turns to the cheap member); one with none before has none. +func TestIntentClassifierFailsKeepsThePreviousIntent(t *testing.T) { + s, _, _, c := intented(t, provider.Rule{Use: "b/big", Intent: "refactoring"}) + c.set("1", 0) + out, r := postOK(t, s, "k1", chat("rename this package", nil, 0, "")) + if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.Fallback != "" { + t.Fatalf("turn 1: %s %+v", out, r.Rule) + } + c.set("", 500) + out, r = postOK(t, s, "k1", chat("rename this package", []string{"and the tests"}, 0, "")) + cl := r.Rule.Classified + if !strings.Contains(out, "from kb") || r.Rule.N != 1 || !strings.Contains(cl.Error, "classifier down") || cl.Intent != "refactoring" || cl.Fallback != "previous" { + t.Fatalf("down: %s %+v %+v", out, r.Rule, cl) + } + // resting after the failure, the turn after keeps it too + asked := c.n() + out, r = postOK(t, s, "k1", chat("rename this package", []string{"and the tests", "and the docs"}, 0, "")) + cl = r.Rule.Classified + if !strings.Contains(out, "from kb") || !strings.Contains(cl.Error, "not asked again") || cl.Fallback != "previous" || c.n() != asked { + t.Fatalf("resting: %s %+v %d/%d", out, cl, c.n(), asked) + } + // another conversation, with no turn before, has no intent to keep + out, r = postOK(t, s, "k2", chat("rename that package", nil, 0, "")) + if cl = r.Rule.Classified; !strings.Contains(out, "from ka") || r.Rule.N != 0 || cl.Intent != "" || cl.Fallback != "" { + t.Fatalf("no turn before: %s %+v", out, cl) + } +} + // A classifier that answers something else is up: the turn goes on without // an intent, and the next one asks it again rather than resting. func TestIntentOddAnswerDoesNotRest(t *testing.T) { diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index 60f9793c8..082ad0d64 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -82,7 +82,10 @@ type Classified struct { Sure float64 `json:"sure,omitempty"` // how confident it was of the intent, 0 to 1 Cached bool `json:"cached,omitempty"` // said before, for the same message Ms int `json:"ms,omitempty"` // how long asking it took - Error string `json:"error,omitempty"` // why it couldn't say: no intent matches then + Error string `json:"error,omitempty"` // why it couldn't say: no intent matches then, unless Fallback + // Fallback: "previous" when it couldn't say and the turn keeps the + // intent the turn before had (After), rather than none + Fallback string `json:"fallback,omitempty"` // AfterEffort: the reasoning picked for the turn before, which it was told AfterEffort string `json:"afterEffort,omitempty"` @@ -284,6 +287,13 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a } if err != nil { c.Error = err.Error() + if c.After != "" { + // timed out, failed or resting: the intent the turn + // before had, still one of this turn's, is a better + // guess than none, which sends the turn to the + // group's first member whatever it is (#1826) + c.Intent, c.Fallback = c.After, "previous" + } } } q.Intent = c.Intent diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5a25b7c72..eb656e2c3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3166,6 +3166,7 @@ const I18N = { "said before, for the same message": "同一条消息之前已判断过", "in {ms}": "用时 {ms}", "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.": "{by} 未能判断第 {turn} 轮属于 {kinds} 中的哪一个({err}),带意图的规则均不命中。", + "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so the turn keeps “{intent}”, as turn {prev} was.": "{by} 未能判断第 {turn} 轮属于 {kinds} 中的哪一个({err}),因此沿用第 {prev} 轮的“{intent}”。", "{by} was asked which of {kinds} turn {turn} is, and said none ({took}).": "{by} 判断第 {turn} 轮不属于 {kinds} 中的任何一个({took})。", "{by} was asked which of {kinds} turn {turn} is, and said “{intent}” ({took}).": "{by} 判断第 {turn} 轮属于 {kinds} 中的“{intent}”({took})。", "It was told turn {prev} was “{after}”, which a message that only carries on from it is too.": "并告知它第 {prev} 轮为“{after}”,仅承接上一轮的消息也归为此类。", @@ -7597,6 +7598,7 @@ const I18N = { "said before, for the same message": "同一條訊息之前已判斷過", "in {ms}": "用時 {ms}", "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.": "{by} 未能判斷第 {turn} 輪屬於 {kinds} 中的哪一個({err}),帶意圖的規則均不命中。", + "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so the turn keeps “{intent}”, as turn {prev} was.": "{by} 未能判斷第 {turn} 輪屬於 {kinds} 中的哪一個({err}),因此沿用第 {prev} 輪的「{intent}」。", "{by} was asked which of {kinds} turn {turn} is, and said none ({took}).": "{by} 判斷第 {turn} 輪不屬於 {kinds} 中的任何一個({took})。", "{by} was asked which of {kinds} turn {turn} is, and said “{intent}” ({took}).": "{by} 判斷第 {turn} 輪屬於 {kinds} 中的「{intent}」({took})。", "It was told turn {prev} was “{after}”, which a message that only carries on from it is too.": "並告知它第 {prev} 輪為「{after}」,僅承接上一輪的訊息也歸為此類。", @@ -12045,6 +12047,7 @@ const I18N = { "said before, for the same message": "同じメッセージについて判定済み", "in {ms}": "{ms} で", "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.": "{by} はターン {turn} が {kinds} のどれかを判定するはずでしたが、できませんでした({err})。そのため、インテントを含むルールは一致しません。", + "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so the turn keeps “{intent}”, as turn {prev} was.": "{by} はターン {turn} が {kinds} のどれかを判定するはずでしたが、できませんでした({err})。そのため、ターン {prev} と同じ「{intent}」のままにします。", "{by} was asked which of {kinds} turn {turn} is, and said none ({took}).": "{by} にターン {turn} が {kinds} のどれかを尋ねたところ、どれでもないと答えました({took})。", "{by} was asked which of {kinds} turn {turn} is, and said “{intent}” ({took}).": "{by} にターン {turn} が {kinds} のどれかを尋ねたところ、「{intent}」と答えました({took})。", "It was told turn {prev} was “{after}”, which a message that only carries on from it is too.": "ターン {prev} が「{after}」だったことも伝えています。それを続けるだけのメッセージも同じ扱いです。", @@ -16490,6 +16493,7 @@ const I18N = { "said before, for the same message": "bereits zuvor für dieselbe Nachricht bestimmt", "in {ms}": "in {ms}", "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.": "{by} sollte bestimmen, welche von {kinds} Runde {turn} ist, konnte es aber nicht – {err} –, daher trifft keine Regel mit Absicht zu.", + "{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so the turn keeps “{intent}”, as turn {prev} was.": "{by} sollte bestimmen, welche von {kinds} Runde {turn} ist, konnte es aber nicht – {err} –, daher bleibt die Runde bei „{intent}“ wie Runde {prev}.", "{by} was asked which of {kinds} turn {turn} is, and said none ({took}).": "{by} wurde gefragt, welche von {kinds} Runde {turn} ist, und sagte: keine ({took}).", "{by} was asked which of {kinds} turn {turn} is, and said “{intent}” ({took}).": "{by} wurde gefragt, welche von {kinds} Runde {turn} ist, und sagte „{intent}“ ({took}).", "It was told turn {prev} was “{after}”, which a message that only carries on from it is too.": "Ihm wurde mitgeteilt, dass Runde {prev} „{after}“ war; eine Nachricht, die nur daran anknüpft, gilt ebenso.", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 27362d33e..b7e722bde 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -664,6 +664,9 @@ if (!c) return x?.pick ? t("Turn {turn} reasons at {level}, as the classifier picked when it began.", { turn: x.turn, level: x.pick }) : null; const r = { rule: x }; const by = c.by || t("the classifier"), kinds = (c.intents || []).map((x) => `“${x}”`).join(", "); + // it couldn't say, and the turn keeps the intent the turn before had + // (#1826), rather than going with none + if (c.error && c.fallback === "previous" && c.intent) return t("{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so the turn keeps “{intent}”, as turn {prev} was.", { by, kinds, turn: r.rule.turn, err: c.error, intent: c.intent, prev: r.rule.turn - 1 }); if (c.error) return c.intents?.length ? t("{by} was to tell which of {kinds} turn {turn} is, but couldn't — {err} — so no rule with an intent matches it.", { by, kinds, turn: r.rule.turn, err: c.error }) : t("{by} was to rate how hard turn {turn} is, but couldn't — {err} — so it reasons as the agent asked.", { by, turn: r.rule.turn, err: c.error }); diff --git a/internal/gui/tests/routing-intent-fallback.test.cjs b/internal/gui/tests/routing-intent-fallback.test.cjs new file mode 100644 index 000000000..4532a22b8 --- /dev/null +++ b/internal/gui/tests/routing-intent-fallback.test.cjs @@ -0,0 +1,115 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A group's classifier that couldn't say which kind a turn is (timed out, +// failed, resting after a failure) leaves the turn with the intent the turn +// before had, rather than none (#1826). The trace tells it couldn't, why, +// and the intent the turn kept; a failure with nothing to keep still says +// no rule with an intent matches. In every language, and at a phone's +// width the reason stays on the page. +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/fast", name: "fast", providerName: "A", icon: "generic", context: 256000, 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/fast", "b/opus"], routing: "order", ready: true, classifier: "c/cls", + memberInfo: [{ id: "a/fast", ready: true, context: 256000 }, { id: "b/opus", ready: true, context: 1000000 }], + rules: [{ use: "b/opus", intent: "complex" }] }], + pools: [], +}); +const now = Date.now(); +const err = "c/cls: no answer in 8s"; +const routeOf = (kept) => ({ + id: 7, seq: 7, time: new Date(now - 2000).toISOString(), agent: "claude", model: "main", provider: kept ? "b" : "a", done: true, status: 200, ms: 900, tokens: 9000, + group: { id: "main", name: "Main", members: ["a/fast", "b/opus"] }, + order: kept + ? [{ id: "b", provider: "b", name: "B", kind: "key", model: "opus", known: true }, { id: "a", provider: "a", name: "A", kind: "key", model: "fast", known: true }] + : [{ id: "a", provider: "a", name: "A", kind: "key", model: "fast", known: true }, { id: "b", provider: "b", name: "B", kind: "key", model: "opus", known: true }], + tries: [{ id: kept ? "b" : "a", model: kept ? "opus" : "fast", start: new Date(now - 2000).toISOString(), done: true, ms: 800, status: 200 }], + rule: kept + ? { n: 1, use: "b/opus", when: ['intent "complex"'], turn: 3, tokens: 9000, + classified: { by: "c/cls", intents: ["complex"], intent: "complex", after: "complex", error: err, fallback: "previous" } } + : { n: 0, turn: 1, tokens: 9000, classified: { by: "c/cls", intents: ["complex"], error: err } }, +}); + +const words = { + en: { kept: `c/cls was to tell which of “complex” turn 3 is, but couldn't — ${err} — so the turn keeps “complex”, as turn 2 was.`, + none: `c/cls was to tell which of “complex” turn 1 is, but couldn't — ${err} — so no rule with an intent matches it.` }, + zh: { kept: `c/cls 未能判断第 3 轮属于 “complex” 中的哪一个(${err}),因此沿用第 2 轮的“complex”。`, + none: `c/cls 未能判断第 1 轮属于 “complex” 中的哪一个(${err}),带意图的规则均不命中。` }, + "zh-TW": { kept: `c/cls 未能判斷第 3 輪屬於 “complex” 中的哪一個(${err}),因此沿用第 2 輪的「complex」。`, + none: `c/cls 未能判斷第 1 輪屬於 “complex” 中的哪一個(${err}),帶意圖的規則均不命中。` }, + ja: { kept: `c/cls はターン 3 が “complex” のどれかを判定するはずでしたが、できませんでした(${err})。そのため、ターン 2 と同じ「complex」のままにします。`, + none: `c/cls はターン 1 が “complex” のどれかを判定するはずでしたが、できませんでした(${err})。そのため、インテントを含むルールは一致しません。` }, + de: { kept: `c/cls sollte bestimmen, welche von “complex” Runde 3 ist, konnte es aber nicht – ${err} –, daher bleibt die Runde bei „complex“ wie Runde 2.`, + none: `c/cls sollte bestimmen, welche von “complex” Runde 1 ist, konnte es aber nicht – ${err} –, daher trifft keine Regel mit Absicht zu.` }, +}; + +function serve(lang, 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 === "/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, kept) { + 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 = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, routeOf(kept))); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-group").first().waitFor(); + return { page, errors }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + for (const width of [1100, 390]) { + test(`${engine} ${lang} ${width}px: a classifier that couldn't say keeps the turn before's intent`, async (t) => { + const { page, errors } = await open(t, engine, lang, width, true); + await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.kept).catch(() => {}); + const said = await page.evaluate(() => document.documentElement.innerText); + assert(said.includes(w.kept), `the kept intent is told: ${said.slice(0, 3000)}`); + assert(!said.includes(w.none), "not said as no intent"); + const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(wide <= 0, `no sideways scroll: ${wide}px`); + assert.deepEqual(errors, []); + }); + } + test(`${engine} ${lang}: a classifier that couldn't say, with nothing to keep`, async (t) => { + const { page, errors } = await open(t, engine, lang, 1100, false); + await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.none).catch(() => {}); + const said = await page.evaluate(() => document.documentElement.innerText); + assert(said.includes(w.none), `no intent is told: ${said.slice(0, 3000)}`); + assert.deepEqual(errors, []); + }); + } +}