agent: Codex's status line shows the account's quota or the relay's balance (opt-in)

lyj1115 on X asked for the current account's quota, or the relay key's
balance, under Codex's chat box, off by default. Codex's TUI draws its
footer from a status line provider from 0.171.0-alpha.12 on: a stdio
MCP server whose tool advertises a statusline entrypoint, picked in
[tui] status_line_provider behind [features] tui_extensions_statusline.
Codex reads it about once a second with the thread's id. Nothing is put
into the prompt or the model's reply.

- `magpie statusline --codex` is that server. Each read asks the local
  gateway for the thread's latest route and the kept quotas (no vendor
  read). It answers `→ provider/model` and that provider's account that
  answered last, with its windows or a key's balance. A gateway that is
  down gives a null tree, never an error, because an error stops Codex's
  reads. The tool's name and words name neither magpie nor a vendor,
  since the tool is listed to the model.
- A status line square on Codex's row (`magpie codex statusline on`)
  writes the flag, [mcp_servers.quota_line] (this magpie by full path,
  args statusline --codex, env_vars = ["MAGPIE_ADDR"]) and the
  provider. Every write is read back, and the file is restored on a
  mismatch. Off and Disconnect take out only magpie's keys, and the flag
  only when the stash says magpie wrote it.
- Nothing of the user's is written over. A provider of their own, a
  quota_line of theirs, the flag turned off or an unreadable file keeps
  the square away and refuses on.
- The switch is offered only when a Codex CLI here is 0.171.0-alpha.12
  or newer (0.170.0 reads the keys and draws nothing), and only on this
  computer, not in a WSL distro.
- In the GUI, the status line square's title takes the note of its
  field's on option, which Claude Code's field already sent with the
  same words TOGGLES kept, so Codex's says its own words in en, zh,
  zh-TW, ja and de. TOGGLES' copy of Claude's note went, and app.js
  stays under its budget (30 bytes of room) without a raise.

The Codex desktop app has no such footer. cockpit-tools reaches it
through a debug port, and magpie doesn't.

Run (WSL magpie-desktop, since mote's load was over 18):
- go vet -tags nogui ./...; GOOS=windows go vet of agent, cli, provider
  and gui; gofmt -l clean.
- go test -tags nogui of ./internal/cli and ./internal/provider: ok.
- ./internal/agent -run "CodexStatus|Statusline|StatusLine|TestCodex|
  TestWSLCodex": ok.
- ./internal/gui -run "CoreScript|Budget|I18n|Keys" and node --test of
  codex-statusline, claude-statusline and i18n-keys (both engines, every
  language, window and panel), with vet (and GOOS=linux and windows
  vet) of agent, cli, provider and gui, on mote at the rebased head
  (on 1bd1a08a3): all ok, 64 of 64 GUI cases.

Broken by hand:
- free() reduced to `readable`: TestCodexStatusLineLeavesTheUsers is red
  on their provider, their server and flag off.
- The field not appended: TestCodexStatusLineSwitch is red ("no
  statusline field").
- The first build checked `at.base == nil` after codexIn had set base.
  Every agent test went red, which is how that bug was found.

Real Codex, in a sandbox HOME on WSL with a fake gateway:
- 0.171.0-alpha.13, with `magpie codex statusline on` writing config.toml,
  draws `→ relay/glm-5  relay $4.20` under the prompt, and the server is
  read about once a second.
- Without env_vars, Codex starts the server without MAGPIE_ADDR: nothing
  was asked and nothing was drawn. That is why env_vars is written.
- On a second time leaves the file byte for byte. Off brings it back to
  what it was, apart from Codex's own NUX counter.
- 0.170.0 lists quota_line from the same file and runs fine.

Not tried: macOS and Windows Codex; a real gateway with real accounts
(the server was fed through MAGPIE_ADDR); whether an open Codex session
picks the footer up without a restart.

Full suite: run after push.
This commit is contained in:
yetone
2026-11-19 00:44:40 +08:00
parent 1bd1a08a3a
commit 2ab2f69132
13 changed files with 1059 additions and 4 deletions
+22
View File
@@ -2875,6 +2875,28 @@ computer Claude Code runs on:
`"statusLine": {"type": "command", "command": "curl -fsS -m 1 -H 'Authorization: Bearer <gateway key>' --data-binary @- http://<host>:3425/v1/magpie/statusline || true"}`.
`magpie web` shows this command with its own address under Settings → About.
Codex's TUI has a footer of the same kind from 0.171.0-alpha.12 on: a
status line provider, a stdio MCP server whose tool says it draws one.
`magpie statusline --codex` is that server. Codex reads it about once a
second and passes the thread's id; it answers the model the thread's latest
turn went to, then the account of that provider that answered last, with
its windows, or a relay key's balance:
`→ relay/glm-5 relay $4.20`, or `→ codex/gpt-5.5 codex me@example.com 5h 37% 7d 12%`.
With no route it shows the account that answered last of all, and with the
gateway not running it shows nothing. It is off until the status line square
on Codex's row (or `magpie codex statusline on`) turns it on. That writes
three things into `~/.codex/config.toml`: `[features] tui_extensions_statusline = true`,
`[mcp_servers.quota_line]` running this magpie by its full path with
`args = ["statusline", "--codex"]` and `env_vars = ["MAGPIE_ADDR"]` (Codex hands a server only a few variables of its own), and
`[tui] status_line_provider = { server = "quota_line", tool = "statusline" }`.
Off, or Disconnect, takes out only those, and the flag only when magpie
wrote it. The square isn't offered while the user has a provider of their
own picked, a `quota_line` server of their own or the flag turned off. It
is also not offered until a Codex CLI here is 0.171.0-alpha.12 or newer:
0.170.0 accepts the keys and draws nothing. Codex lists the server's tool
to the model like any MCP tool's. Its name and description say only what it
shows. The Codex app has no such footer.
`magpie heap [<file>]` is for a report of magpie holding too much memory: a
macOS `sample` of the app shows Go's frames as `???`. It asks the running
magpie that serves the gateway (the app, the menu bar, `magpie serve` or
+1
View File
@@ -184,6 +184,7 @@ something else shows up as drift.
- Claude Code takes one window (`CLAUDE_CODE_MAX_CONTEXT_TOKENS`, `claudeContextEnv` in [`claude.go`](../../internal/agent/claude.go)) for every model it doesn't know. Claude Code alone on magpie is told its main model's (`claudeWindow`), and a model picked in its `/model` (magpie's `modelPicker`) runs at that one value. Beside a main that is one of Claude's own models (or a group of them), with no tier that isn't, nothing is told, so a model picked there ran at Claude Code's own 200K: a routing group of a 500K GPT and a 1M Claude did (young02036 on Discord). Then (`pickerApart`) the `/model` rows (`pickerRefs`) count as tiers do in the layout below. While Claude Desktop is on magpie too, its Code tab runs Claude Code on the same `~/.claude/settings.json` with every model Desktop lists, so magpie tells it the largest window of those and of Claude Code's own models (its main, tiers and `/model` rows), and holds each model below it to its own with `modelSettings.<id>.autoCompactWindow` (`claudePlan` in [`claude_budget.go`](../../internal/agent/claude_budget.go), #2025: the least held a 1M model to 131K). A model handed by a `[1m]` id (Desktop's under `DesktopLongest`, a Desktop model past 200K and under 1M, or Claude Code's own) counts by its 1M too, or by its own window under 1M, which is its entry, so it still runs at 1M when Claude Code stops taking the id for 1M (the 1M beta turned away once, `CLAUDE_CODE_DISABLE_1M_CONTEXT`); left out, a 1M model beside a 272K GPT was told 272K (dumplings on Discord). Under `DesktopLongest` that 1M model also compacts at its whole 1M, not the working window (`work` in `desktopPlan`; henglu486729 on X: Desktop's 1M entry showed and compacted at 272K); a threshold typed in magpie (`CompactAt`, a model's or provider's) still holds it. Claude Code 2.1.296 matches that key by the id it was handed, lowercased and without `[1m]`; it comes before the top-level `autoCompactWindow`, which serves a model without one. Every auto-compact window magpie writes for Claude Code, per model, top-level and in `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, is held to 1000000 (`claudeCompactCap`): Claude Code 2.1.316's settings schema, and Claude Desktop 2.7032's copy of it, read a larger value as none, so a 1048576 threshold typed for a 1M model ran it at the top-level 272K (ZeroX2017 on X). The threshold in magpie stays as typed, Codex and Grok Build get it unheld, and tune's card reads it back as typed. `CLAUDE_CODE_AUTO_COMPACT_WINDOW` would take precedence over both, so in this mode magpie's working window goes in the top-level `autoCompactWindow` instead, and an entry is written only where a model's window or its own threshold differs from what it would run at without one. magpie's entries and top-level value are stashed (`claude.model_budgets`, `claude.compact_default`) and go when Desktop leaves magpie; the user's own entries, top-level value and variables stay, a user's entry past its model's window (or `auto`) holds the largest to that window unless the model is handed by a `[1m]` id, which the largest doesn't reach, and with a `CLAUDE_CODE_AUTO_COMPACT_WINDOW` of the user's the least window is told as before. A Code tab session whose environment host is WSL runs on the distro's Claude Code, which reads `${CLAUDE_CONFIG_DIR:-$HOME/.claude}` there (Desktop 4.29.0's remote probe) and not Windows' file, so each `claude@wsl:<distro>` is told the same while Windows' Desktop is on magpie (`desktopOn`), on magpie itself or not; it read 200K for a 500K group before (young02036 on Discord).
- Claude Code is told what each of magpie's models can do in `CLAUDE_CODE_MODEL_CAPABILITIES` (`claudeCapsEnv`, `claudeCapabilities` in [`claude.go`](../../internal/agent/claude.go)): `<model>=effort[,xhigh_effort][,max_effort]` for those it is shown, and, while Claude Desktop is on magpie, for Desktop's `mythos-magpie-<number>` ids its Code tab hands it. A Claude model Claude Code knows gets no more than Claude Code gives it (Opus and Sonnet 4.6: no xhigh), and one with no known levels isn't named. A model that reaches max without xhigh (GLM-5.3 at low/high/max, DeepSeek V4 at high/max) is said to have xhigh too: the gateway runs xhigh at max for it (`fitEffort`), and Claude Code 2.1.299 turns Ultracode down without `xhigh_effort` ("Ultracode isn't available on …"), which in Desktop is the Ultracode level and dynamic workflows (leesunrise2364 on Discord; `TestClaudeModelCapabilities`). A value of the user's is left alone.
- Claude Code's status line (`statusline`, [`claude_statusline.go`](../../internal/agent/claude_statusline.go)) is a switch on its row, beside ultracode (steven_4422 on Discord: the 5h and 7d use in Claude Code). On writes settings.json's `statusLine` to run this magpie by its full path (`update.Program()`, forward slashes and quoted for Git Bash on Windows) with `statusline` (#1997, [`statusline_cli.go`](../../internal/cli/statusline_cli.go)), which reads the gateway's kept windows with a 1s timeout and prints nothing when it can't. A status line runs magpie's when its program's base name is `magpie` (or `magpie-…`) and its first argument `statusline` (`claudeStatusOurs`), so one written by hand from the reference counts too. A status line of the user's own (claude-hud, a script) is never written over: Options is empty while one is there, so the square isn't shown, and on is refused; an unreadable settings.json is refused too. Off and Disconnect take out only magpie's. Claude Code watches settings.json and reruns a changed command in its open sessions, so it is Quiet and needs no restart. Only on this computer: a WSL distro, running or stopped (`wslKinds` asleep options), isn't offered it (`TestClaudeStatusLine*`, `TestWSLClaudeNoStatusLine`, `claude-statusline.test.cjs`). For Claude Code on another computer than magpie (Docker), the gateway serves the same line at `/v1/magpie/statusline` ([`statusline.go`](../../internal/gateway/statusline.go), the renderer shared in [`provider/statusline.go`](../../internal/provider/statusline.go)), and `magpie web` shows the curl to put in settings.json (`TestStatuslineEndpoint`, `TestStatuslineEndpointIsTheCLIsLine`, `statusline-remote.test.cjs`); nothing writes that computer's file.
- Codex's status line (`statusline`, [`codex_statusline.go`](../../internal/agent/codex_statusline.go)) is the same square on Codex's row (lyj1115 on X: the account's quota or the relay's balance under Codex's chat box). Codex's TUI (0.171.0-alpha.12 on) draws its footer from a stdio MCP server whose tool advertises a statusline entrypoint, picked in `[tui] status_line_provider` behind `[features] tui_extensions_statusline`. On writes the flag, `[mcp_servers.quota_line]` running this magpie with `statusline --codex` ([`statusline_codex.go`](../../internal/cli/statusline_codex.go)) and `env_vars = ["MAGPIE_ADDR"]`, and the provider. Codex starts a server with only a few of its variables (HOME and PATH among them), so a MAGPIE_ADDR the user runs Codex with gets through only by env_vars; without one the server finds the gateway from the address the running gateway wrote down, as every client does. The provider answers each read from the gateway's route for the thread (its id is Codex's `session_id`) and its kept quotas (`provider.CodexStatuslineCards`), with a null tree, never an error, when the gateway is down: an error or a read past Codex's 1s stops its reads. Every write is read back, and the file is put back as it was when it doesn't read as magpie's. Nothing of the user's is written over: a provider of their own (anything but `"default"`), a `quota_line` server of theirs, a flag turned off or an unreadable file keeps the square away and refuses on. The flag goes on off only when the stash says magpie wrote it. It is offered only where a Codex CLI here (`codexReaders`) is 0.171.0-alpha.12 or newer, since 0.170.0 reads the keys and draws nothing, and only on this computer. Disconnect takes it out with the rest. The tool is listed to the model too, so its words name neither magpie nor a vendor (`TestCodexStatusLine*`, `TestCodexStatuslineServer`, `TestCodexStatuslineCards`, `codex-statusline.test.cjs`).
- MiniMax Code takes a model ref with one slash in the whole (a SubAgent's `model` must match `^[^/\s]+\/[^/\s]+$`, #1387), and magpie's refs there are `custom_provider:magpie/<model>`. So a model under `custom_provider.magpie` is written with `~` for each slash of its catalog id (`bb-codex~gpt-6.1-sol`, `provider.FlatID`), only when that spelling stands for one served id (`provider.Flattened`); the gateway takes it back. A config an older magpie wrote moves over on the next sync: the user's keys on a model go to its new key, `defaultModel`, `defaultLightModel` and `memory.captureModel`/`consolidationModel` follow (`mcodeRefs`), and the slashed key stays, switched off (`enabled: false`), so a session begun on it still resumes. magpie never edits the user's own `agents/<name>/agent.md`. No other agent was found with this limit ([`minimax.go`](../../internal/agent/minimax.go)).
- MiniMax Code's data folder is found as the app finds it (`appdir.MiniMaxDirIn`): `$MINIMAX_DATA_DIR`, `$MAVIS_DATA_DIR`, then the parent folder the desktop app's Settings moved it to, kept as `config.localRuntimeDataParentDir` in its electron-store file (`MiniMax/minimax-agent-cn-config.json` for the China build, `MiniMax Agent/minimax-agent-config.json` for the global one, under Application Support on a Mac and `%APPDATA%` on Windows), as `<parent>/.minimax`, else `~/.minimax`. A store that can't be read or parsed is the default, as electron-store reads it. The wiring, Sessions' calls and the Library's skills all use it ([`minimax.go`](../../internal/appdir/minimax.go)).
- MiniMax Code Desktop (3.1.10, `MiniMax Code.app`, `com.minimax.agent.cn` or `com.minimax.agent`) runs the same runtime on the same `config.yaml`, but its window keeps the model last picked in it (localStorage `mavis:model-selection`) and runs that, not `defaultModel`, while that model is still listed. Its runtime reads `config.yaml` at start-up and doesn't watch it, and it has no local API in a release build, so magpie can't move the pick. With the app installed (`desktopApps`), MiniMax Code's notice says to restart the app and pick a magpie model once in its menu ([`minimax.go`](../../internal/agent/minimax.go)).
+13
View File
@@ -276,6 +276,8 @@ func codexIn(at place) *Agent {
// where 127.0.0.1 is the distro's own, so the user points it at
// Windows as WSL sees it, or a forward of theirs (#816); magpie keeps
// that address, checks against it and writes it again
// onHere: this machine's Codex, before base names its kept gateway
onHere := at.spell == nil && at.base == nil
if at.spell == nil && at.base == nil {
at.base = func() string { return codexKeptGateway(path) }
}
@@ -2644,6 +2646,17 @@ func codexIn(at place) *Agent {
// yet is managed there (switching then left config.toml's wiring behind,
// and Codex on its own list; kakzyanaba on X)
a.Fields = append(a.Fields, codexScopeField(at, func() bool { return a.Wired() || a.Routed() || a.FailingOver() }))
// the footer's quota (codex_statusline.go), taken out with magpie
statusField := codexStatusField(at, path, onHere)
a.Fields = append(a.Fields, statusField)
if unwire := a.Unwire; unwire != nil {
a.Unwire = func() error {
if err := unwire(); err != nil {
return err
}
return statusField.Set("")
}
}
// this machine's Codex: the address its config keeps is tried (Drift),
// and moved to WSL's new one when that changed (#1013)
if at.spell == nil {
+260
View File
@@ -0,0 +1,260 @@
package agent
// Codex's status line, magpie's (lyj1115 on X: the current account's quota,
// or the relay's balance, under Codex's chat box, off unless turned on).
// Codex's TUI, from 0.171.0-alpha.12, draws its footer from a status line
// provider: a stdio MCP server whose tool advertises a statusline
// entrypoint, picked in config.toml's [tui] status_line_provider = {
// server, tool } behind [features] tui_extensions_statusline (its bundled
// create-statusline skill). `magpie statusline --codex` is such a server
// (internal/cli/statusline_codex.go). The switch on Codex's row writes
// those three keys, the server as this magpie's binary by its full path;
// off takes out only what is magpie's.
//
// A provider of the user's own, or an [mcp_servers.quota_line] of theirs,
// is never written over: the switch isn't offered while one is there, and
// on is refused; nor is a features flag they turned off. The flag is
// taken out on off only when magpie wrote it (stashed). Only offered
// where a Codex CLI here can draw it: 0.170.0 reads the keys without
// complaint and draws nothing. The desktop app has no such footer, and is
// not reached into (cockpit-tools drives it through its debug port).
// Only on this computer, as Claude Code's switch.
import (
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/edit"
)
const (
// the names config.toml has for magpie's server and its tool;
// cli.CodexStatusServer and cli.CodexStatusTool say the same
codexStatusServer = "quota_line"
codexStatusTool = "statusline"
// codexStatusFrom is the first Codex that draws a provider's footer
codexStatusFrom = "0.171.0-alpha.12"
// codexStatusFeature is the flag status_line_provider is read behind
codexStatusFeature = "tui_extensions_statusline"
// codexStatusFlagKey stashes that magpie wrote the flag
codexStatusFlagKey = "codex.statusline_feature"
)
// codexStatusArgs are what Codex runs magpie's binary with.
var codexStatusArgs = []string{"statusline", "--codex"}
// codexStatusState is what config.toml says about the status line.
type codexStatusState struct {
readable bool
// mine: a provider picked that isn't magpie's (not "default")
mine bool
// server: [mcp_servers.quota_line] is there; ours: it runs magpie's
server, serverOurs bool
// picked: status_line_provider names magpie's server and tool
picked bool
// flag is features.tui_extensions_statusline: "true", "false" or ""
flag string
}
// ours says the status line is magpie's and on.
func (s codexStatusState) ours() bool { return s.picked && s.serverOurs }
// free says magpie may turn it on: nothing of the user's in the way.
func (s codexStatusState) free() bool {
return s.readable && !s.mine && (!s.server || s.serverOurs) && s.flag != "false"
}
func codexStatusRead(path string) codexStatusState {
raw, err := edit.Read(path)
if err != nil {
return codexStatusState{}
}
var doc struct {
Features map[string]any `toml:"features"`
McpServers map[string]any `toml:"mcp_servers"`
Tui struct {
Provider any `toml:"status_line_provider"`
} `toml:"tui"`
}
if err := toml.Unmarshal(raw, &doc); err != nil {
return codexStatusState{}
}
s := codexStatusState{readable: true}
switch v := doc.Features[codexStatusFeature].(type) {
case bool:
s.flag = fmt.Sprint(v)
case nil:
default:
s.flag = "false" // not Codex's spelling: the user's, left alone
}
if srv, ok := doc.McpServers[codexStatusServer]; ok {
s.server = true
m, _ := srv.(map[string]any)
cmd, _ := m["command"].(string)
args, _ := m["args"].([]any)
var as []string
for _, a := range args {
v, _ := a.(string)
as = append(as, v)
}
s.serverOurs = magpieProgram(cmd) && slices.Equal(as, codexStatusArgs)
}
switch v := doc.Tui.Provider.(type) {
case nil:
case string:
s.mine = v != "default"
case map[string]any:
s.picked = v["server"] == codexStatusServer && v["tool"] == codexStatusTool
s.mine = !s.picked
default:
s.mine = true
}
return s
}
// magpieProgram says whether a command path is a magpie binary.
func magpieProgram(cmd string) bool {
base := strings.ToLower(filepath.Base(strings.ReplaceAll(cmd, `\`, "/")))
base = strings.TrimSuffix(base, ".exe")
return base == "magpie" || strings.HasPrefix(base, "magpie-")
}
// codexStatusDraws says whether a Codex CLI here draws a provider's
// footer.
func codexStatusDraws(at place) bool {
for _, r := range codexReaders(at) {
if r.Kind == "cli" && r.Version != "" && !Newer(codexStatusFrom, r.Version) {
return true
}
}
return false
}
// codexStatusField is the statusline switch of Codex's config.toml at
// path; here says the Codex is this computer's (not a distro's).
func codexStatusField(at place, path string, here bool) Field {
flagKey := at.key(codexStatusFlagKey)
return Field{
Key: "statusline", Label: "status line", Quiet: true,
Get: func() string {
if codexStatusRead(path).ours() {
return "on"
}
return ""
},
Set: func(v string) error {
s := codexStatusRead(path)
switch v {
case "", "off":
if s.picked {
if err := edit.DelTOMLKey(path, "tui", "status_line_provider"); err != nil {
return err
}
}
if s.serverOurs {
if err := edit.DelTOMLTable(path, "mcp_servers."+codexStatusServer); err != nil {
return err
}
}
if peek(flagKey)[flagKey] != "" {
if s.flag == "true" {
if err := edit.DelTOMLKey(path, "features", codexStatusFeature); err != nil {
return err
}
}
forget(flagKey)
}
return nil
case "on":
if s.ours() {
return nil
}
if !here {
return fmt.Errorf("magpie's status line is for Codex on this computer, not in WSL")
}
if !s.readable {
return fmt.Errorf("%s can't be read; magpie leaves it as it is", at.native(path))
}
if !s.free() {
return fmt.Errorf("%s has a status line provider, an [mcp_servers.%s] or a %s of its own; magpie leaves them as they are", at.native(path), codexStatusServer, codexStatusFeature)
}
was, err := edit.Read(path)
if err != nil {
return err
}
stashed := false
undo := func(err error) error {
if stashed {
forget(flagKey)
}
if was == nil {
edit.DelTOMLKey(path, "tui", "status_line_provider")
edit.DelTOMLTable(path, "mcp_servers."+codexStatusServer)
edit.DelTOMLKey(path, "features", codexStatusFeature)
} else {
edit.WriteAtomic(path, was)
}
return err
}
if s.flag == "" {
stash(map[string]string{flagKey: "1"})
stashed = true
if err := edit.SetTOMLKey(path, "features", codexStatusFeature, true); err != nil {
return undo(err)
}
}
args := make([]any, len(codexStatusArgs))
for i, a := range codexStatusArgs {
args[i] = a
}
if err := edit.SetTOMLTable(path, "mcp_servers."+codexStatusServer,
edit.KV{Path: "command", Value: claudeStatusExe()},
edit.KV{Path: "args", Value: edit.Raw(tomlStrings(codexStatusArgs))},
// Codex hands a server only a few of its variables: a
// MAGPIE_ADDR the user runs Codex with is the gateway
// the footer asks
edit.KV{Path: "env_vars", Value: edit.Raw(tomlStrings([]string{"MAGPIE_ADDR"}))},
); err != nil {
return undo(err)
}
if err := edit.SetTOMLKey(path, "tui", "status_line_provider", edit.Inline{
{Path: "server", Value: codexStatusServer}, {Path: "tool", Value: codexStatusTool},
}); err != nil {
return undo(err)
}
// a file whose tui or features were spelled so the keys
// landed beside them (dotted keys up top) reads back other
if !codexStatusRead(path).ours() {
return undo(fmt.Errorf("%s didn't read back as magpie wrote it; it is left as it was", at.native(path)))
}
return nil
}
return fmt.Errorf("status line is on or off, not %q", v)
},
Options: func(map[string]string) []Option {
if !here {
return nil
}
s := codexStatusRead(path)
if !s.ours() && (!s.free() || !codexStatusDraws(at)) {
return nil
}
return []Option{{Value: "on", Note: "the remaining quota or balance of the account in use, under Codex's prompt"}}
},
}
}
// tomlStrings is a TOML array of strings.
func tomlStrings(ss []string) string {
parts := make([]string, len(ss))
for i, s := range ss {
b, _ := toml.Marshal(map[string]string{"s": s})
_, v, _ := strings.Cut(strings.TrimSpace(string(b)), " = ")
parts[i] = v
}
return "[" + strings.Join(parts, ", ") + "]"
}
+197
View File
@@ -0,0 +1,197 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/pelletier/go-toml/v2"
)
// codexStatusOf is what config.toml says of the footer: the flag, the
// server's command and args, and the provider picked.
func codexStatusOf(t *testing.T, config string) (flag any, command any, args any, picked any) {
t.Helper()
var doc map[string]any
if err := toml.Unmarshal([]byte(config), &doc); err != nil {
t.Fatalf("%v:\n%s", err, config)
}
features, _ := doc["features"].(map[string]any)
servers, _ := doc["mcp_servers"].(map[string]any)
srv, _ := servers[codexStatusServer].(map[string]any)
tui, _ := doc["tui"].(map[string]any)
return features[codexStatusFeature], srv["command"], srv["args"], tui["status_line_provider"]
}
// lyj1115 on X: the account's quota or the relay's balance under Codex's
// chat box, off unless turned on. On writes the feature flag, magpie's
// server by its full path and the provider; off takes the three out, and
// nothing else in the file moves.
func TestCodexStatusLineSwitch(t *testing.T) {
codexReadersAre(t, "0.171.0-alpha.13")
const before = "model = \"gpt-5.5\"\n\n[tui]\ntheme = \"dark\"\n"
home, read := codexHome(t, "", before)
claudeStatusAt(t, "/Applications/Magpie.app/Contents/MacOS/magpie")
f := codex(home).Field("statusline")
if f == nil {
t.Fatal("Codex has no statusline field")
}
if f.Get() != "" {
t.Fatalf("on before it was turned on: %q", f.Get())
}
if opts := f.Options(nil); len(opts) != 1 || opts[0].Value != "on" || !strings.Contains(opts[0].Note, "Codex") {
t.Fatalf("options: %+v", opts)
}
if err := f.Set("on"); err != nil {
t.Fatal(err)
}
flag, cmd, args, picked := codexStatusOf(t, read())
p, _ := picked.(map[string]any)
if flag != true || cmd != "/Applications/Magpie.app/Contents/MacOS/magpie" ||
strings.Join(strs(args), " ") != "statusline --codex" || !strings.Contains(read(), "env_vars = ['MAGPIE_ADDR']") ||
p["server"] != "quota_line" || p["tool"] != "statusline" ||
!strings.Contains(read(), `theme = "dark"`) || !strings.Contains(read(), `model = "gpt-5.5"`) {
t.Fatalf("on:\n%s", read())
}
if f.Get() != "on" {
t.Fatalf("Get after on: %q", f.Get())
}
on := read()
if err := f.Set("on"); err != nil || read() != on {
t.Fatalf("on again: %v\n%s", err, read())
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if got := read(); strings.Contains(got, "quota_line") || strings.Contains(got, codexStatusFeature) ||
strings.Contains(got, "status_line_provider") || !strings.Contains(got, `theme = "dark"`) {
t.Fatalf("off:\n%s", got)
}
if err := f.Set("maybe"); err == nil {
t.Fatal("a value neither on nor off was taken")
}
}
func strs(v any) []string {
xs, _ := v.([]any)
var out []string
for _, x := range xs {
s, _ := x.(string)
out = append(out, s)
}
return out
}
// What is the user's is left as it is: a provider of their own (or a
// server named as magpie's) keeps the switch away and on is refused; a
// flag they set themselves stays when magpie's footer is turned off, and
// one they turned off keeps it off.
func TestCodexStatusLineLeavesTheUsers(t *testing.T) {
codexReadersAre(t, "0.171.0-alpha.13")
claudeStatusAt(t, "/usr/local/bin/magpie")
for name, config := range map[string]string{
"their provider": "[tui]\nstatus_line_provider = { server = \"mine\", tool = \"line\" }\n",
"their server": "[mcp_servers.quota_line]\ncommand = \"node\"\nargs = [\"q.js\"]\n",
"flag off": "[features]\ntui_extensions_statusline = false\n",
"unreadable": "[tui\n",
} {
t.Run(name, func(t *testing.T) {
home, read := codexHome(t, "", config)
f := codex(home).Field("statusline")
if opts := f.Options(nil); len(opts) != 0 {
t.Fatalf("offered beside the user's: %+v", opts)
}
if err := f.Set("on"); err == nil {
t.Fatal("on was taken")
}
if read() != config {
t.Fatalf("written:\n%s", read())
}
if err := f.Set(""); err != nil || read() != config {
t.Fatalf("off: %v\n%s", err, read())
}
})
}
t.Run("their flag on", func(t *testing.T) {
const config = "[features]\ntui_extensions_statusline = true\n"
home, read := codexHome(t, "", config)
f := codex(home).Field("statusline")
if err := f.Set("on"); err != nil {
t.Fatal(err)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if flag, _, _, _ := codexStatusOf(t, read()); flag != true || strings.Contains(read(), "quota_line") {
t.Fatalf("off took the user's flag, or left magpie's server:\n%s", read())
}
})
t.Run("default provider", func(t *testing.T) {
home, read := codexHome(t, "", "[tui]\nstatus_line_provider = \"default\"\n")
f := codex(home).Field("statusline")
if err := f.Set("on"); err != nil {
t.Fatal(err)
}
if f.Get() != "on" {
t.Fatalf("Codex's own default kept magpie's out:\n%s", read())
}
})
}
// 0.170.0 reads the keys and draws nothing: the switch is offered only
// where a Codex CLI here draws a provider's footer.
func TestCodexStatusLineNeedsACodexThatDraws(t *testing.T) {
for _, vs := range [][]string{{"0.170.0"}, {""}, {"0.171.0-alpha.11"}, nil} {
codexReadersAre(t, vs...)
home, _ := codexHome(t, "", "")
if opts := codex(home).Field("statusline").Options(nil); len(opts) != 0 {
t.Fatalf("offered with Codex %q: %+v", vs, opts)
}
}
codexReadersAre(t, "0.170.0", "0.171.0-alpha.12")
home, _ := codexHome(t, "", "")
if opts := codex(home).Field("statusline").Options(nil); len(opts) != 1 {
t.Fatalf("not offered beside a Codex that draws it: %+v", opts)
}
}
// Disconnect takes magpie's footer out with the rest of magpie.
func TestCodexStatusLineGoesWithUnwire(t *testing.T) {
codexReadersAre(t, "0.171.0-alpha.13")
claudeStatusAt(t, "/usr/local/bin/magpie")
home, read := codexHome(t, "", "model = \"gpt-5.5\"\n")
cx := codex(home)
if err := cx.Field("statusline").Set("on"); err != nil {
t.Fatal(err)
}
if err := cx.Unwire(); err != nil {
t.Fatal(err)
}
if got := read(); strings.Contains(got, "quota_line") || strings.Contains(got, codexStatusFeature) {
t.Fatalf("left after Disconnect:\n%s", got)
}
}
// A distro's Codex isn't offered the switch, running or stopped: the
// server would name this computer's magpie (only on this computer, as
// Claude Code's).
func TestWSLCodexNoStatusLine(t *testing.T) {
codexReadersAre(t, "0.171.0-alpha.13")
root, _ := claudeDistroHome(t, "")
os.MkdirAll(filepath.Join(root, "home", "me", ".codex"), 0o755)
d := distro{Name: "Ubuntu", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.codex": true}, Gateway: "172.20.0.1"}
k := wslKindOf("codex")
for name, a := range map[string]*Agent{"running": wslAgent(k, d), "stopped": asleep(wslAgent(k, d), k, d)} {
f := a.Field("statusline")
if f == nil {
t.Fatalf("%s distro: no statusline field", name)
}
if o := f.Options(nil); len(o) != 0 {
t.Errorf("%s distro offers %v", name, o)
}
}
if err := wslAgent(k, d).Field("statusline").Set("on"); err == nil {
t.Error("on taken in a distro")
}
}
+15 -1
View File
@@ -18,6 +18,7 @@ import (
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/yetone/magpie/internal/gateway"
@@ -25,6 +26,7 @@ import (
)
const statuslineUsage = `usage: magpie statusline [<provider|account>…]
magpie statusline --codex
one line for Claude Code's status line: the model the session's latest turn went
to through magpie, then each subscription and plan magpie has, as last read: its
windows' use ("5h 62% 7d 41%"), * on the one that answered last. Accounts that
@@ -36,7 +38,12 @@ const statuslineUsage = `usage: magpie statusline [<provider|account>…]
unless a status line of your own (claude-hud, a script) is there; or add it yourself:
"statusLine": {"type": "command", "command": "magpie statusline"}
It asks the gateway on this computer (the port in Settings' Gateway address, or MAGPIE_ADDR), never
a vendor, and prints nothing when the gateway isn't running.`
a vendor, and prints nothing when the gateway isn't running.
--codex is Codex's footer (Codex 0.171 on): an MCP server Codex starts, showing the
model the thread's latest turn went to and that account's windows or balance. Turn it
on with the status line square on Codex's row in the Agents page (or
magpie codex statusline on), which writes ~/.codex/config.toml's [mcp_servers.quota_line],
[features] tui_extensions_statusline and [tui] status_line_provider.`
// statuslineWait bounds each ask of the gateway: Claude Code shows the line
// only once the command ends.
@@ -44,6 +51,13 @@ const statuslineWait = time.Second
// statuslineCmd: magpie statusline [<provider|account>…]
func statuslineCmd(args []string) error {
if len(args) > 1 && strings.HasPrefix(args[1], "-") {
if args[1] == "--codex" && len(args) == 2 {
// Codex's footer: an MCP server Codex starts (statusline_codex.go)
return newCodexStatus(gateway.ClientURL()).serve(os.Stdin, os.Stdout)
}
return fmt.Errorf("magpie statusline takes providers or accounts, or --codex alone, not %q\n%s", args[1], statuslineUsage)
}
fmt.Println(statusline(os.Stdin, args[1:], gateway.ClientURL(), time.Now()))
return nil
}
+232
View File
@@ -0,0 +1,232 @@
package cli
// magpie statusline --codex: Codex's status line, magpie's (lyj1115 on X:
// the current account's quota, or the relay's balance, under Codex's chat
// box). Codex (0.171.0-alpha.12 on, behind [features]
// tui_extensions_statusline) draws its footer from a stdio MCP server
// whose tool advertises a statusline entrypoint
// (_meta["openai/ui"].entrypoints, its bundled create-statusline skill):
// it reads that resource about once a second, with the thread's state in
// params._meta["com.openai/codex-statusline-state"], and draws the UI tree
// the read returns; null clears the footer, and an error or a read past
// its one second stops the reads until the provider is picked again. This
// is that server, newline-delimited JSON-RPC on stdin and stdout. Each
// read asks the gateway on this computer what it already holds: the
// thread's latest route (Codex sends its thread id as session_id) and the
// accounts as last read (/v1/magpie/quotas?kept=1), never a vendor. The
// Agents page writes it into config.toml (internal/agent/codex_statusline.go).
//
// Its tool is listed to the model like any MCP tool, so its name and
// words name neither magpie nor a vendor.
import (
"bufio"
"cmp"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
const (
// CodexStatusServer and CodexStatusTool are the server's name in
// config.toml's [mcp_servers] and its tool's, as status_line_provider
// names them
CodexStatusServer = "quota_line"
CodexStatusTool = "statusline"
codexStatusURI = "ui://quota-line/footer"
// codexStatusState is where Codex puts the thread's state in a read
codexStatusState = "com.openai/codex-statusline-state"
)
// codexStatusWait bounds each ask of the gateway: Codex gives a read one
// second in all, and one past it stops the footer.
const codexStatusWait = 400 * time.Millisecond
// codexStatusKeep is how long the accounts read are kept between reads:
// Codex reads again a second after each one.
const codexStatusKeep = 5 * time.Second
// codexStatus answers Codex's reads from the gateway at base.
type codexStatus struct {
base string
client *http.Client
now func() time.Time
mu sync.Mutex
quotas []provider.Quota
quotasAt time.Time
}
func newCodexStatus(base string) *codexStatus {
return &codexStatus{base: base, client: &http.Client{Timeout: codexStatusWait}, now: time.Now}
}
// serve answers requests from in on out until in ends.
func (c *codexStatus) serve(in io.Reader, out io.Writer) error {
sc := bufio.NewScanner(in)
sc.Buffer(make([]byte, 64<<10), 8<<20)
enc := json.NewEncoder(out)
for sc.Scan() {
var req struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
reply := map[string]any{"jsonrpc": "2.0", "id": nil}
if err := json.Unmarshal(sc.Bytes(), &req); err != nil {
if strings.TrimSpace(sc.Text()) == "" {
continue
}
reply["error"] = map[string]any{"code": -32700, "message": "Parse error"}
} else if len(req.ID) == 0 || string(req.ID) == "null" {
continue // a notification
} else {
reply["id"] = req.ID
if res, ok := c.respond(req.Method, req.Params); ok {
reply["result"] = res
} else {
reply["error"] = map[string]any{"code": -32601, "message": "Method not found"}
}
}
if err := enc.Encode(reply); err != nil {
return err
}
}
return sc.Err()
}
var codexStatusToolDef = map[string]any{
"name": CodexStatusTool,
"title": "Quota",
"description": "The remaining quota or balance of the account this thread uses, as shown in the footer.",
"inputSchema": map[string]any{"type": "object", "properties": map[string]any{}},
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
"_meta": map[string]any{"openai/ui": map[string]any{
"entrypoints": []any{map[string]any{"type": "statusline", "resourceUri": codexStatusURI}},
}},
}
func (c *codexStatus) respond(method string, params json.RawMessage) (any, bool) {
switch method {
case "initialize":
return map[string]any{
"protocolVersion": "2025-06-18",
"capabilities": map[string]any{"tools": map[string]any{}, "resources": map[string]any{}},
"serverInfo": map[string]any{"name": CodexStatusServer, "version": "1"},
}, true
case "ping":
return map[string]any{}, true
case "tools/list":
return map[string]any{"tools": []any{codexStatusToolDef}}, true
case "tools/call":
// the model may call it: it is told the line the footer shows
var p struct {
Meta map[string]json.RawMessage `json:"_meta"`
}
_ = json.Unmarshal(params, &p)
line := strings.Join(c.cells(threadOf(p.Meta)), " · ")
return map[string]any{"content": []any{map[string]any{"type": "text", "text": cmp.Or(line, "No quota is known.")}}}, true
case "resources/list":
return map[string]any{"resources": []any{map[string]any{"name": "footer", "uri": codexStatusURI, "mimeType": "application/json"}}}, true
case "resources/templates/list":
return map[string]any{"resourceTemplates": []any{}}, true
case "resources/read":
var p struct {
URI string `json:"uri"`
Meta map[string]json.RawMessage `json:"_meta"`
}
_ = json.Unmarshal(params, &p)
tree, _ := json.Marshal(codexStatusTree(c.cells(threadOf(p.Meta))))
return map[string]any{"contents": []any{map[string]any{"uri": codexStatusURI, "mimeType": "application/json", "text": string(tree)}}}, true
}
return nil, false
}
// threadOf is the thread id in a read's state, "" when there is none.
func threadOf(meta map[string]json.RawMessage) string {
var st struct {
Thread struct {
ID string `json:"id"`
} `json:"thread"`
}
_ = json.Unmarshal(meta[codexStatusState], &st)
return strings.TrimSpace(st.Thread.ID)
}
// codexStatusTree is the footer: the model, then the account, or null
// (nothing shown) when the gateway told nothing.
func codexStatusTree(cells []string) any {
if len(cells) == 0 {
return nil
}
var kids []any
for i, s := range cells {
color := "status-limit"
if i == 0 && strings.HasPrefix(s, "→ ") {
color = "status-model"
}
kids = append(kids, map[string]any{"type": "text", "props": map[string]any{"color": color}, "children": []any{s}})
}
return map[string]any{"type": "row", "props": map[string]any{"gap": 2, "wrap": "wrap"}, "children": kids}
}
// cells are the footer's parts for thread: "→ provider/model" when the
// gateway has its route, then the account it went to.
func (c *codexStatus) cells(thread string) []string {
var wg sync.WaitGroup
model := ""
if thread != "" {
wg.Add(1)
go func() {
defer wg.Done()
var route struct {
Route *struct {
Asked string `json:"asked"`
Model string `json:"model"`
} `json:"route"`
}
if getJSON(c.client, c.base+"/v1/magpie/route?session="+url.QueryEscape(thread), &route) && route.Route != nil {
model = cmp.Or(route.Route.Model, route.Route.Asked)
}
}()
}
qs, ok := c.accounts()
wg.Wait()
if !ok {
return nil
}
var out []string
if model != "" {
out = append(out, "→ "+model)
}
now := c.now()
for _, q := range provider.CodexStatuslineCards(model, qs) {
out = append(out, provider.CodexStatuslineCard(q, now))
}
return out
}
// accounts are the gateway's kept quotas, read again once codexStatusKeep
// has gone by; ok is false when the gateway can't be asked.
func (c *codexStatus) accounts() ([]provider.Quota, bool) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.quotasAt.IsZero() && c.now().Sub(c.quotasAt) < codexStatusKeep {
return c.quotas, true
}
var quotas struct {
Data []provider.Quota `json:"data"`
}
if !getJSON(c.client, c.base+"/v1/magpie/quotas?kept=1", &quotas) {
c.quotasAt = time.Time{}
return nil, false
}
c.quotas, c.quotasAt = quotas.Data, c.now()
return c.quotas, true
}
+117
View File
@@ -0,0 +1,117 @@
package cli
import (
"bufio"
"encoding/json"
"io"
"strings"
"testing"
"time"
)
// codexRead is a resources/read as Codex's TUI sends it (statusline.d.ts:
// the thread's state in params._meta), cut to the fields around the one
// read.
const codexRead = `{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"ui://quota-line/footer","_meta":{"com.openai/codex-statusline-state":{"thread":{"id":"6f1d2c3a-9b8e-4a7f-8c1d-2e3f4a5b6c7d"},"model":{"name":"gpt-5.5"},"account":{"rate_limits":null}}}}}`
// mcpTalk sends lines to a codexStatus and returns its replies by id.
func mcpTalk(t *testing.T, c *codexStatus, lines ...string) map[string]map[string]any {
t.Helper()
pr, pw := io.Pipe()
go func() {
c.serve(strings.NewReader(strings.Join(lines, "\n")+"\n"), pw)
pw.Close()
}()
out := map[string]map[string]any{}
sc := bufio.NewScanner(pr)
for sc.Scan() {
var m map[string]any
if err := json.Unmarshal(sc.Bytes(), &m); err != nil {
t.Fatalf("%v: %s", err, sc.Text())
}
id, _ := json.Marshal(m["id"])
out[string(id)] = m
}
return out
}
// lyj1115 on X: Codex's footer shows the model the thread went to and
// that account's windows, from what the gateway kept (never a vendor
// read); a tool Codex's statusline picker takes (its entrypoint), whose
// words name neither magpie nor a vendor, since the model is told them.
func TestCodexStatuslineServer(t *testing.T) {
now := time.Now()
s := statuslineGateway(t, now)
c := newCodexStatus(s.URL)
got := mcpTalk(t, c,
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"codex-mcp-client","version":"0.171.0"}}}`,
`{"jsonrpc":"2.0","method":"notifications/initialized"}`,
`{"jsonrpc":"2.0","id":2,"method":"tools/list"}`,
codexRead,
`{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"ui://quota-line/footer","_meta":{"com.openai/codex-statusline-state":{"thread":{"id":"another"}}}}}`,
`{"jsonrpc":"2.0","id":5,"method":"nope"}`,
)
if len(got) != 5 {
t.Fatalf("replies: %v", got)
}
if res, _ := got["1"]["result"].(map[string]any); res["protocolVersion"] != "2025-06-18" {
t.Fatalf("initialize: %v", got["1"])
}
tools, _ := got["2"]["result"].(map[string]any)["tools"].([]any)
tool, _ := tools[0].(map[string]any)
b, _ := json.Marshal(tool)
if tool["name"] != "statusline" || !strings.Contains(string(b), `"entrypoints":[{"resourceUri":"ui://quota-line/footer","type":"statusline"}]`) {
t.Fatalf("tool: %s", b)
}
if low := strings.ToLower(string(b)); strings.Contains(low, "magpie") || strings.Contains(low, "codex") || strings.Contains(low, "openai\"") {
t.Fatalf("the tool the model is told of names magpie or a vendor: %s", b)
}
tree := func(id string) string {
res, _ := got[id]["result"].(map[string]any)
cs, _ := res["contents"].([]any)
c, _ := cs[0].(map[string]any)
if c["mimeType"] != "application/json" {
t.Fatalf("read %s: %v", id, got[id])
}
return c["text"].(string)
}
// the thread's route is claude's: its account that answered last
if want := `{"children":[{"children":["→ claude/claude-opus-5-5"],"props":{"color":"status-model"},"type":"text"},{"children":["claude a@example.com 5h 62% 7d 41%"],"props":{"color":"status-limit"},"type":"text"}],"props":{"gap":2,"wrap":"wrap"},"type":"row"}`; tree("3") != want {
t.Fatalf("read:\n got %s\nwant %s", tree("3"), want)
}
// a thread the gateway has no route for: the account that answered last
if !strings.Contains(tree("4"), `"claude a@example.com 5h 62% 7d 41%"`) || strings.Contains(tree("4"), "→") {
t.Fatalf("read with no route: %s", tree("4"))
}
if got["5"]["error"] == nil {
t.Fatalf("unknown method answered: %v", got["5"])
}
}
// A relay key's balance is the account's line; a gateway that doesn't
// answer clears the footer (null) and never errors, which would stop
// Codex's reads.
func TestCodexStatuslineBalanceAndDown(t *testing.T) {
now := time.Now()
c := newCodexStatus(statuslineGateway(t, now).URL)
if got := c.cells(""); len(got) != 1 || got[0] != "claude a@example.com 5h 62% 7d 41%" {
t.Fatalf("no thread: %q", got)
}
down := newCodexStatus("http://127.0.0.1:1")
got := mcpTalk(t, down, codexRead)
res, _ := got["3"]["result"].(map[string]any)
cs, _ := res["contents"].([]any)
if len(cs) != 1 || cs[0].(map[string]any)["text"] != "null" {
t.Fatalf("gateway down: %v", got["3"])
}
}
// statusline --codex takes nothing else, and a flag it doesn't know is
// refused, never read as an account.
func TestStatuslineFlags(t *testing.T) {
for _, args := range [][]string{{"statusline", "--codex", "x"}, {"statusline", "--nope"}, {"statusline", "--help"}} {
if err := statuslineCmd(args); err == nil || !strings.Contains(err.Error(), "usage") {
t.Fatalf("%q: %v", args, err)
}
}
}
+4 -3
View File
@@ -4752,10 +4752,11 @@ function holdPop(pop, room) {
if (!(parseFloat(getComputedStyle(pop).maxHeight) <= room)) pop.style.maxHeight = room + "px";
}
// a Claude Code switch: a square a click turns on or off, lit while on.
// an agent's switch: a square a click turns on or off, lit while on.
const TOGGLES = {
ultracode: { label: "ultracode", note: "Claude plans a workflow for each substantive task", said: "{agent} ultracode → {value}" },
statusline: { label: "status line", note: "the 5h and 7d use of the accounts magpie serves, under Claude Code's prompt", said: "{agent} status line → {value}" },
// its note is the agent's own, on its field's on (Codex's footer isn't Claude Code's)
statusline: { label: "status line", said: "{agent} status line → {value}" },
};
function toggled(f) { return Object.hasOwn(TOGGLES, f.key); }
function fieldToggle(a, f) {
@@ -4763,7 +4764,7 @@ function fieldToggle(a, f) {
const on = f.value === "on";
const b = el("button", "field extra" + (on ? " set" : ""));
b.append(svg(EXTRA_GLYPH[f.key], 13, 1.5));
b.title = t("{label}: {value}", { label: t(k.label), value: t(on ? "on" : "off") }) + "\n" + t(k.note);
b.title = t("{label}: {value}", { label: t(k.label), value: t(on ? "on" : "off") }) + "\n" + t(k.note || f.options?.find((o) => o.value == "on")?.note || "");
b.setAttribute("aria-label", b.title);
b.setAttribute("aria-pressed", String(on));
b.dataset.key = f.key;
+4
View File
@@ -1142,6 +1142,7 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"status line": "状态栏",
"the 5h and 7d use of the accounts magpie serves, under Claude Code's prompt": "Claude Code 输入框下方显示 magpie 所用账号的 5 小时和 7 天用量",
"the remaining quota or balance of the account in use, under Codex's prompt": "Codex 输入框下方显示当前账号的剩余额度或中转余额",
"{agent} status line → {value}": "{agent} 状态栏 → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "已打开的 Claude Code 会话仍用启动时的推理强度,重开后生效。",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "已打开的 Claude Code 会话仍用启动时的 ultracode 设置,重开后生效。",
@@ -6642,6 +6643,7 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"status line": "狀態列",
"the 5h and 7d use of the accounts magpie serves, under Claude Code's prompt": "Claude Code 輸入框下方顯示 magpie 所用帳號的 5 小時和 7 天用量",
"the remaining quota or balance of the account in use, under Codex's prompt": "Codex 輸入框下方顯示目前帳號的剩餘額度或中轉餘額",
"{agent} status line → {value}": "{agent} 狀態列 → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "已開啟的 Claude Code 會話仍用啟動時的推理強度,重開後生效。",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "已開啟的 Claude Code 會話仍用啟動時的 ultracode 設定,重開後生效。",
@@ -12102,6 +12104,7 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"status line": "ステータスライン",
"the 5h and 7d use of the accounts magpie serves, under Claude Code's prompt": "Claude Code の入力欄の下に、magpie が使うアカウントの 5 時間と 7 日の使用量を表示します",
"the remaining quota or balance of the account in use, under Codex's prompt": "Codex の入力欄の下に、使用中のアカウントの残りクォータまたはリレーの残高を表示します",
"{agent} status line → {value}": "{agent} ステータスライン → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "開いている Claude Code セッションは起動時の推論レベルのままです。反映するには再起動してください。",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "開いている Claude Code セッションは起動時の ultracode のままです。反映するには再起動してください。",
@@ -17582,6 +17585,7 @@ const I18N = {
"{agent} ultracode → {value}": "{agent} ultracode → {value}",
"status line": "Statuszeile",
"the 5h and 7d use of the accounts magpie serves, under Claude Code's prompt": "die 5-Stunden- und 7-Tage-Nutzung der Konten, die magpie nutzt, unter der Eingabe von Claude Code",
"the remaining quota or balance of the account in use, under Codex's prompt": "das verbleibende Kontingent oder Guthaben des genutzten Kontos, unter der Eingabe von Codex",
"{agent} status line → {value}": "{agent} Statuszeile → {value}",
"an open Claude Code session keeps the effort it started with — restart it to use this.": "eine offene Claude-Code-Sitzung behält den Reasoning-Effort vom Start — zum Übernehmen neu starten.",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.": "eine offene Claude-Code-Sitzung behält die ultracode-Einstellung vom Start — zum Übernehmen neu starten.",
@@ -0,0 +1,108 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Codex's status line (lyj1115 on X: the account's quota or the relay's
// balance under Codex's chat box, off unless turned on): the same square
// as Claude Code's on Codex's row, its title Codex's own note (the
// option's, not Claude Code's 5h and 7d), a click posting statusline on
// and off, in every language. A Codex the switch isn't offered to (too old
// to draw it, or a provider of the user's own) shows no square. Chromium
// and WebKit, the window and the narrow tray panel.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const NOTE = "the remaining quota or balance of the account in use, under Codex's prompt";
const codex = (id, value, offered) => ({
id, name: "Codex " + id, icon: "codex-color", path: "/test/" + id, wired: true,
fields: [
{ key: "model", label: "model", value: "gpt-5.5", options: [{ value: "gpt-5.5", icon: "openai", ref: "codex/gpt-5.5" }] },
{ key: "statusline", label: "status line", value, options: offered ? [{ value: "on", note: NOTE }] : [] },
],
});
function serve(lang, sets) {
let on = false;
const st = () => ({ agents: [codex("mine", on ? "on" : "", true), codex("theirs", "", false)], profiles: [], settings: { lang, theme: "light" } });
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: st() });
if (url.pathname === "/api/set") {
const b = req.postDataJSON();
sets.push(b);
if (b.field === "statusline") on = b.value === "on";
return route.fulfill({ json: st() });
}
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { label: "status line", note: "under Codex's prompt", said: "status line → on" },
zh: { label: "状态栏", note: "Codex 输入框下方显示当前账号的剩余额度或中转余额", said: "状态栏 → 开启" },
"zh-TW": { label: "狀態列", note: "Codex 輸入框下方顯示目前帳號的剩餘額度或中轉餘額", said: "狀態列 → 開啟" },
ja: { label: "ステータスライン", note: "リレーの残高", said: "ステータスライン → オン" },
de: { label: "Statuszeile", note: "Guthaben des genutzten Kontos", said: "Statuszeile → an" },
};
const row = (id) => `.row.agent[data-id="${id}"]`;
const square = (id) => `${row(id)} .field[data-key="statusline"]`;
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: Codex's status line is a switch`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => {
if (errors.length) console.log(errors);
await browser.close();
});
for (const mode of ["", "panel"]) {
await t.test(mode || "window", async () => {
const sets = [];
const page = await (await browser.newContext({ viewport: { width: mode ? 400 : 900, height: 560 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, sets));
await page.goto("http://magpie.test/" + (mode ? "?mode=" + mode : ""));
await page.locator(row("mine")).waitFor();
// one row open at a time: the user's first, then magpie's
for (const id of ["theirs", "mine"]) {
await page.locator(`${row(id)} ${mode ? ".ag-sum" : ".ag-link"}`).click();
await page.waitForTimeout(mode ? 700 : 200);
if (id === "theirs") assert.equal(await page.locator(square("theirs")).count(), 0, "a square on a Codex it isn't offered to");
}
const sq = page.locator(square("mine")).first();
await sq.waitFor();
assert.equal(await sq.getAttribute("aria-pressed"), "false");
const title = await sq.getAttribute("title");
assert.ok(title.includes(w.label) && title.includes(w.note) && !/5h|5 小时|5 小時|5 時間|5-Stunden/.test(title), `title ${JSON.stringify(title)}`);
const box = await sq.boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= (mode ? 400 : 900), "the square is off the page");
await sq.click();
await page.waitForTimeout(300);
assert.deepEqual(sets, [{ agent: "mine", field: "statusline", value: "on" }]);
assert.ok((await page.locator("#status").textContent()).includes(w.said), await page.locator("#status").textContent());
const lit = page.locator(square("mine")).first();
assert.equal(await lit.getAttribute("aria-pressed"), "true");
assert.match(await lit.getAttribute("class"), /\bset\b/);
await lit.click();
await page.waitForTimeout(300);
assert.deepEqual(sets[1], { agent: "mine", field: "statusline", value: "" });
});
}
assert.deepEqual(errors, []);
});
}
}
+45
View File
@@ -93,3 +93,48 @@ func StatuslineCard(q Quota, now time.Time) string {
}
return strings.Join(cells, " ")
}
// CodexStatuslineCards are the accounts a Codex thread's footer shows
// (lyj1115 on X: the quota of the account in use, or the relay's balance,
// under Codex's chat box): those of the provider the thread's latest turn
// went to (model is provider/model), the one that answered last of them,
// a key's balance as well as a subscription's windows; with no such
// account, the one that answered last of all.
func CodexStatuslineCards(model string, qs []Quota) []Quota {
shown := func(q Quota) bool { return len(q.Windows) > 0 || q.Kind == "balance" && q.Balance != "" }
latest := func(keep func(Quota) bool) []Quota {
var out []Quota
for _, q := range qs {
if !shown(q) || !keep(q) {
continue
}
switch {
case len(out) == 0:
out = []Quota{q}
case q.LastServedAt != nil && (out[0].LastServedAt == nil || q.LastServedAt.After(*out[0].LastServedAt)):
out[0] = q
}
}
return out
}
if p, _, ok := strings.Cut(model, "/"); ok && p != "" {
if out := latest(func(q Quota) bool { return q.Provider == p }); len(out) > 0 {
return out
}
}
return latest(func(q Quota) bool { return q.Last })
}
// CodexStatuslineCard is one account as Codex's footer shows it: its
// windows as StatuslineCard has them, or a key's balance.
func CodexStatuslineCard(q Quota, now time.Time) string {
if len(q.Windows) == 0 && q.Balance != "" {
name := q.Provider
if q.Alias != "" {
name += " " + q.Alias
}
return name + " " + q.Balance
}
q.Last = false // one account is shown: no star to tell it apart
return StatuslineCard(q, now)
}
@@ -0,0 +1,41 @@
package provider
import (
"strings"
"testing"
"time"
)
// Codex's footer: the accounts of the provider the thread went to (the
// one that answered last of them), a relay key by its balance; with no
// route, or none of that provider's, the account that answered last.
func TestCodexStatuslineCards(t *testing.T) {
now := time.Now()
at := func(d time.Duration) *time.Time { x := now.Add(d); return &x }
qs := []Quota{
{Provider: "claude", User: "a@x", LastServedAt: at(-time.Minute), Last: true, Windows: []QuotaSpan{{Name: "5 hours", Used: 62}}},
{Provider: "codex", User: "c@x", LastServedAt: at(-time.Hour), Windows: []QuotaSpan{{Name: "5 hours", Used: 10}}},
{Provider: "codex", User: "d@x", LastServedAt: at(-2 * time.Minute), Windows: []QuotaSpan{{Name: "5 hours", Used: 20}}},
{Provider: "relay", Kind: "balance", Balance: "$4.20", Alias: "work"},
{Provider: "empty", Kind: "balance"},
}
name := func(cs []Quota) string {
var out []string
for _, q := range cs {
out = append(out, CodexStatuslineCard(q, now))
}
return strings.Join(out, " · ")
}
for model, want := range map[string]string{
"codex/gpt-5.5": "codex d@x 5h 20%",
"relay/glm-5": "relay work $4.20",
"claude/opus": "claude a@x 5h 62%",
"empty/m": "claude a@x 5h 62%",
"": "claude a@x 5h 62%",
"gpt-5.5": "claude a@x 5h 62%",
} {
if got := name(CodexStatuslineCards(model, qs)); got != want {
t.Errorf("%q: %q, want %q", model, got, want)
}
}
}