gateway: DSH's compaction leaves a provider out of its limit for the same model elsewhere (qtwaiter on X)

qtwaiter's DSH chat ran on WorkBuddy's deepseek-v4.1-flash until
WorkBuddy rate-limited it. A switch to Trae CN's deepseek-v4.1-flash
failed with the same 429 ("WorkBuddy: 您的使用量已超出频率限制 ...
(out of its allowance: not asked again before ...)"), while DSH's own
DeepSeek route switched fine. compaction-basic (0.2.2-rc.1, agent/request
hook) compacts on the model it switches away from before a turn on
another, whenever the history is over the new model's threshold (Trae CN
lists the model at 200000/64000, so ~84K; DSH's own routes are 1M and
never compact), and fails the switch with MODEL_SWITCH_COMPACTION_FAILED
when that compaction is refused. The compaction went to WorkBuddy, which
magpie held as out of its allowance, so every switch failed.

Now a dsh compaction whose provider has every key or account resting
(quotaHeld or timedHeld over its candidates) goes on the same model from
another provider (provider.AutoGroupOf), the widest window that is
served, allowed to the key and not resting itself
(dshCompactElsewhere in dsh_compact.go). The route records it as
Moved{Why: "dsh-compact-rested"}, which the Routing page explains in
five languages. With no such provider it stays as asked with a log
line. A compaction model set on dsh's row (#5395) is still read first.

Run (mote):
- go test -run TestDshCompact ./internal/gateway/: ok.
  TestDshCompactLeavesRestedProvider replays the screenshot's case:
  turn on workbuddy 429 (Retry-After 3600), compaction then served by
  trae-cn/deepseek-v4.1-flash with WorkBuddy not asked again, the next
  ordinary turn still held. Red on the old code with the reporter's
  exact 429 text. TestDshCompactStaysUnlessRested: not resting, no other
  provider, another agent all stay.
- go vet ./internal/gateway/ on darwin, linux (nogui) and windows; gofmt.
- go test -count=1 -timeout 45m ./internal/gateway/: ok (908.8s)
- GUI (chromium + webkit, 5 languages, 2 widths): dsh-compact-model
  20/20, routing-moved-why 20/20, i18n-keys 4/4, i18n-en-no-cjk 4/4.
At the pushed head (rebased): go vet and the TestDshCompact tests ok.
Broken by hand: skipping the stand-in (`false && m != ""`) turns
TestDshCompactLeavesRestedProvider red; removing the client.js case turns
dsh-compact-model red. Both restored.
Not tried: the real DSH app with a rate-limited WorkBuddy account. A
switch away from a model no other provider serves still fails while its
provider is out of its limit; the compaction model square covers it.
This commit is contained in:
yetone
2026-11-10 13:42:14 +08:00
parent 0a44c1c845
commit 5426c43cca
8 changed files with 283 additions and 28 deletions
+1 -1
View File
@@ -82,7 +82,7 @@ something else shows up as drift.
- dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking` or `AdaptiveWithEffort`, so Max reaches GLM-5.3 as max) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. For a custom provider with more than one URL that is the API its Base URL was given as (`BaseAPI`), after the vendor rules (an OpenAI model on OpenAI's API, a Claude where Messages is served): a relay set to Responses whose Chat URL Detect found beside it had its GPTs on dsh's Chat route (nb5p on Discord, `TestDshCustomResponsesProvider`). dsh's bundled pi-ai (`@earendil-works/pi-ai`, dsh 0.2.1-rc.2) takes `openai-responses` as a route's `api`. A routing group has `responses` when a member is best on Responses and every other member takes a Responses request as it is too, or translates every request anyway (`provider.GroupAPI`, #1594; zyh6036 on X: a group of subscriptions that all serve Responses, not all best there, was asked on Chat), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, so a member only Chat reaches keeps being relayed, and a Messages-only group stays there too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. A model of a route whose api stands as `openai-responses` carries `compat.supportsStrictMode` (#3055): OpenAI's Responses API takes a function tool whose `strict` is left out as a strict-mode one, every property required, so a tool's optional parameters come back filled; pi-ai says `strict: false` on an ordinary tool only when the compat says so, by the api the route has, not by its name. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. A start on a model by an id magpie lists it by no longer, a found group's `group/auto-<slug>` (now `auto/<model>`, `provider.PublicRef`) or a renamed provider's (`provider.RenamedRef`), moves onto the id its route lists, in every profile and the home layer: dsh finds the start by that id, and the desktop app showed no model picked while its patch list held every route (zyh6036 on X, `TestDshStartOnAFoundGroupsOldIdMovesOntoItsId`). `renameFoundGroups` moves only a value applied.json records, and the start dsh read was not one (none on the owner's install either), nor is a pick made in dsh. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id.
- The names every agent's model list gets are `provider.Labels`' ([`modelprefs.go`](../../internal/provider/modelprefs.go)). With Provider in model names off (or own, for names the user gave), a name stands alone unless another model in the same list reads the same, when both keep their provider's after it. A routing group named as anything else in the list keeps "· routing group", and the model it shares the name with stays plain: the group found for a model served by two providers, one of them hidden from the agent, had the shown model read "GPT-6.1 Terra · MyGateway" beside its provider's plain "GPT-6.1 Sol" (nb5p on Discord; `TestPlainNames`, `TestSuffixMode`, `TestPlainOwnNamesGroups`).
- dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to what leaves dsh half the window to compact in (window/2 − 65536), or to a quarter of the window where that is more (every window under 262144, as VS Code and Copilot in JetBrains hold it), on every route and in the older `llm-deepseek` entry (`dshMaxTokens`). A quarter alone cut DeepSeek's 393216 on its 1000000 window to 250000 (#3298); now it keeps all of it and dsh compacts at 541248, while 500000/393216 is held to 184464 and compacts at 250000. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`.
- dsh compacts on the session's latest model (compaction-basic with no `summarizationModel`), so a switch away from a model whose provider is out of its limit failed on the compaction (Musikrv77852 on X, #5395). dsh's opened row has a compaction model square (`compact_model`, `dshCompactField` in [`dsh.go`](../../internal/agent/dsh.go)), offered once dsh is on magpie's route: magpie's own `Live` setting (`settings.DshCompactModel`, `provider.SetDshCompactModel`), which the gateway reads on each request (`dshCompactTo`), so nothing is written into dsh's profiles. DS Bot's requests can't be told from dsh's, so it has no square of its own and its compactions follow the same setting (`TestDshCompactionModelField`, `dsh-compact-model.test.cjs`).
- dsh compacts on the session's latest model (compaction-basic with no `summarizationModel`), so a switch away from a model whose provider is out of its limit failed on the compaction (Musikrv77852 on X, #5395). dsh's opened row has a compaction model square (`compact_model`, `dshCompactField` in [`dsh.go`](../../internal/agent/dsh.go)), offered once dsh is on magpie's route: magpie's own `Live` setting (`settings.DshCompactModel`, `provider.SetDshCompactModel`), which the gateway reads on each request (`dshCompactTo`), so nothing is written into dsh's profiles. DS Bot's requests can't be told from dsh's, so it has no square of its own and its compactions follow the same setting (`TestDshCompactionModelField`, `dsh-compact-model.test.cjs`). With no compaction model set, a compaction on a model whose provider is out of its limit goes to the same model from another provider when one serves it (`dshCompactElsewhere` in the gateway, `dsh-compact-rested`; qtwaiter on X: a WorkBuddy rate limit refused a switch to Trae CN's model).
- Each of magpie's routes has `streamIdleTimeoutMs: 600000` (`dshIdleWait`), the gateway's own wait for a reply's headers (`upstreamHeaderWait`, 10 minutes). llm-pi-ai gives a turn up after 5 minutes without a pi-ai event (`DEFAULT_STREAM_IDLE_TIMEOUT_MS`, 0.1.5 to 0.2.2), and the gateway's `: keepalive` comments (`keepQueued`, `keepQuiet`) are not events: real dsh 0.2.1-rc.2 timed out at a route's 3000ms with comments every second. A turn queued behind dsh's own title request on a plugin serving one request at a time (magpie-gemini-web, `maxConcurrency: 1`) was cut while the gateway and the plugin still waited, and recorded as 499 (tim on Discord). A value already on the route, set in dsh or by hand, stays (`TestDshRoutesWaitAsLongAsTheGateway`, `TestDshRouteKeepsTheUsersIdleWait`). Codex's comment-blind limit is met in the gateway instead (`agentQuietMost`).
- While magpie serves, `KeepDshWired` writes the routes again every 30 seconds, since dsh writes over its patch list. A round that writes nothing is kept (`dshRounds`), and the next round does nothing when nothing it reads has changed since. It checks the bytes of dsh's files (every profile's `cordis.patch.yml`, the home layer, `settings.yaml`, `.env`, `.credentials.yaml`, `config.yaml`) and the gateway's address. It also checks `provider.StampNow`: no Changed, plugin change or `filememo.Forget`, the same environment, and the providers', settings' and catalog's files unchanged. The models are built again when that stamp moves, and at least every `dshModelsFor` (5 minutes) for what no stamp sees, such as another app's account file or a date-retired model. Building the whole catalog and every route each round allocated 12 GB of a user's 35.7 GB in 48 minutes (`TestDshRoundWithNothingChangedBuildsNothing`, `TestDshRoundAfterAChangeWritesAgain`).
- DeepSeek Harness Desktop (macOS arm64 and Windows x64; no Linux build) reads the same `$DSH_HOME` or `~/.dsh` as the CLI, as its own profile `profiles/desktop` (`resolveDshHome` and `resolveDesktopPaths` in the app's `lib/main.js`; `defaultDshHome` in github.com/deepseek-ai/deepseek-harness's `packages/util/home-paths/src/index.ts` and `apps/desktop/src/paths.ts`), so it takes magpie's routes with no wiring of its own (#2279, liangjinyuan-sihan). A profile dsh makes after another was wired (the app opened for the first time after the CLI's web profile) is given magpie's routes by the catalog sync and the serving round (`dshFillNewProfiles`), with the start model the wired ones start on when that is one of magpie's, and with no start when the user picked one of dsh's own there: only the routes, beside dsh's models. That second case was left as dsh's empty template, so the app's picker listed only the DeepSeek account (zyh6036 on X, `TestDshFillNewProfilesWhenTheStartIsTheUsers`). With no profile wired, none is filled. Only that app, from deepseek-ai/deepseek-harness (bundle id `com.deepseek.dsh`, productName DeepSeek Harness in `apps/desktop/scripts/electron-builder-config.mjs`), is dsh's: the community "DeepSeek Hermes" (motongv/deepseek-hermes-desktop) v0.1.1337 took for it is not listed or written for (WuSix on Discord, `TestDshOnlyTheOfficialApp`). It is found by `/Applications/DeepSeek Harness.app`, by `%LOCALAPPDATA%\Programs\DeepSeek Harness`, or by the folder its current-user installer records under `HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e` (`InstallLocation`), whose Uninstall key gives the version (`registered` in [`desktopapp.go`](../../internal/agent/desktopapp.go)), so a user who picked another folder is found. With the app installed but never opened there is no `~/.dsh`: the row is still listed, and connecting writes `profiles/desktop/cordis.patch.yml` from dsh's own template (`dshProfileTemplate`) with magpie's routes, which the app keeps on its first start, since it writes only the files that are missing. The notice says the app starts on it the first time it opens (`noticeDsh5`). Disconnect before that first start removes the profile magpie made when nothing else is in it (`dshTidyUnopened`); once the app has opened it, the profile stays and only magpie's entries go (`TestDshDesktopNeverOpened`, `TestDshDesktopRegisteredFolder`; the registry as 0.2.1-rc.2's installer writes it, `TestDshWindowsAsTheInstallerRegistersIt`).
+1 -1
View File
@@ -178,7 +178,7 @@ recorded as a prediction failure (`noPrediction`).
- A model set for Claude Desktop's subagents (`settings.DesktopSubagentModel`, the Agents page's Claude Desktop "subagent model") is put on a subagent's turn in Desktop's Code tab or Cowork after `desktopTurn`, the tiers and the groups, whatever model its lead or its tier asked for (`desktopSubagentPick` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)). Desktop runs its Claude Code with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1`, under which Claude Code ignores the `CLAUDE_CODE_SUBAGENT_MODEL` magpie writes into its settings (see [agent wiring](agent-wiring.md)). A subagent's request is one with `x-claude-code-agent-id` (`subagentOf`) from `claude-desktop`, and only one that offers tools is its turn: Claude Code's tool-less helper calls inside a subagent, on the haiku tier's model, stay where they are, and so do the lead's turns, terminal Claude Code's and every other agent's. The model set must be served by its exact id (`provider.DesktopSubagentUnserved`: `Resolve` takes any model name under a provider that is on), enabled, and allowed to a gateway key held to some models (`groupAllowed` for a group); otherwise the subagent goes on the model asked for and the route trace says why (`Route.Subagent`, said on the Routing page by `subagentWhy`, its `Kind` staying empty). `Route.Model` and the ledger's `Requested` keep the model the subagent asked for. `count_tokens` counts on the model set the same way (`countTokens`). The setting is read on each request, so a change needs no restart of Desktop, and a provider renamed since it was set is read by its new id (`RenamedRef`). A Desktop on another computer that reaches magpie with a named gateway key is read as Claude Code (`agentOf`), so none of Desktop's routing, this included, applies to it. A subagent's turn, moved or not, is never kept as the session's model in `claude-desktop.model` (`desktopTurn`'s `bySubagent`): a subagent on the opus tier's model took the session's place until the lead's next turn, and Desktop's titles asked for meanwhile went to it.
- Desktop's subagent effort (`settings.DesktopSubagentEffort`, `desktopSubagentEffort` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)) applies to the same subagent tool turns, independently of model replacement. Empty leaves requests unchanged. Set, it takes the place of a request model's effort suffix before the existing attempt-level effort fitting: a member fixed at an effort wins, then this pick fitted within group/model levels, then the turn's or request's effort. `withFixedEffort` can enable reasoning when it was disabled, or disable it with `none` on a model that supports that level; a reasonless model is still sent no reasoning fields. `countTokens` applies the pick after restoring any unmasked body. `Route.Effort` keeps the incoming effort, `Route.SubagentEffort` the configured pick, and each try and usage record the level actually sent; the Routing story explains the configured pick even when no model was replaced. A nonempty model pick already classifies the turn, so the effort check reuses it; empty effort costs only a held-settings read. The next request takes a changed or cleared effort without a Desktop restart.
- Every Claude Code subagent's turn, Desktop's or a terminal's, moved or not, keeps its `x-claude-code-agent-id` in `Route.SubagentID` (`subagentTurnOf` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)): a request with the id that offers tools and names no kind, the turn the two settings above take. Claude Code 2.1.295 sends the id from any agent context but the main one; its `x-claude-code-request-class` and `x-claude-code-agent-type` hints go only to a first-party base URL or with `CLAUDE_CODE_GATEWAY_HINT_HEADERS`, so magpie doesn't get them. A Desktop pick or effort that found the turn is trusted, so the body isn't decoded again, and a request without the id isn't decoded at all. The Routing page tags it as Codex's subagents are (`tagKind` in [`routing.js`](../../internal/gui/assets/routing.js)): in the request list, the story, the replay and the tray panel, with the reason `kindWhy` gives Codex's. `Kind` stays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger's `Subagent` keeps the same id, and also marks a subagent's tool-less helper calls, which aren't tagged. A route recorded before this has no id and no tag.
- A request a stand-in of magpie's put on another model than the agent named keeps that model and the rule in `Route.Moved` (`ModelMove{To, Why}` in [`trace.go`](../../internal/gateway/trace.go), set by `move` in `serve`): Claude Desktop's moves (`desktopMove` in [`desktop.go`](../../internal/gateway/desktop.go): `desktop-title`, `desktop-check`, `desktop-gone`, each with a `-first` form when it went to the first model listed for want of a chat turn or a menu pick, `desktop-tier`, `desktop-beside`, `desktop-aside`), `classifier`, `claude-tier`, `stand-in` (the agent's config), `codex-turn` (`codexMemoryStandIn`), `dsh-compact` (`dshCompactTo` in [`dsh_compact.go`](../../internal/gateway/dsh_compact.go): DeepSeek Harness's compaction, known by compaction-basic's ask in `compactAsks` since its llm-pi-ai routes send no `x-deepseek-harness-compact`, goes on `settings.DshCompactModel` when it is enabled, served by its exact id and allowed to the key, else stays as asked with a log line; Musikrv77852 on X, #5395, `TestDshCompactMoved`) and `privacy` (`maskRouteFor`). A subagent's move says its own (`Route.Subagent`), and a group or `Resolve` names no move. The Routing page tags such a row Title or Stand-in (`movedTag`, `movedWhy` in the routing plugin's client.js), in the list, the replay and the tray panel, and says why in the row's title and once in the story; a kind's tag wins, and its story still says the move, but for Desktop's connection check (`connection_check`), whose own story says where it went (`movedSays`). Neo on Discord read Desktop's title on `chatflowsai/claude-opus-5-5` (the only Claude-looking id Desktop is shown, so its own pick) served on the chat's `agentrouter/gpt-6.1-sol` as the model swapped unasked (`TestClaudeDesktopMoveSaysWhy`, `routing-moved-why.test.cjs`). Codex backend rewrites done before `serve` (`codexFollowTo`, `codexMaskRoute`) show the moved model as asked and have no `Moved`.
- A request a stand-in of magpie's put on another model than the agent named keeps that model and the rule in `Route.Moved` (`ModelMove{To, Why}` in [`trace.go`](../../internal/gateway/trace.go), set by `move` in `serve`): Claude Desktop's moves (`desktopMove` in [`desktop.go`](../../internal/gateway/desktop.go): `desktop-title`, `desktop-check`, `desktop-gone`, each with a `-first` form when it went to the first model listed for want of a chat turn or a menu pick, `desktop-tier`, `desktop-beside`, `desktop-aside`), `classifier`, `claude-tier`, `stand-in` (the agent's config), `codex-turn` (`codexMemoryStandIn`), `dsh-compact` (`dshCompactTo` in [`dsh_compact.go`](../../internal/gateway/dsh_compact.go): DeepSeek Harness's compaction, known by compaction-basic's ask in `compactAsks` since its llm-pi-ai routes send no `x-deepseek-harness-compact`, goes on `settings.DshCompactModel` when it is enabled, served by its exact id and allowed to the key, else stays as asked with a log line; Musikrv77852 on X, #5395, `TestDshCompactMoved`), `dsh-compact-rested` (`dshCompactElsewhere`, the same file: a compaction DeepSeek Harness asks on the model it switches away from, before a turn on another, that no compaction model took, whose provider has every key or account out of its allowance or held for a while (`quotaHeld`, `timedHeld`), goes on the same model from another provider, the one with the widest window that is served, allowed to the key and not resting itself (`provider.AutoGroupOf`); dsh fails the switch over a refused compaction, so a WorkBuddy rate limit held every model the user switched to, Trae CN's included (qtwaiter on X, `TestDshCompactLeavesRestedProvider`, `TestDshCompactStaysUnlessRested`). With no such provider it stays as asked, with a log line; a switch from a model nobody else serves still needs the compaction model set) and `privacy` (`maskRouteFor`). A subagent's move says its own (`Route.Subagent`), and a group or `Resolve` names no move. The Routing page tags such a row Title or Stand-in (`movedTag`, `movedWhy` in the routing plugin's client.js), in the list, the replay and the tray panel, and says why in the row's title and once in the story; a kind's tag wins, and its story still says the move, but for Desktop's connection check (`connection_check`), whose own story says where it went (`movedSays`). Neo on Discord read Desktop's title on `chatflowsai/claude-opus-5-5` (the only Claude-looking id Desktop is shown, so its own pick) served on the chat's `agentrouter/gpt-6.1-sol` as the model swapped unasked (`TestClaudeDesktopMoveSaysWhy`, `routing-moved-why.test.cjs`). Codex backend rewrites done before `serve` (`codexFollowTo`, `codexMaskRoute`) show the moved model as asked and have no `Moved`.
- A Chat or Responses client's effort spelled `off` (`reasoning_effort`, or `reasoning.effort`, any case) is read at the top of `serve` as magpie's own off level, `none` (`offAsNone`, plugins#334), and a model asked `<model>:off` as `<model>:none` (`askedAt`): every check and route below reads `none`, a model with an off level is sent its own spelling of it, and one without goes at its least level as `none` asked does (`fitEffort`). `off` itself is never sent on. `saysOff` looks for it without parsing the body, which only a body naming it pays for.
- A level a vendor names in words of its own (`catalog.EffortAliases`: Trae's `light` and `extra_high`, which Our Free Model's plugin lists) is the level it is (`EffortLevel`): `effortOf` reads it as `low` or `xhigh`, and `NearestEffort` places a model's own words by it, so `low` asked of a model listing `light` is sent as `light`, and its `light` as it is (nianshou5 on Discord; `TestNearestEffortTakesVendorWords`, `TestPluginThinkingOff`). dsh and Pi offer such a model's levels as theirs, sent in its words (`modelEffort` in [`agents.go`](../../internal/agent/agents.go); `TestDshOffersTraeNamedLevels`).
- Rules and image inputs are handled here too.
+81 -13
View File
@@ -11,6 +11,11 @@ import (
// it (provider.DshCompactModel) rather than the one it asked for.
const movedDshCompact = "dsh-compact"
// movedDshCompactRested is the reason DSH's compaction went on the same
// model from another provider: the one it asked for rests out of its
// limit (dshCompactElsewhere).
const movedDshCompactRested = "dsh-compact-rested"
// dshCompactTo is the model a DeepSeek Harness compaction (kind, as
// serve recorded it: DSH's mark, or its compaction ask on a route that
// sends no mark) goes on: the one set for DSH's compactions, "" to leave
@@ -28,21 +33,84 @@ func dshCompactTo(r *http.Request, agent, kind, asked string) string {
if to == "" || to == asked {
return ""
}
why := ""
if _, off := idOff(to); off {
why = "it is disabled in magpie"
} else if w := provider.Unserved(to); w != "" {
why = w
} else if who, held := keyHolds(r); held || withGatewayKey(r) {
g, ms, isGroup := provider.FindGroup(to)
p, model, ok := provider.Resolve(to)
if isGroup && !groupGiven(r, who, held, g, ms) || held && !isGroup && (!ok || !modelAllowed(who, p, model)) {
why = "the gateway key may not use it"
}
}
if why != "" {
if why := compactRefused(r, to); why != "" {
log.Printf("gateway: DeepSeek Harness's compaction stays on %s, not %s: %s", asked, to, why)
return ""
}
return to
}
// compactRefused says why a compaction can't be put on to, a model or
// routing group: disabled, not served by that exact id, or not the
// gateway key's to use; "" when it can.
func compactRefused(r *http.Request, to string) string {
if _, off := idOff(to); off {
return "it is disabled in magpie"
}
if w := provider.Unserved(to); w != "" {
return w
}
if who, held := keyHolds(r); held || withGatewayKey(r) {
g, ms, isGroup := provider.FindGroup(to)
p, model, ok := provider.Resolve(to)
if isGroup && !groupGiven(r, who, held, g, ms) || held && !isGroup && (!ok || !modelAllowed(who, p, model)) {
return "the gateway key may not use it"
}
}
return ""
}
// dshCompactElsewhere is the model a DeepSeek Harness compaction asked on
// asked goes on instead, "" to leave it: when every account of asked's
// provider rests out of its limit, the same model (as magpie's found
// groups merge models, provider.AutoGroupOf) from another provider that
// isn't resting, the largest window first. DSH compacts on the session's
// previous model before a switch to one with a smaller window, so a
// switch away from a provider out of its limit failed on that provider's
// refusal, and the model switched to was never asked (qtwaiter on X:
// WorkBuddy's deepseek-v4.1-flash out of its rate, Trae CN's
// deepseek-v4.1-flash picked, "Cannot switch to magpie/trae-cn/
// deepseek-v4.1-flash: context compaction failed: 429 ... WorkBuddy").
// Without magpie DSH's own DeepSeek routes all have 1M windows and never
// compact on a switch. A routing group's request is left: the group
// already goes past a resting member. The cheap checks come first: only
// a DSH compaction on a resting model reads the served list.
func (s *Server) dshCompactElsewhere(r *http.Request, agent, kind, asked string, from provider.Protocol) string {
if agent != "dsh" || kind != KindCompact {
return ""
}
if _, _, isGroup := provider.FindGroup(asked); isGroup {
return ""
}
p, model, ok := provider.Resolve(asked)
if !ok || !s.allResting(p, model, from) {
return ""
}
key := provider.AutoGroupOf(p.ID, model)
best, window := "", -1
for _, e := range provider.Served() {
if e.Group != "" || e.Provider.ID == p.ID || e.Context <= window || provider.AutoGroupOf(e.Provider.ID, e.Model) != key {
continue
}
if compactRefused(r, e.ID) != "" || s.allResting(e.Provider, e.Model, from) {
continue
}
best, window = e.ID, e.Context
}
if best == "" {
log.Printf("gateway: DeepSeek Harness's compaction stays on %s, out of its limit: no other provider serves %s", asked, model)
}
return best
}
// allResting says whether every candidate a request for p's model would
// try rests out of its limit, so it would be answered with the refusal
// held for it (quotaHeld, timedHeld) without asking anyone.
func (s *Server) allResting(p provider.Provider, model string, from provider.Protocol) bool {
cs := s.candidates(p, model, from)
if _, _, ok := quotaHeld(cs); ok {
return true
}
_, _, ok := timedHeld(cs)
return ok
}
+163
View File
@@ -0,0 +1,163 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// wbLimited is WorkBuddy's refusal in qtwaiter's screenshot, as its
// plugin hands it on.
const wbLimited = `{"error":{"code":null,"message":"您的使用量已超出频率限制,将在 2026-11-10 13:28:47 UTC+8 重置,您也可以切换其他模型继续使用。","param":null,"type":"rate_limit_error"}}`
// dshTwoProviders saves wb and trae, both serving deepseek-v4.1-flash on
// fake Anthropic upstreams, wb's refusing every request as out of its
// rate for an hour while limited is set. It returns the models each was
// asked for, in order, by provider.
func dshTwoProviders(t *testing.T, traeServes ...string) (asked func(string) []string) {
t.Helper()
fresh(t)
noRests()
t.Cleanup(noRests)
var mu sync.Mutex
seen := map[string][]string{}
up := func(id string, limited bool) string {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
model := modelOf(body)
mu.Lock()
seen[id] = append(seen[id], model)
mu.Unlock()
if limited {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Retry-After", "3600")
w.WriteHeader(429)
io.WriteString(w, wbLimited)
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"reply","type":"message","role":"assistant","model":"`+model+`","content":[{"type":"text","text":"checkpoint"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}`)
}))
t.Cleanup(s.Close)
return s.URL
}
if err := provider.Save(provider.Provider{ID: "wb", Name: "WorkBuddy", Key: "k", Anthropic: up("wb", true), Models: []string{"deepseek-v4.1-flash", "glm-5.2"}}); err != nil {
t.Fatal(err)
}
if len(traeServes) > 0 {
if err := provider.Save(provider.Provider{ID: "trae-cn", Name: "Trae CN", Key: "k", Anthropic: up("trae-cn", false), Models: traeServes}); err != nil {
t.Fatal(err)
}
}
return func(id string) []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), seen[id]...)
}
}
// dshSend is dshAsk without its 200 check: the status and body.
func dshSend(s *Server, model, last string) (int, string) {
b, _ := json.Marshal(map[string]any{"model": model, "max_tokens": 200, "messages": []any{
map[string]any{"role": "user", "content": "fix the build"},
map[string]any{"role": "assistant", "content": "done"},
map[string]any{"role": "user", "content": last},
}})
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(string(b)))
r.Header.Set("Authorization", "Bearer "+TokenFor("dsh"))
r.Header.Set("User-Agent", dshUA)
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
return w.Code, w.Body.String()
}
// qtwaiter on X: DSH on WorkBuddy's deepseek-v4.1-flash, out of its rate,
// switched to Trae CN's, and every try said "Cannot switch to
// magpie/trae-cn/deepseek-v4.1-flash: context compaction failed: 429 ...
// WorkBuddy: 您的使用量已超出频率限制". DSH compacts on the model it
// switches away from, and magpie answered that compaction with
// WorkBuddy's held refusal. Now it goes to the same model on Trae CN; the
// session's own turns on WorkBuddy are still refused as they were, and
// the Routing page says why the compaction moved.
func TestDshCompactLeavesRestedProvider(t *testing.T) {
asked := dshTwoProviders(t, "deepseek-v4.1-flash", "glm-5.2")
s := New()
if code, body := dshSend(s, "wb/deepseek-v4.1-flash", "go on"); code != 429 || !strings.Contains(body, "频率限制") {
t.Fatalf("WorkBuddy's turn: %d %s", code, body)
}
before := len(asked("wb"))
code, body := dshSend(s, "wb/deepseek-v4.1-flash", dshCompactAsk)
if code != 200 {
t.Fatalf("the compaction for the switch: %d %s", code, body)
}
if got := asked("trae-cn"); len(got) != 1 || got[0] != "deepseek-v4.1-flash" {
t.Fatalf("Trae CN asked for %v, want its deepseek-v4.1-flash", got)
}
if len(asked("wb")) != before {
t.Fatal("WorkBuddy was asked again while it rests")
}
r := lastRoute(s)
if r.Kind != KindCompact || r.Moved == nil || *r.Moved != (ModelMove{To: "trae-cn/deepseek-v4.1-flash", Why: movedDshCompactRested}) {
t.Fatalf("trace: kind %q moved %+v", r.Kind, r.Moved)
}
// a turn of the session's, not a compaction, isn't moved
if code, body := dshSend(s, "wb/deepseek-v4.1-flash", "go on"); code != 429 || !strings.Contains(body, "频率限制") {
t.Fatalf("WorkBuddy's next turn: %d %s", code, body)
}
if got := asked("trae-cn"); len(got) != 1 {
t.Fatalf("a turn went to Trae CN: %v", got)
}
}
// A compaction on a provider that isn't resting stays there, as does one
// no other provider serves the model of (it is refused as it was), and
// one on a model whose stand-in rests too.
func TestDshCompactStaysUnlessRested(t *testing.T) {
t.Run("not resting", func(t *testing.T) {
asked := dshTwoProviders(t, "deepseek-v4.1-flash")
s := New()
if code, _ := dshSend(s, "trae-cn/deepseek-v4.1-flash", dshCompactAsk); code != 200 {
t.Fatalf("status %d", code)
}
if r := lastRoute(s); r.Moved != nil {
t.Fatalf("moved %+v", r.Moved)
}
if len(asked("trae-cn")) != 1 || len(asked("wb")) != 0 {
t.Fatalf("wb %v, trae %v", asked("wb"), asked("trae-cn"))
}
})
t.Run("no other provider", func(t *testing.T) {
asked := dshTwoProviders(t, "glm-5.2")
s := New()
dshSend(s, "wb/deepseek-v4.1-flash", "go on")
if code, body := dshSend(s, "wb/deepseek-v4.1-flash", dshCompactAsk); code != 429 || !strings.Contains(body, "频率限制") {
t.Fatalf("%d %s", code, body)
}
if len(asked("trae-cn")) != 0 {
t.Fatalf("Trae CN asked for %v", asked("trae-cn"))
}
})
t.Run("other agent", func(t *testing.T) {
asked := dshTwoProviders(t, "deepseek-v4.1-flash")
s := New()
dshSend(s, "wb/deepseek-v4.1-flash", "go on")
b, _ := json.Marshal(map[string]any{"model": "wb/deepseek-v4.1-flash", "max_tokens": 200, "messages": []any{
map[string]any{"role": "user", "content": dshCompactAsk},
}})
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(string(b)))
r.Header.Set("Authorization", "Bearer "+TokenFor("opencode"))
r.Header.Set("x-deepseek-harness-compact", "1")
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 429 || len(asked("trae-cn")) != 0 {
t.Fatalf("%d, Trae CN asked for %v", w.Code, asked("trae-cn"))
}
})
}
+6
View File
@@ -2518,6 +2518,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
asked = m
move(m, movedDshCompact)
}
// and, its provider out of its limit, on the same model from another
// provider: DSH compacts on the model it switches away from
if m := s.dshCompactElsewhere(r, agent, call.Kind, asked, from); m != "" {
asked = m
move(m, movedDshCompactRested)
}
// a Codex subagent on the model set for Codex's subagents, whatever
// its lead asked for (willz on Discord), and a Claude Desktop
// subagent's tool turn on the one set for Desktop's; one already put
@@ -3723,6 +3723,7 @@ function routingPage(part) {
case "codex-turn": return t("{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.", v);
case "codex-follow": return t("{agent} asked for {model}, one of its own default models, for its memories, and its config names no model for them; magpie served it on {to}, the model of its conversation.", v);
case "dsh-compact": return t("{agent} asked for {model} to compact its conversation; magpie served it on {to}, the model set for its compaction.", v);
case "dsh-compact-rested": return t("{agent} asked for {model} to compact its conversation, and its provider is out of its limit; magpie served it on {to}, the same model from another provider.", v);
case "privacy": return t("Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.", v);
default: return t("magpie served it on {to} in place of {model}.", v);
}
@@ -537,6 +537,7 @@ magpie.strings({
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} 为它自己的调用请求了 {model},但 magpie 不提供它;magpie 让 {to} 来处理,即它上一轮所用的模型。",
"{agent} asked for {model}, one of its own default models, for its memories, and its config names no model for them; magpie served it on {to}, the model of its conversation.": "{agent} 为它的记忆请求了它自己的默认模型 {model},而它的配置没有为记忆指定模型;magpie 让 {to} 来处理,即它这段对话所用的模型。",
"{agent} asked for {model} to compact its conversation; magpie served it on {to}, the model set for its compaction.": "{agent} 请求用 {model} 压缩它的对话;magpie 让 {to} 来处理,即为它的压缩设定的模型。",
"{agent} asked for {model} to compact its conversation, and its provider is out of its limit; magpie served it on {to}, the same model from another provider.": "{agent} 请求用 {model} 压缩它的对话,而它的服务商已超出限额;magpie 让 {to} 来处理,即另一家服务商的同一模型。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "脱敏会改动这个请求,所以 magpie 把它原样发给了 {to},即在 设置 › 隐私 里为此设定的模型。",
"magpie served it on {to} in place of {model}.": "magpie 让 {to} 代替 {model} 处理了它。",
"Stand-in": "替代",
@@ -1259,6 +1260,7 @@ magpie.strings({
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} 為它自己的呼叫請求了 {model},但 magpie 不提供它;magpie 讓 {to} 來處理,即它上一輪所用的模型。",
"{agent} asked for {model}, one of its own default models, for its memories, and its config names no model for them; magpie served it on {to}, the model of its conversation.": "{agent} 為它的記憶請求了它自己的預設模型 {model},而它的設定沒有為記憶指定模型;magpie 讓 {to} 來處理,即它這段對話所用的模型。",
"{agent} asked for {model} to compact its conversation; magpie served it on {to}, the model set for its compaction.": "{agent} 請求用 {model} 壓縮它的對話;magpie 讓 {to} 來處理,即為它的壓縮設定的模型。",
"{agent} asked for {model} to compact its conversation, and its provider is out of its limit; magpie served it on {to}, the same model from another provider.": "{agent} 請求用 {model} 壓縮它的對話,而它的服務商已超出限額;magpie 讓 {to} 來處理,即另一家服務商的同一模型。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "去識別化會改動這個請求,所以 magpie 把它原樣送給了 {to},即在 設定 › 隱私 裡為此設定的模型。",
"magpie served it on {to} in place of {model}.": "magpie 讓 {to} 代替 {model} 處理了它。",
"Stand-in": "替代",
@@ -1979,6 +1981,7 @@ magpie.strings({
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} は自身の呼び出しに magpie が提供していない {model} をリクエストしました。magpie は {to}(直前のターンに応答したモデル)で応答しました。",
"{agent} asked for {model}, one of its own default models, for its memories, and its config names no model for them; magpie served it on {to}, the model of its conversation.": "{agent} はメモリのために自身のデフォルトモデル {model} をリクエストしましたが、設定でメモリ用のモデルが指定されていません。magpie は {to}(会話のモデル)で応答しました。",
"{agent} asked for {model} to compact its conversation; magpie served it on {to}, the model set for its compaction.": "{agent} は会話の圧縮に {model} をリクエストしました。magpie は {to}(圧縮用に設定されたモデル)で応答しました。",
"{agent} asked for {model} to compact its conversation, and its provider is out of its limit; magpie served it on {to}, the same model from another provider.": "{agent} は会話の圧縮に {model} をリクエストしましたが、そのプロバイダーは上限に達しています。magpie は {to}(別のプロバイダーの同じモデル)で応答しました。",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "マスキングでこのリクエストが変わるため、magpie はそのまま {to}(設定 › プライバシーで指定されたモデル)に送りました。",
"magpie served it on {to} in place of {model}.": "magpie は {model} の代わりに {to} で応答しました。",
"Stand-in": "代替",
@@ -2701,6 +2704,7 @@ magpie.strings({
"{agent} asked for {model} for a call of its own, which magpie doesn't serve; magpie served it on {to}, the model its last turn was answered on.": "{agent} hat für einen eigenen Aufruf {model} angefordert, das magpie nicht anbietet; magpie hat ihn mit {to} beantwortet, dem Modell, das seinen letzten Zug beantwortet hat.",
"{agent} asked for {model}, one of its own default models, for its memories, and its config names no model for them; magpie served it on {to}, the model of its conversation.": "{agent} hat für seine Erinnerungen {model} angefordert, eines seiner eigenen Standardmodelle, und seine Konfiguration legt dafür kein Modell fest; magpie hat sie mit {to} beantwortet, dem Modell seiner Unterhaltung.",
"{agent} asked for {model} to compact its conversation; magpie served it on {to}, the model set for its compaction.": "{agent} hat {model} angefordert, um seine Unterhaltung zu komprimieren; magpie hat sie mit {to} beantwortet, dem dafür eingestellten Modell.",
"{agent} asked for {model} to compact its conversation, and its provider is out of its limit; magpie served it on {to}, the same model from another provider.": "{agent} hat {model} angefordert, um seine Unterhaltung zu komprimieren, doch sein Anbieter ist über seinem Limit; magpie hat sie mit {to} beantwortet, demselben Modell eines anderen Anbieters.",
"Masking would have changed this request, so magpie sent it as written to {to}, the model set for that in Settings › Privacy.": "Die Maskierung hätte diese Anfrage verändert, daher hat magpie sie unverändert an {to} gesendet, das dafür unter Einstellungen › Datenschutz festgelegte Modell.",
"magpie served it on {to} in place of {model}.": "magpie hat sie mit {to} statt {model} beantwortet.",
"Stand-in": "Ersatz",
+26 -13
View File
@@ -3,7 +3,9 @@
// latest model, so switching away from a model whose provider is out of its
// limit failed on the compaction. Its row has a square for the model its
// compactions go on, in the app's own picker; the Routing story says why a
// compaction went there. All APIs are faked.
// compaction went there. qtwaiter on X: with nothing set, a compaction on
// a provider out of its limit goes to the same model from another
// provider, and the story says that too. All APIs are faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -32,6 +34,8 @@ const seat = { id: "fake", provider: "fake", name: "Fake", who: "Test key", kind
const routes = [
{ id: 1, seq: 1, time: at(0), agent: "dsh", model: "fake/m1", provider: "fake", kind: "compact", moved: { to: "fake/m2", why: "dsh-compact" },
order: [seat], tries: [{ id: "fake", model: "m2", start: at(0), done: true, status: 200, ms: 900 }], done: true, status: 200, ms: 900, tokens: 1200 },
{ id: 2, seq: 2, time: at(1), agent: "dsh", model: "workbuddy/deepseek-v4.1-flash", provider: "trae-cn", kind: "compact", moved: { to: "trae-cn/deepseek-v4.1-flash", why: "dsh-compact-rested" },
order: [{ ...seat, id: "trae-cn", provider: "trae-cn", name: "Trae CN", model: "deepseek-v4.1-flash" }], tries: [{ id: "trae-cn", model: "deepseek-v4.1-flash", start: at(1), done: true, status: 200, ms: 900 }], done: true, status: 200, ms: 900, tokens: 1200 },
];
function server(lang, fixture) {
@@ -50,7 +54,7 @@ function server(lang, fixture) {
}
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait")) return new Promise(() => {});
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes });
return json({ mine: true, now: now.toISOString(), seq: 2, totals: { requests: 2, rerouted: 0, errors: 0 }, routes });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/gateway/session-titles") return json({ titles: {} });
@@ -70,15 +74,20 @@ function server(lang, fixture) {
// Expected reader-facing words, independent of the translation lookup.
const W = {
en: { unset: "compaction model: the session's model", def: "Default", note: "each compaction on the session's model", set: "compaction model: M2",
moved: "DeepSeek Harness asked for fake/m1 to compact its conversation; magpie served it on fake/m2, the model set for its compaction." },
moved: "DeepSeek Harness asked for fake/m1 to compact its conversation; magpie served it on fake/m2, the model set for its compaction.",
rested: "DeepSeek Harness asked for workbuddy/deepseek-v4.1-flash to compact its conversation, and its provider is out of its limit; magpie served it on trae-cn/deepseek-v4.1-flash, the same model from another provider." },
zh: { unset: "压缩模型:会话所用的模型", def: "默认", note: "每次压缩都用会话所用的模型", set: "压缩模型:M2",
moved: "DeepSeek Harness 请求用 fake/m1 压缩它的对话;magpie 让 fake/m2 来处理,即为它的压缩设定的模型。" },
moved: "DeepSeek Harness 请求用 fake/m1 压缩它的对话;magpie 让 fake/m2 来处理,即为它的压缩设定的模型。",
rested: "DeepSeek Harness 请求用 workbuddy/deepseek-v4.1-flash 压缩它的对话,而它的服务商已超出限额;magpie 让 trae-cn/deepseek-v4.1-flash 来处理,即另一家服务商的同一模型。" },
"zh-TW": { unset: "壓縮模型:工作階段所用的模型", def: "預設", note: "每次壓縮都用工作階段所用的模型", set: "壓縮模型:M2",
moved: "DeepSeek Harness 請求用 fake/m1 壓縮它的對話;magpie 讓 fake/m2 來處理,即為它的壓縮設定的模型。" },
moved: "DeepSeek Harness 請求用 fake/m1 壓縮它的對話;magpie 讓 fake/m2 來處理,即為它的壓縮設定的模型。",
rested: "DeepSeek Harness 請求用 workbuddy/deepseek-v4.1-flash 壓縮它的對話,而它的服務商已超出限額;magpie 讓 trae-cn/deepseek-v4.1-flash 來處理,即另一家服務商的同一模型。" },
ja: { unset: "圧縮モデル:セッションのモデル", def: "デフォルト", note: "圧縮はいつもセッションのモデルで行う", set: "圧縮モデル:M2",
moved: "DeepSeek Harness は会話の圧縮に fake/m1 をリクエストしました。magpie は fake/m2(圧縮用に設定されたモデル)で応答しました。" },
moved: "DeepSeek Harness は会話の圧縮に fake/m1 をリクエストしました。magpie は fake/m2(圧縮用に設定されたモデル)で応答しました。",
rested: "DeepSeek Harness は会話の圧縮に workbuddy/deepseek-v4.1-flash をリクエストしましたが、そのプロバイダーは上限に達しています。magpie は trae-cn/deepseek-v4.1-flash(別のプロバイダーの同じモデル)で応答しました。" },
de: { unset: "Komprimierungsmodell: das Modell der Sitzung", def: "Standard", note: "jede Komprimierung auf dem Modell der Sitzung", set: "Komprimierungsmodell: M2",
moved: "DeepSeek Harness hat fake/m1 angefordert, um seine Unterhaltung zu komprimieren; magpie hat sie mit fake/m2 beantwortet, dem dafür eingestellten Modell." },
moved: "DeepSeek Harness hat fake/m1 angefordert, um seine Unterhaltung zu komprimieren; magpie hat sie mit fake/m2 beantwortet, dem dafür eingestellten Modell.",
rested: "DeepSeek Harness hat workbuddy/deepseek-v4.1-flash angefordert, um seine Unterhaltung zu komprimieren, doch sein Anbieter ist über seinem Limit; magpie hat sie mit trae-cn/deepseek-v4.1-flash beantwortet, demselben Modell eines anderen Anbieters." },
};
const row = '.row.agent[data-id="dsh"]';
@@ -153,12 +162,16 @@ for (const engine of engines) {
fixture.state = fresh();
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-req").first().waitFor();
assert((await page.locator(".rt-req").first().getAttribute("title")).includes("\n" + w.moved), "the row's title says why");
await page.locator(".rt-req").first().evaluate((e) => e.click());
await page.waitForFunction(() => document.querySelector(".rt-req")?.getAttribute("aria-pressed") === "true");
const story = await page.locator(".rt-steps").textContent();
assert.equal(story.split(w.moved).length - 1, 1, `${w.moved}\nonce in\n${story}`);
await page.locator(".rt-req").nth(1).waitFor();
for (const why of [w.moved, w.rested]) {
const titles = await page.locator(".rt-req").evaluateAll((es) => es.map((e) => e.getAttribute("title") || ""));
const i = titles.findIndex((x) => x.includes("\n" + why));
assert(i >= 0, `no row's title says\n${why}\nin\n${titles.join("\n--\n")}`);
await page.locator(".rt-req").nth(i).evaluate((e) => e.click());
await page.waitForFunction((n) => document.querySelectorAll(".rt-req")[n]?.getAttribute("aria-pressed") === "true", i);
const story = await page.locator(".rt-steps").textContent();
assert.equal(story.split(why).length - 1, 1, `${why}\nonce in\n${story}`);
}
assert.deepEqual(errors, []);
});
}