gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)

P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
This commit is contained in:
yetone
2026-10-15 01:32:12 +08:00
parent 8f4d091c6e
commit eb7199e120
27 changed files with 2197 additions and 2090 deletions
+2 -2
View File
@@ -75,7 +75,7 @@ recorded as a prediction failure (`noPrediction`).
- 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 `<system-reminder …>` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's `<environment_context>`, `<user_instructions>`, `<turn_aborted>`, `<user_shell_command>`, `<subagent_notification>` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's `<task-notification>`, `<subagent-notification>`, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's `<plugin_reference>`; the Codex app's `<in-app-browser-context …>`. 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 rule's members go first (`ruleOver`, `applyRule`): the member it names, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`.
- 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`.
- The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `routing.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`.
- The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.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$\<distro>` or `\\wsl.localhost\<distro>` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: <path>` (its `<`/`>` as entities; ` (was <old>)` after a change dropped), Codex's `<environment_context>` `<cwd>`, Pi's `<cwd>` in the system prompt, and OpenCode's `Working directory:` inside its `<env>` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule).
- A pause rule (`Rule.Pause`, `pause=<model>`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause=<model> except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`.
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.
@@ -108,7 +108,7 @@ recorded as a prediction failure (`noPrediction`).
- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or more than `longestWritten` (7 days) off isn't read. One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). Out of credit or quota on a model that costs credits, where the subscription serves other models free (`catalog.Model.Free`: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; `Provider.PaidBesideFree`), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, `TestOutOfCreditLeavesFreeModels`). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (`brokeWords`), not a rate limit, on the built-in's raw body and the plugin's `insufficient_quota` alike (`TestCreditsExhaustedIsOutOfCredit`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.
- An account resting out of its window (a Claude account by the time Claude Code's refusal named, `resets`, or any by `window`) is back once magpie's reading of its windows (`provider.Allowances`) finds it full till sooner: the window used below `SpentShareOf`, or its reset passed, with no other window over the same models still full. The reading tells `provider.OnRenewed` as the account's `UsageAgent` and user, and `renewed` lifts that account's rests out of quota or by `window`; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in `restingOf`.
- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more.
- A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `routing.js`, #1960, `routing-model-rest.test.cjs`).
- A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`).
- A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests.
- Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949).
- A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name.
+7 -7
View File
@@ -15,9 +15,9 @@ three.
| Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. | [`backend.go`](../../internal/gui/backend.go) |
| API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |
| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) |
| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions and Library pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library and Routing pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway page (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) |
| No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) |
## Runtime path
@@ -58,7 +58,7 @@ refresh was requested this time; a failed read retains its failure notice.
Usage rows and aggregates use `Record.Decode` and `DecodeOf` in
[`internal/usage/usage.go`](../../internal/usage/usage.go). Routing uses
`decodeOf` in [`routing.js`](../../internal/gui/assets/routing.js); Usage
`decodeOf` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js); Usage
rows use `ledDecode` in [`app.js`](../../internal/gui/assets/app.js).
When an answer follows reasoning, only answer tokens are timed from the
@@ -109,7 +109,7 @@ cover the calculation, cache round trip, translated streams and both pages.
### Routing purpose filter
The request heading's purpose menu in [`routing.js`](../../internal/gui/assets/routing.js)
The request heading's purpose menu in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)
uses `openProtoMenu`'s live checkbox selection: each tick immediately shows
requests matching any selected purpose, with the menu kept open. An empty
selection, All purposes or Clear filter restores every purpose without
@@ -128,7 +128,7 @@ single choice sent to the ledger API. See `purpose-filter.test.cjs` and
### Routing mode chip
The stage's chip and the Accounts and keys heading in
[`routing.js`](../../internal/gui/assets/routing.js) name how a route
[`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js) name how a route
routes only where that can be changed: a group, or a provider in
`/api/groups`' `pools` (two or more accounts or keys on). There they are
`.rt-go` controls (`goTo`, `goRouting`) that bring the group's card or the
@@ -143,7 +143,7 @@ See `routing-mode-goes.test.cjs`.
Three or more API keys, or three or more accounts, of one provider standing
next to each other for one model (same fixed effort, fallback and
group-in-group heading) fold into one stage row, `li.rt-fold` in
[`routing.js`](../../internal/gui/assets/routing.js) (`FOLD_AT`,
[`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js) (`FOLD_AT`,
`rebuild`). It shows the count and their state together: the one that is
lit and what it is doing, how many are available and how many rest
(`together`). Requests that land on a folded seat fly to the fold
@@ -171,7 +171,7 @@ gateway's order and choice of seat don't change. Two stay two rows. See
A subscription account's row in Accounts and keys shows each of its
windows under the one figure routing went by, with when each resets
("5 hours 40% used · resets in 2h"), as the Usage page reads them (#1833).
`cardOf` in [`routing.js`](../../internal/gui/assets/routing.js) matches
`cardOf` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js) matches
the route's account to app.js's `quotas`: a `subscription` card of this
computer (no `from`) whose provider is the account's `agent` (a plugin's
provider id) or its provider, and whose user is the account's, ignoring
+20 -3
View File
@@ -8,8 +8,8 @@ turned off. `plugins.yml` says which are on. This page describes P0 (the
runtime, the file and the window's switch) and P1 (the window's kernel: a
plugin's page, its error boundary, the kit it draws with and its settings
form, with the Gateway page as the first plugin to draw its own page), and
P2 so far (a page moved out of the core whole: its code, styles and words,
starting with Sessions). OpenCode plugins (npm packages in
P2 so far (a page moved out of the core whole: its code, styles and words:
Sessions, Library and Routing). OpenCode plugins (npm packages in
the plugin host) are a different thing; see
[provider and plugin ownership](provider-plugins.md) and
[gateway middleware](gateway-middleware.md).
@@ -24,7 +24,7 @@ the plugin host) are a different thing; see
| Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) |
| Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), and `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`). Its one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
The boundary is checked by `TestPluginsImportOnlyCore`: no package outside
`plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never
@@ -113,6 +113,23 @@ says one of its words, which goes back to i18n.js.
are hidden, and `close`, `dirty` and `discard` are what `show()` asks
before the reader leaves it. `window.loadLibrary`, `redrawLibrary`,
`closeLibraryModal`, `libraryDirty` and `discardLibrary` are gone.
- **Routing** (`plugins/routing`, `Client: i18n.js, routing.css,
client.js`): the page that was `routing.js`, Essential. Its part's `html`
is the page's head and boxes that were index.html's; the rest of the page
is drawn by `routingPage`, run at `mount` because it builds on app.js. It
keeps itself after that, as it did (its own `hidden`, the language, the
window's focus), so its hooks are only `dirty` and `discard`, a routing
group being edited, which `show()` and the window's close ask through
`magpie.call("routing", …)`: `window.routingDirty` and `discardRouting`
are gone. Its tab in the tray panel and the panel's section are marked
`data-feature="routing"`. What other pages use of it is still on
`window` (`openRoute` for context.js; `kindName`, `swapWhy` and
`routedWhy` for Usage's Requests; `newGroupWith` for Providers;
`panelRoutingShown` for the panel). With the plugin off, what leads to
the page goes with it: the nav and panel tabs, the guide's Open Routing,
Providers' "Make a routing group of …" (`data-feature="routing"`), the
Usage list's View routing and its time as a link, and the context card's
Latest request; a panel left on its Routing tab shows Agents.
## Source of truth and composing
+2 -2
View File
@@ -527,11 +527,11 @@ func TestAntigravityQuotaOnAClaudeCodeTurnStaysQuota(t *testing.T) {
// The Routing page says the note apart from Antigravity's words, in its own
// language, only when it knows the very words the gateway adds.
func TestAntigravityTurnedAwayHintIsTheRoutingPages(t *testing.T) {
b, err := os.ReadFile(filepath.Join("..", "gui", "assets", "routing.js"))
b, err := os.ReadFile(filepath.Join("..", "gui", "assets", "plugins", "routing", "client.js"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), quote(antigravityTurnedAwayHint)) {
t.Fatal("routing.js doesn't know the note the gateway adds to Antigravity's refusal")
t.Fatal("plugins/routing/client.js doesn't know the note the gateway adds to Antigravity's refusal")
}
}
+1 -1
View File
@@ -99,7 +99,7 @@ func (s *Server) antigravityForeseen(p provider.Provider, from provider.Protocol
// antigravityTurnedAwayHint is what magpie adds to Antigravity's words, after
// " — ", for the agent and the Routing page, which says it apart from them in
// its own language (routing.js AG_TURNED_AWAY).
// its own language (routing/client.js AG_TURNED_AWAY).
const antigravityTurnedAwayHint = "Antigravity answers this 429 to the system prompt of Claude Code and the Claude Agent SDK (Claude Desktop's chats) whatever quota is left, so it is not a quota and waiting won't help; use another provider for these chats, or put one after Antigravity in a routing group"
// turnedAwayStatus is what the agent is told when nobody is left to answer
+1 -1
View File
@@ -244,7 +244,7 @@ func TestLoopGuardLeavesOrdinaryRepliesAlone(t *testing.T) {
var texts = map[string]string{}
for _, f := range []string{
"internal/gateway/gateway.go", "internal/gateway/fallback.go", "internal/gateway/anthropic.go",
"internal/gui/assets/app.js", "internal/gui/assets/i18n.js", "internal/gui/assets/app.css", "internal/gui/assets/routing.js", "internal/gui/assets/plugins/sessions/client.js", "internal/gui/assets/index.html",
"internal/gui/assets/app.js", "internal/gui/assets/i18n.js", "internal/gui/assets/app.css", "internal/gui/assets/plugins/routing/client.js", "internal/gui/assets/plugins/sessions/client.js", "internal/gui/assets/index.html",
"docs/code-standards.md", "LESSONS.md", "docs/subsystems/gateway-routing.md", "docs/subsystems/providers-accounts.md",
"go.sum",
} {
+22 -15
View File
@@ -1638,6 +1638,7 @@ function guideCard(g) {
}
const open = el("button", "text guide-open", t("Open Routing"));
open.type = "button";
open.dataset.feature = "routing";
open.onclick = (e) => {
e.stopPropagation();
if (mode === "window") show("routing");
@@ -5131,6 +5132,7 @@ function keptNote(m) {
} else {
words.append(el("span", "", t("{provider} is used only through routing groups, and {model} is in none, so no agent can use it. Make a group of it, or untick “Only through routing groups” in {provider}'s models.", { provider: m.provider, model })));
act.textContent = t("Make a routing group of it");
act.dataset.feature = "routing"; // made on the Routing page
act.onclick = (ev) => {
ev.stopPropagation();
closePicker();
@@ -7423,7 +7425,7 @@ async function cancelEdit(keep) {
return true;
}
window.addEventListener("beforeunload", (e) => {
if (providerDirty() || window.routingDirty?.() || ((view === "library" || importing || importingApps) && modalFormDirty())) {
if (providerDirty() || magpie.call("routing", "dirty") || ((view === "library" || importing || importingApps) && modalFormDirty())) {
e.preventDefault();
e.returnValue = "";
}
@@ -10420,6 +10422,7 @@ function renderModels(p) {
if (!p.unlisted) { lost.append(" " + t("Once saved, make a group of them in Routing.")); return; }
for (const id of none.slice(0, 4)) {
const b = el("button", "text action", t("Make a routing group of {model}", { model: id }));
b.dataset.feature = "routing"; // made on the Routing page
b.onclick = (ev) => { if (mode !== "window") api("window/main?view=routing&newgroup=" + encodeURIComponent(p.id + "/" + id), {}); else window.newGroupWith?.(p.id + "/" + id, "", ev); };
lost.append(b);
}
@@ -10992,7 +10995,7 @@ const ROUTINGS = [
];
// weight is a key's share: offered for a provider with keys only
const routingsOf = (p) => p.account ? ROUTINGS.filter(([id]) => id !== "weight") : ROUTINGS;
// as on the Routing page's list of these (routing.js AFF_OPTS)
// as on the Routing page's list of these (routing/client.js AFF_OPTS)
const STAYS = [
["", "Auto", "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh."],
["session", "Session", "A conversation stays with the account or key that answered it for the whole session, while it can answer."],
@@ -11003,7 +11006,7 @@ const STAYS = [
// what one rate limited while it still has quota does then (provider.Sink,
// 01huadalang): keeps its place, back first once its rest ends, or goes to
// the back of the order so the load goes round — as on the Routing page
// (routing.js SINK_OPTS)
// (routing/client.js SINK_OPTS)
const SINKS = [
[false, "Keeps its place", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again."],
[true, "Goes to the back", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts."],
@@ -15844,7 +15847,7 @@ if (mode === "panel") document.addEventListener("visibilitychange", () => {
// The tray panel is four tabs over the one page: the agents, the allowances
// of every subscription and key (the "usage" tab, as it was named before),
// what the requests add up to (the "stats" tab, the window's Requests made
// small) and the gateway's latest requests (routing.js draws those). The saved
// small) and the gateway's latest requests (routing/client.js draws those). The saved
// profiles open from Profiles at the Agents tab's foot, over the list (a tab
// of their own was one too many). The tab is remembered.
const profBtn = $("#profBtn"), profBox = $(".profiles");
@@ -15882,9 +15885,10 @@ let panelTab = "agents";
try { panelTab = localStorage.getItem("magpie.panelTab") || "agents"; } catch {}
function setPanelTab(tab) {
const tabs = $("#ptabs");
// no usage to show, no tab for it (nor for profiles: they open from the foot)
// no usage to show, no tab for it (nor for profiles: they open from the
// foot), nor for a page a built-in plugin switched off (Routing)
const b = tabs.querySelector(`[data-ptab="${tab}"]`);
if (!b || b.hidden) tab = "agents";
if (!b || b.hidden || featureHides(b)) tab = "agents";
closeProfiles();
if (tab !== "usage") panelPeek = "";
panelTab = tab;
@@ -17842,7 +17846,8 @@ function ledDetail(r, cols) {
if (Number.isFinite(r.ms) && r.ms > 0) add("Duration", (r.source === "log" ? "≈" : "") + ledTook(r.ms));
// the way it was routed: the row's time links there too, which reads as
// a time rather than a link (#799)
if (r.route_id) {
// (with the Routing page switched off there is nowhere to see it)
if (r.route_id && !featuresOff.has("routing")) {
const go = el("button", "text led-route-link", t("View routing"));
go.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); };
const dd = el("dd");
@@ -18749,7 +18754,7 @@ const LED_COLS = [
];
// the tokens a reply was seen to write and the ms it took, as
// usage.DecodeOf and routing.js's decodeOf tell them: one that reasoned
// usage.DecodeOf and routing/client.js's decodeOf tell them: one that reasoned
// counts its answer from its first text, its reasoning written before
// the stream showed any (tony on Discord); null when it tells no speed.
// A reply held back and let go in a burst at its end tells none (John on
@@ -19002,8 +19007,9 @@ function renderLedger() {
tr.append(c);
return c;
};
const when = r.route_id ? el("button", "text led-route-link", ledTime(r.t)) : ledTime(r.t);
if (r.route_id) {
const routed = r.route_id && !featuresOff.has("routing"); // the Routing page there to open it on
const when = routed ? el("button", "text led-route-link", ledTime(r.t)) : ledTime(r.t);
if (routed) {
when.title = t("View routing");
// the link opens the route, not the row's details as well
when.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); };
@@ -24550,9 +24556,9 @@ async function show(v) {
if (view === "library" && modalFormDirty() && !(await confirmDiscard())) return false;
if (view === "library") magpie.call("library", "close"); else closeModal();
}
if (view === "routing" && window.routingDirty?.()) {
if (view === "routing" && magpie.call("routing", "dirty")) {
if (!(await confirmDiscard())) return false;
window.discardRouting?.();
magpie.call("routing", "discard");
}
if (view === "library" && magpie.call("library", "dirty")) {
if (!(await confirmDiscard())) return false;
@@ -24562,7 +24568,7 @@ async function show(v) {
view = v;
// the page the reader leaves is the one the window opens on next (keptView)
if (mode === "window") { try { localStorage.setItem("magpie.lastView", v); } catch { /* not kept */ } }
const title = magpie.page(v)?.title ?? ({ agents: "Agents", providers: "Providers", routing: "Routing", usage: "Usage", plugins: "Plugins", settings: "Settings" })[v];
const title = magpie.page(v)?.title ?? ({ agents: "Agents", providers: "Providers", usage: "Usage", plugins: "Plugins", settings: "Settings" })[v];
$("#pageTitle").dataset.en = title;
$("#pageTitle").textContent = t(title);
if (mode === "window") {
@@ -24576,7 +24582,7 @@ async function show(v) {
$("#prefs").classList.toggle("on", v === "settings");
if (v === "settings") $("#prefs").setAttribute("aria-current", "page"); else $("#prefs").removeAttribute("aria-current");
navSubs();
for (const id of ["agents", "providers", "routing", "usage", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id;
for (const id of ["agents", "providers", "usage", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id;
// back to where the reader was in it, and again once it has what it loads
const back = () => backToReader($("#view-" + v));
requestAnimationFrame(back);
@@ -24638,6 +24644,7 @@ function applyFeatures(list) {
if (off.size === featuresOff.size && [...off].every((id) => featuresOff.has(id))) return;
featuresOff = off;
featureStyle();
if (mode === "panel" && panelTab !== "agents") setPanelTab(panelTab); // its tab may be gone
if (mode !== "window") return;
navHides();
if (featureHides($(`#nav button[data-view="${view}"]`))) show(gatewayMode ? "providers" : "agents");
@@ -25733,7 +25740,7 @@ navHides(); // the pages built-in plugins switched off have, from boot.js
// from the tray or a reload) first, then the one kept; a page gateway mode
// leaves out, or one there is no longer, gives way to the first page.
// the pages the window can open on besides the first (Agents)
const OPEN_VIEWS = ["providers", "routing", "usage", "plugins", "settings", ...magpie.pages()];
const OPEN_VIEWS = ["providers", "usage", "plugins", "settings", ...magpie.pages()];
function keptView() {
const asked = params.get("view");
if (asked === "agents" || OPEN_VIEWS.includes(asked)) return asked;
+2 -1
View File
@@ -858,6 +858,7 @@
if (a.latestId) {
const go = el("button", "text", t("Latest request"));
go.type = "button";
go.dataset.feature = "routing"; // it opens on the Routing page
go.onclick = () => window.openRoute(a.latestId, a.latestTime, { context: true }).catch((e) => status(e.message, "err"));
foot.append(go);
}
@@ -894,7 +895,7 @@
still: true, cache, place: "session",
series: s.points,
crumbs: [agentLabel(s.agent), s.title || s.key.slice(0, 12), t("latest request")],
onPoint: (pt) => window.openRoute(pt.id, pt.time, { context: true }).catch((e) => status(e.message, "err")),
onPoint: (pt) => { if (!featuresOff.has("routing")) window.openRoute(pt.id, pt.time, { context: true }).catch((e) => status(e.message, "err")); },
}));
}
return box;
File diff suppressed because it is too large Load Diff
+6 -13
View File
@@ -9,7 +9,7 @@
<script src="theme.js"></script>
<script src="omarchy.js"></script>
<link rel="stylesheet" href="app.css">
<link rel="stylesheet" href="routing.css">
<link rel="stylesheet" href="plugins/routing/routing.css">
<link rel="stylesheet" href="plugins/library/library.css">
<link rel="stylesheet" href="plugins.css">
<link rel="stylesheet" href="plugins/sessions/sessions.css">
@@ -51,7 +51,7 @@
<button data-view="library" data-feature="library"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3.5h9v13H5a1.5 1.5 0 0 1 0-3h9"/></g></svg><span data-t>Library</span></button>
<span class="nav-gl" data-t>Models</span>
<button data-view="providers"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="10" r="3"/><path d="M10 10h7M14 10v3M16.5 10v2"/></g></svg><span data-t>Providers</span></button>
<button data-view="routing"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h5l4-5h5M8 10l4 5h5M14.5 3l2.5 2-2.5 2M14.5 13l2.5 2-2.5 2"/></g></svg><span data-t>Routing</span></button>
<button data-view="routing" data-feature="routing"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h5l4-5h5M8 10l4 5h5M14.5 3l2.5 2-2.5 2M14.5 13l2.5 2-2.5 2"/></g></svg><span data-t>Routing</span></button>
<button data-view="gateway" data-feature="gateway"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="14" height="5" rx="1.5"/><rect x="3" y="11" width="14" height="5" rx="1.5"/><path d="M6 6.5h.01M6 13.5h.01"/></g></svg><span data-t>Gateway</span></button>
<span class="nav-gl" data-t>Insights</span>
<button data-view="usage"><svg class="nav-ic" viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 16V9M8 16V5M12 16v-5M16 16V7"/></g></svg><span data-t>Usage</span></button>
@@ -87,7 +87,7 @@
<button type="button" data-ptab="agents"><span data-t>Agents</span><em id="ptabN"></em></button>
<button type="button" data-ptab="usage"><span data-t>Allowances</span></button>
<button type="button" data-ptab="stats"><span data-t>Usage</span></button>
<button type="button" data-ptab="routing"><span data-t>Routing</span></button>
<button type="button" data-ptab="routing" data-feature="routing"><span data-t>Routing</span></button>
</nav>
<main class="view" id="view-agents">
@@ -98,7 +98,7 @@
<button class="text" id="save" data-t>+ Save current</button>
</section>
<section class="panel-quota" id="panelQuota" hidden></section>
<section class="panel-routing" id="panelRouting" hidden></section>
<section class="panel-routing" id="panelRouting" data-feature="routing" hidden></section>
<section class="panel-usage" id="panelUsage" hidden></section>
</main>
@@ -124,14 +124,6 @@
<!-- the pages plugins add (kernel.js) go here, in the order they register -->
<template data-slot="page"></template>
<main class="view" id="view-routing" hidden>
<div class="row-head"><span class="label" data-t>Routing</span><span class="rt-livedot" aria-hidden="true"></span><span class="note" data-t>live, as the gateway decides</span><span class="grow"></span>
<button class="text rt-newgroup" id="rtNewGroup" type="button" data-feature="groups" data-tt="Make a routing group of any models you like — agents pick it as one model"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"/></svg><span data-t>New group</span></button>
<button class="text rt-mask" id="rtMask" aria-pressed="false" data-tt="Mask the accounts on this page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button></div>
<section class="rt" id="rt"></section>
<div class="rt-more" id="rtMore"></div>
</main>
<main class="view" id="view-usage" hidden>
<div class="usage-head">
<div class="segs" id="usageTab"></div>
@@ -567,9 +559,10 @@
<script src="plugins/sessions/client.js"></script>
<script src="plugins/library/i18n.js"></script>
<script src="plugins/library/client.js"></script>
<script src="plugins/routing/i18n.js"></script>
<script src="plugins/routing/client.js"></script>
<script src="purposes.js"></script>
<script src="app.js"></script>
<script src="routing.js"></script>
<script src="plugins.js"></script>
<script src="context.js"></script>
</body>
@@ -7,7 +7,39 @@
// recorded while deciding (see internal/gateway/trace.go) — the order it
// weighed the accounts in, what it weighed them by, what each answered,
// how long a failed one rests. Nothing here is worked out again or made up.
(() => {
//
// A page the Routing plugin adds to the window (kernel.js), its words in
// i18n.js beside this file. Classic script, loaded before app.js: what
// runs as it loads touches neither the page nor app.js. Its markup is the
// html below; mount, at magpie.start, draws the stage and starts reading
// the gateway's trace, and from then on the page keeps itself (it watches
// its own hidden, the language and the window). dirty and discard are a
// routing group being edited, asked of it before the reader leaves.
magpie.plugin("routing", (ctx) => {
ctx.slots.add("page", {
key: "routing",
title: "Routing",
html: `
<div class="row-head"><span class="label" data-t>Routing</span><span class="rt-livedot" aria-hidden="true"></span><span class="note" data-t>live, as the gateway decides</span><span class="grow"></span>
<button class="text rt-newgroup" id="rtNewGroup" type="button" data-feature="groups" data-tt="Make a routing group of any models you like — agents pick it as one model"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"/></svg><span data-t>New group</span></button>
<button class="text rt-mask" id="rtMask" aria-pressed="false" data-tt="Mask the accounts on this page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button></div>
<section class="rt" id="rt"></section>
<div class="rt-more" id="rtMore"></div>
`,
// once the window's scripts have all run: the page it opens on is
// shown by then, so the first draw is of a page in sight (WebKit
// opened the first request a draw late), and context.js's ctxCard,
// which draws the context window's card, is there for it
mount() {
const ready = document.readyState === "loading" ? new Promise((go) => document.addEventListener("DOMContentLoaded", go, { once: true })) : Promise.resolve();
return ready.then(() => routingPage(this));
},
});
});
// The page, drawn once app.js is set up; part is its part, given the hooks
// app.js calls
function routingPage(part) {
const box = $("#rt");
if (!box) return;
const NS = "http://www.w3.org/2000/svg";
@@ -3365,8 +3397,9 @@
renderGroups();
return true;
}
window.routingDirty = groupDirty;
window.discardRouting = () => { gEdit = null; renderGroups(); };
// what app.js asks before the reader leaves the page
part.dirty = groupDirty;
part.discard = () => { gEdit = null; renderGroups(); };
async function groupAction(action, body, ok) {
if (action === "delete" && !await confirmRemoval(groups?.groups.find((g) => g.id === body.id)?.name || body.id,
"This routing group will no longer be available to agents.")) return;
@@ -5537,4 +5570,4 @@
words();
start();
poll();
})();
}
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
/* Routing, live: the Gateway view's stage for what routing does with each
request (routing.js). The same stage as the site's Model Routing, only
request (client.js). The same stage as the site's Model Routing, only
played by the gateway's own trace. */
.rt { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px 12px; margin: 0 0 18px; }
.rt-top { display: flex; flex-direction: column; gap: 3px; }
@@ -139,7 +139,7 @@
.rt-accts li { transition: none; }
}
/* The narrow and wide layouts below go by a box's own width, as container
queries would: routing.js sets max560 on a box 560px wide or less, min1150
queries would: client.js sets max560 on a box 560px wide or less, min1150
on one 1150px or wider. Not container queries: in WebKit they kept the
page from scrolling to its end (#1249). :where() keeps each rule as
strong as it was inside its query. */
+1 -1
View File
@@ -98,7 +98,7 @@ func TestPageNamesItsFilesByContent(t *testing.T) {
t.Errorf("/: Content-Type %q", ct)
}
body := page.Body.String()
for _, f := range []string{"app.js", "routing.js", "plugins.js", "plugins/sessions/client.js", "plugins/sessions/sessions.css", "plugins/library/client.js", "plugins/library/library.css", "context.js", "i18n.js", "compat.js", "app.css", "routing.css", "context.css"} {
for _, f := range []string{"app.js", "plugins.js", "plugins/routing/client.js", "plugins/routing/routing.css", "plugins/sessions/client.js", "plugins/sessions/sessions.css", "plugins/library/client.js", "plugins/library/library.css", "context.js", "i18n.js", "compat.js", "app.css", "context.css"} {
b, err := fs.ReadFile(staticFS(), f)
if err != nil {
t.Fatal(err)
+3 -3
View File
@@ -44,12 +44,12 @@ func TestBuiltinSwitch(t *testing.T) {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 6 {
if len(out) != 7 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
// the gateway page is essential: on in every preset
if b.On != (b.ID == "library" || b.ID == "gateway") || b.On != (b.State == pluginrt.Active) {
// the Gateway and Routing pages are essential: on in every preset
if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "routing") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
+1 -1
View File
@@ -200,7 +200,7 @@ func TestGroupMemberThatIsAGroupCarriesWhatAgentsSee(t *testing.T) {
}
// and each member's row is readable: a member that carries any of these
// draws chips (routing.js reads memberInfo when the member is a group)
// draws chips (routing/client.js reads memberInfo when the member is a group)
for _, mi := range outer.Info {
if !mi.Group && mi.Context == 0 {
t.Errorf("member %s carries nothing to read", mi.ID)
+11 -2
View File
@@ -23,12 +23,13 @@ const PLUGINS = [
{ id: "groups", name: "Routing groups", sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", one: "1 group in use", many: "{n} groups in use" },
{ id: "library", name: "Library", sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent", one: "1 item given to agents", many: "{n} items given to agents" },
{ id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" },
{ id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" },
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
{ id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" },
];
// a new install's (the Essentials preset): all off but the Gateway page,
// which is essential, and two routing groups the user made
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], sessions: [false, 0], warmups: [false, 0] };
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], routing: [true, 0], sessions: [false, 0], warmups: [false, 0] };
// the Gateway page's settings, as pluginrt.SchemaOf makes them
const GATEWAY_SCHEMA = {
@@ -158,7 +159,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
if (lang !== "en") assert.notEqual(g.why, "2 groups in use", `${where}: why translated`);
const gw = rows.find((r) => r.id === "gateway");
assert.deepEqual([gw.on, gw.disabled], ["true", false], `${where}: the Gateway page, on`);
for (const r of rows.filter((r) => r.id !== "groups" && r.id !== "gateway")) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
const rt = rows.find((r) => r.id === "routing");
assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`);
for (const r of rows.filter((r) => !["groups", "gateway", "routing"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
@@ -190,6 +193,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator('#builtinList [data-id="otel"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="otel"] [aria-checked="true"]');
assert.ok(await page.locator("#setTab-otel").evaluate((b) => getComputedStyle(b).display !== "none"), `${where}: Observability back`);
// Routing switched off: its tab and the panel's go, the page stays
await page.locator('#builtinList [data-id="routing"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="routing"] [aria-checked="false"]');
assert.deepEqual(posts.at(-1), ["routing", false], where);
if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing")], `${where}: Routing gone`);
assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`);
// Discover brings the search back
await pluginTabs(page, side).nth(1).click();
assert.ok(await page.locator("#view-plugins .pm-find").isVisible(), `${where}: search on Discover`);
+1 -1
View File
@@ -9,7 +9,7 @@ const choice = (family, weight, style) => ({ family, name: "Chosen", weight, sty
for (const [name, engine] of [["chromium", chromium], ["webkit", webkit]]) {
test(`${name}: font reset restores the original cascade and explicit emphasis`, async () => {
const css = (await Promise.all(["app.css", "plugins/library/library.css", "routing.css", "plugins/sessions/sessions.css", "plugins.css"].map(f => fs.readFile(path.join(assets, f), "utf8")))).join("\n");
const css = (await Promise.all(["app.css", "plugins/library/library.css", "plugins/routing/routing.css", "plugins/sessions/sessions.css", "plugins.css"].map(f => fs.readFile(path.join(assets, f), "utf8")))).join("\n");
const js = await fs.readFile(path.join(assets, "fonts.js"), "utf8");
const browser = await engine.launch();
try {
@@ -118,7 +118,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// every label beside its own field, or over it where the editor is one
// column: a hidden classifier left its cell behind, and Levels' label
// sat at the right, its choices below. Under 760px the editor is one
// column on purpose (routing.css), so the label is above its field
// column on purpose (plugins/routing/routing.css), so the label is above its field
// there — beside is only what a wide window can ask for.
const oneColumn = width <= 760;
const rows = await ed.evaluate((e, oneColumn) => [...e.children].filter((c) => c.matches("label") && !c.hidden && c.offsetParent).map((l) => {
@@ -50,10 +50,10 @@ async function redsOf() {
test("no colour an agent can be marked with reads as the failure red", async () => {
const reds = await redsOf();
const js = await fs.readFile(path.join(assets, "routing.js"), "utf8");
const js = await fs.readFile(path.join(assets, "plugins/routing/client.js"), "utf8");
const hues = js.match(/const HUES = \{([\s\S]*?)\};/);
const spare = js.match(/const SPARE = \[([^\]]*)\]/);
assert(hues && spare, "hueOf's palette not found in routing.js");
assert(hues && spare, "hueOf's palette not found in routing/client.js");
const all = [...hues[1].matchAll(/(\w+):\s*"(#[0-9a-f]{6})"/gi)].map((m) => [m[1], m[2]])
.concat([...spare[1].matchAll(/"(#[0-9a-f]{6})"/gi)].map((m) => ["spare", m[1]]));
assert(all.length > 10, "palette too small: " + JSON.stringify(all));
@@ -16,7 +16,7 @@ const { chromium, webkit } = require("playwright");
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["webkit"];
const assets = path.resolve(__dirname, "../assets");
const routing = path.join(assets, "routing.js");
const routing = path.join(assets, "plugins/routing/client.js");
const iso = (ms) => new Date(ms).toISOString();
const acct = (n) => ({ id: `acct-${n}`, provider: `prov${n}`, name: `Provider ${n}`, who: `user${n}@example.com`, kind: "account", model: `model-${n}`, known: true, used: 10 * n, plan: "Pro" });
const agentsOf = ["codex", "claude", "opencode", "kimi"];
@@ -80,7 +80,7 @@ const selfRaf = (src) => { const m = src.match(/requestAnimationFrame\s*\(\s*([A
test("the loop's frame is still there to be counted, and asks for itself", async () => {
const src = await fs.readFile(routing, "utf8");
assert(byName(src) || selfRaf(src), "routing.js must still keep its frame loop in a function of its own, or the test below counts nothing");
assert(byName(src) || selfRaf(src), "routing/client.js must still keep its frame loop in a function of its own, or the test below counts nothing");
});
for (const engine of engines) for (const lang of ["en", "zh"]) {
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const narrow = width <= 600;
assert.equal(await tracks(page, ".rt-stage"), narrow ? 2 : 3, "the stage's columns");
assert.equal(await tracks(page, ".rt-reqs"), width < 800 ? 2 : 4, "the requests' columns");
// by the room the page has, the sidebar's aside (routing.js byWidth)
// by the room the page has, the sidebar's aside (routing/client.js byWidth)
const room = await page.locator(".rt-more").first().evaluate((e) => e.getBoundingClientRect().width);
assert.equal(await tracks(page, ".rt-cols"), room >= 1150 ? 2 : 1, "the requests and the accounts, side by side or one under the other");
+1 -1
View File
@@ -10,7 +10,7 @@ const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const sheets = ["app.css", "plugins/library/library.css", "routing.css", "plugins/sessions/sessions.css", "plugins.css"];
const sheets = ["app.css", "plugins/library/library.css", "plugins/routing/routing.css", "plugins/sessions/sessions.css", "plugins.css"];
test("no stylesheet names a monospace stack of its own", async () => {
for (const f of sheets) {
+2 -2
View File
@@ -43,7 +43,7 @@ func TestWebCompresses(t *testing.T) {
}
// what Chrome and Safari send over plain http
const browser = "gzip, deflate"
for _, f := range []string{"i18n.js", "app.js", "routing.js", "app.css", "index.html"} {
for _, f := range []string{"i18n.js", "app.js", "plugins/routing/client.js", "app.css", "index.html"} {
want, err := fs.ReadFile(staticFS(), f)
if err != nil {
t.Fatal(err)
@@ -119,7 +119,7 @@ func TestVersionedFilesKept(t *testing.T) {
return rec
}
page := get("/").Body.String()
for _, f := range []string{"app.js", "routing.js", "i18n.js", "app.css"} {
for _, f := range []string{"app.js", "plugins/routing/client.js", "i18n.js", "app.css"} {
b, err := fs.ReadFile(staticFS(), f)
if err != nil {
t.Fatal(err)
+2 -2
View File
@@ -453,7 +453,7 @@ func (t Totals) Floor() float64 {
// over next to no time would lift everyone's; its TTFT still counts.
// The bounds are wide of any real stream: the fastest vendors write a few
// thousand tokens a second, and a tenth of a second is the least a
// stream's timing tells anything by. routing.js's speedOf has the same.
// stream's timing tells anything by. routing/client.js's speedOf has the same.
const (
MinDecodeMs = 100
MaxDecodeSpeed = 10000
@@ -533,7 +533,7 @@ func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64, firstReasonin
// HeldShare and ThinkPace tell a reply held back and let go in a burst
// (DecodeOf): its content came in under a quarter of its window, or its
// answer at over 20 times the pace its reasoning came. routing.js's
// answer at over 20 times the pace its reasoning came. routing/client.js's
// decodeOf and app.js's ledDecode have the same.
const (
HeldShare = 4
+1
View File
@@ -7,6 +7,7 @@ import (
_ "github.com/yetone/magpie/plugins/groups"
_ "github.com/yetone/magpie/plugins/library"
_ "github.com/yetone/magpie/plugins/otel"
_ "github.com/yetone/magpie/plugins/routing"
_ "github.com/yetone/magpie/plugins/sessions"
_ "github.com/yetone/magpie/plugins/warmups"
)
+30
View File
@@ -0,0 +1,30 @@
// Package routing is the Routing page: each request the gateway routes,
// played as it decides, the accounts it weighed and what each answered,
// and the routing groups' editor. The gateway routes the same with the
// page off; while the user has a routing group, the page that edits it
// stays on.
package routing
import (
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "routing", API: "^1", Requires: []string{"window", "gateway"}, Essential: true,
Name: "Routing", Sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups",
One: "1 group in use", Many: "{n} groups in use",
InUse: func() (int, error) {
n := 0
for _, g := range provider.Groups() {
if !g.Auto && !g.Hidden {
n++
}
}
return n, nil
},
Parts: []pluginrt.Part{{Slot: "nav.page", Key: "routing"}},
Client: []string{"i18n.js", "routing.css", "client.js"},
})
}