agent, gui: Codex isn't handed to a magpie it can't reach, through a proxy or after magpie quits (Muma102kMichael, Leon920717, thisisvainxx on X)

Muma102kMichael (Windows): after magpie took Codex over, every project
and every new chat got 502. Codex's reqwest sends its requests for
http://127.0.0.1:3425 through HTTP_PROXY/ALL_PROXY or the system's
proxy, and only an exact IP or a CIDR in NO_PROXY (on Windows, with no
NO_PROXY, the bypass list with "*." removed) keeps 127.0.0.1 off it:
"127.*" and "localhost" don't, and macOS' exceptions aren't read. A
proxy in global mode answers 502 for every request. With [features]
respect_system_proxy Codex asks the system alone and goes direct with
no proxy set there. Account failover, which magpie writes uninvited
when 2+ ChatGPT accounts are on, put all of Codex's traffic, its own
models included, behind that proxy.

- codex_proxy.go works out Codex's proxy the way Codex does and probes
  GET / through it (must answer as magpie). Failover waits for that
  probe and isn't written while the proxy doesn't pass Codex on; one
  written before goes again.
- New drift kind "proxied": the Agents pill says Codex reaches magpie
  through a proxy that doesn't pass its requests on, How to fix names
  the fix (DIRECT rule for 127.0.0.0/8, NO_PROXY=127.0.0.1, or
  127.0.0.1 in Windows' bypass list), and the dialog has a one-click
  Disconnect from magpie (also on unreachable drift).
- Leon920717: after quitting magpie Codex kept retrying. The app that
  serves the gateway now takes failover out in OnShutdown
  (EndCodexFailover); the next start's Sync writes it again. A
  connected Codex is kept (its model is magpie's; Disconnect restores).
  A kill or crash still leaves failover in place.
- thisisvainxx: "several restarts". Codex's app-server keeps the base
  URL it started with, and KeepCodexDaemonCurrent ends with magpie, so
  EndCodexFailover restarts it when no codex session is on it.

Run:
- real codex-cli 0.162.1 in a sandbox CODEX_HOME against a fake 502
  proxy and a fake gateway: NO_PROXY=localhost,127.* -> 30 POSTs to the
  proxy; NO_PROXY=localhost -> proxy; NO_PROXY=127.0.0.1 -> gateway;
  respect_system_proxy with HTTP_PROXY set -> gateway directly.
- go test -tags nogui ./internal/agent/ (full package, 465s, ok) and
  the new tests after the daemon change; each new test went red with
  its guarantee broken by hand (failover gate, drift, EndFailover,
  daemon restart on quit).
- node --test agent-proxied/agent-unreachable/agent-failover/
  agent-disconnect-preview: 104 passed, chromium + webkit, en zh zh-TW
  ja de, window and panel.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui clean.
Not tried: the quit path in the real app, on the Windows box, or
whether computer use / remote connection broke for this same reason.
This commit is contained in:
yetone
2026-10-11 23:00:00 +08:00
parent 8029d98b7e
commit f156d90460
12 changed files with 765 additions and 15 deletions
+5 -4
View File
@@ -16,7 +16,7 @@ something else shows up as drift.
| Fields and options | A `Field` has `Get`, `Set` and `Options`. `Set("")` returns the field to the agent's default and takes magpie's wiring out. `Quiet` fields follow another field until set (`Follows`, such as Claude Code's tiers). An `Option` carries the picker's facts: `Direct`, `Via`, `Same`, `Alias`, `Rate` and `Context`. | [`agent.go`](../../internal/agent/agent.go), [`route.go`](../../internal/agent/route.go) |
| The list of agents | `All` lists every agent magpie knows, then the WSL agents (`wslAgents`). `Clients` lists every agent whose requests the gateway knows by name, which `usage.Agents` reads. One file per agent: `claude.go`, `codex.go`, `opencode` in `agents.go`, and so on. | [`agents.go`](../../internal/agent/agents.go) |
| Connect | `ConnectHow` picks the model an agent starts on and reports how. `How` is one of: `kept`, `again`, `joined`, `magpie`, `same`, `alike`, `default` or `first` (#726). With no models to give, it returns `NoModelsError` (code `no_models`). | [`applied.go`](../../internal/agent/applied.go) |
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now. | [`applied.go`](../../internal/agent/applied.go) |
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable`, `proxied` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now. | [`applied.go`](../../internal/agent/applied.go) |
| What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
| Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
@@ -60,9 +60,10 @@ something else shows up as drift.
- A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835).
- `Reapply` on `unwired` sets again every field on one of magpie's models and every field set to magpie itself (`magpieID`, as `Wired` takes it): Claude Desktop's drift shows on a tier, and its `provider` field is what writes the gateway back (dumplings on Discord). Claude Desktop's `Check` judges only the set of folders whose Claude-3p it ran in last (`desktopRead`, by `desktopdir.LastRun`), every set when it ran in none: magpie writes both of an MSIX install's sets, and 2.31226 reads the real `%LOCALAPPDATA%\Claude-3p`, so the package's copy being emptied is not Desktop off magpie.
- `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` in `TestMain`.
- `proxied` (Muma102kMichael on X: every project and every new chat 502 after magpie took Codex over) is this machine's Codex sending its requests for the gateway through a proxy that doesn't pass them on, while the gateway answers here ([`codex_proxy.go`](../../internal/agent/codex_proxy.go)). Codex's reqwest takes `HTTP_PROXY`/`ALL_PROXY`, else the system's proxy, and lets only an exact IP or a CIDR in `NO_PROXY` (on Windows, with no `NO_PROXY`, the bypass list with `*.` taken out) keep 127.0.0.1 off it: `127.*` and `localhost` don't, and macOS' exceptions aren't read. With `[features] respect_system_proxy` it asks the system alone, matching its list itself, wildcards and `<local>` included, and goes direct when no proxy is set there (codex-rs `outbound_proxy`; tried with codex-cli 0.162.1). `codexProxyFor` works out that proxy the same way, and a `GET /` through it must come back as magpie's (`proxyProbe`), tried as `reachable` is. Its pill says how to fix it, as `unreachable`'s does, and the dialog has Disconnect from magpie. Account failover, which magpie writes uninvited, waits for that probe (`codexProxyOK`) and isn't written while the proxy doesn't pass Codex on, and one it wrote goes again. Tests stub the env, the system proxy and `proxyProbe` in `TestMain`.
- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them.
- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again.
- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.
- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading.
@@ -83,9 +84,9 @@ go test -tags nogui ./internal/agent -run '^TestAnte'
go test -tags nogui ./internal/agent -run '^TestAstrBot'
go test -tags nogui ./internal/agent -run '^TestJcode'
go test -tags nogui ./internal/agent -run '^TestPlugged'
go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays'
go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays|TestCodexProxyFor|TestRealProxyProbe|TestCodexFailoverHeldWhileProxyDoesNotPassOn|TestCodexProxiedDrift|TestCodexFailoverEndsWithMagpie'
go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays'
go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune'
node --test internal/gui/tests/context-tune.test.cjs
node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs internal/gui/tests/plugin-agent.test.cjs
node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs internal/gui/tests/agent-proxied.test.cjs internal/gui/tests/plugin-agent.test.cjs
```
+10
View File
@@ -167,6 +167,11 @@ type Agent struct {
// the Agents page says so and what turns it off, and the gateway lists
// it only its own models.
FailingOver func() bool
// EndFailover takes out what account failover wrote, for magpie
// quitting: left there, the agent would be pointed at a gateway that
// no longer answers, and retry till magpie is open again (Leon920717
// on X). The next start's Sync writes it again.
EndFailover func() error
// Follow, for an agent whose own picker moves its main model where
// magpie keeps other settings following it (Claude Code's /model and
// its tiers), brings those along to the model picked there. Run as the
@@ -239,6 +244,11 @@ type Agent struct {
// move, when set, points the agent's config at to where it names the
// gateway at from: an address of WSL's that changed (#1013).
move func(from, to string) error
// viaProxy, when set, says whether the agent's requests for the
// gateway get there through the proxy it sends them by (ok), whether
// that is known yet, and the proxy and where it is set; ok with no
// proxy when it sends them straight there (see codex_proxy.go).
viaProxy func() (ok, known bool, proxy, from string)
// dirShared says Dir is a folder another agent keeps its files in too
// (omp's, when PI_CODING_AGENT_DIR points it at Pi's): that it is there
// says nothing of this agent.
+7 -1
View File
@@ -120,7 +120,10 @@ type Drift struct {
// nothing of it reached the gateway — it runs on an old
// config, or something outside the file overrides it;
// "unreachable" the config is right, but the address off loopback
// it names the gateway at doesn't answer (#1013).
// it names the gateway at doesn't answer (#1013);
// "proxied" the config is right, but the agent sends its requests
// for the gateway through a proxy (Addr) that doesn't
// pass them on to it (codex_proxy.go).
Kind string `json:"kind"`
Field string `json:"field"` // the field it shows on
Now string `json:"now,omitempty"` // what that field says now
@@ -192,6 +195,9 @@ func (a *Agent) Drift() *Drift {
if d := a.unreachable(on, vals[on.Key]); d != nil {
return d
}
if d := a.proxied(on, vals[on.Key]); d != nil {
return d
}
}
if a.Reached != nil && onMagpie {
if at, to, refused := a.Reached(rec.At); !at.IsZero() {
+39 -1
View File
@@ -4,6 +4,7 @@ import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
@@ -512,6 +513,13 @@ func codexIn(at place) *Agent {
return nil
}
on := !disconnected() && codexFailover()
// failover is magpie's own idea, not the user's: never handed
// Codex's requests while a proxy they'd go through doesn't pass
// them on to magpie, which would have every turn fail with 502
// (codex_proxy.go); one written before goes again
if on && at.spell == nil && !codexProxyOK(path, at.gw()) {
on = false
}
if mirror {
t, _ := edit.GetTOMLTable(path, "model_providers."+p)
hasGateway := t["base_url"] == at.codexURL()
@@ -868,7 +876,13 @@ func codexIn(at place) *Agent {
Beside: beside,
Routed: routed,
FailingOver: failingOver,
OwnVia: codexOwnViaMagpie,
EndFailover: func() error {
if !failingOver() {
return nil
}
return errors.Join(dropMirrorFailover(), dropBase())
},
OwnVia: codexOwnViaMagpie,
Sync: func() error {
// model_provider = "magpie" left with its table gone (taken by
// another tool, or a hand edit), which keeps Codex from loading
@@ -1184,6 +1198,7 @@ func codexIn(at place) *Agent {
// and moved to WSL's new one when that changed (#1013)
if at.spell == nil {
a.reach = at.base
a.viaProxy = func() (bool, bool, string, string) { return codexThroughProxy(path, at.gw()) }
a.move = func(from, to string) error { return codexMoveGateway(path, from, to) }
}
return a
@@ -1442,6 +1457,29 @@ func codexFailover() bool {
return false
}
// EndCodexFailover takes account failover out of this machine's Codex
// as the magpie serving its gateway quits (EndFailover): Codex goes
// straight to OpenAI again rather than retrying a gateway that's gone.
// The app-server codex sessions share read the old base URL as it started
// and keeps it, and KeepCodexDaemonCurrent ends with magpie, so it is
// restarted here, when no session is on it (thisisvainxx on X: back on
// its own config, Codex took "several restarts").
func EndCodexFailover() error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
a := codex(home)
if !a.FailingOver() {
return nil
}
if err := a.EndFailover(); err != nil {
return err
}
codexDaemonCheck(a.Path)
return nil
}
// CodexOwnOnly reports whether the Codex that asks the gateway for its
// model list there (/backend-api/codex/models) reaches magpie for account
// failover alone (FailingOver), to be handed only its own models (#1385).
+228
View File
@@ -0,0 +1,228 @@
package agent
import (
"encoding/json"
"net"
"net/http"
"net/url"
"os"
"path"
"runtime"
"strings"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/netproxy"
)
// Codex sends its requests to magpie's gateway, http://127.0.0.1:3425, the
// way it sends every other: through a proxy when one is set (Muma102kMichael
// on X: every project and every new chat 502, "a local gateway config and a
// proxy switch, two pitfalls stacked"). Its HTTP client is reqwest with its
// default features (codex-rs Cargo.toml), whose proxy is hyper-util's
// Matcher::from_system: HTTP_PROXY/ALL_PROXY, else the system's proxy
// (Windows' Internet Options, macOS' network settings), and nothing goes
// around it but what NO_PROXY names — or, with no NO_PROXY, Windows'
// ProxyOverride — as an IP, a CIDR or "*" for an address: "127.*" and
// "localhost" there don't keep 127.0.0.1 off it, and macOS' exceptions
// aren't read at all. A proxy that sends 127.0.0.1 on to a server of its own
// (Clash in global mode, a rule set with no LAN-direct rule) answers 502,
// and Codex is down on every model, its own included once magpie carries
// them. With [features] respect_system_proxy (codex-rs outbound_proxy),
// Codex asks the system alone: Windows' bypass list is matched with its
// wildcards and <local>, macOS' exceptions likewise, and with no proxy set
// there it goes direct.
//
// So before magpie hands Codex's requests to the gateway uninvited (account
// failover), and while it has them, it asks the way Codex would go: through
// which proxy, and whether a request sent through it reaches magpie (Drift
// kind "proxied").
// codexProxyEnv, codexSystemProxy and codexProxyOS are what codexProxyFor
// reads; vars so tests can say.
var (
codexProxyEnv = os.Getenv
codexSystemProxy = netproxy.System
codexProxyOS = runtime.GOOS
)
// codexProxyFor is the proxy this machine's Codex, configured by the
// config.toml at cfg, sends a request for base through, and where that
// proxy is set ("HTTP_PROXY", "the system's proxy settings"); "" when it
// goes straight there.
func codexProxyFor(cfg, base string) (proxy, from string) {
u, err := url.Parse(base)
if err != nil || u.Hostname() == "" {
return "", ""
}
host := u.Hostname()
env := func(keys ...string) string {
for _, k := range keys {
if v := strings.TrimSpace(codexProxyEnv(k)); v != "" {
return v
}
}
return ""
}
httpKeys := []string{"HTTP_PROXY", "http_proxy"}
if u.Scheme == "https" {
httpKeys = []string{"HTTPS_PROXY", "https_proxy"}
}
if f, _ := edit.GetTOMLTable(cfg, "features"); f["respect_system_proxy"] == "true" {
// the system's alone, its own bypass list deciding: with no proxy
// set there Codex goes direct, HTTP_PROXY or not (the environment's
// count only when the system can't be read; tried with codex-cli
// 0.162.1)
sys := codexSystemProxy()
if sys.URL == "" || systemBypassed(host, sys.Bypass) {
return "", ""
}
return sys.URL, systemProxyName()
}
// reqwest's: each of the environment's first, the system's where it
// names none, then ALL_PROXY; NO_PROXY, or Windows' bypass list without
// it, goes around them
p, k := env(httpKeys...), httpKeys[0]
no := env("NO_PROXY", "no_proxy")
sys := codexSystemProxy()
if p == "" && sys.URL != "" {
p, k = sys.URL, systemProxyName()
}
if p == "" {
p, k = env("ALL_PROXY", "all_proxy"), "ALL_PROXY"
}
if no == "" && codexProxyOS == "windows" && sys.URL != "" {
no = strings.ReplaceAll(strings.Join(sys.Bypass, ","), "*.", "")
}
if p == "" || reqwestNoProxy(host, no) {
return "", ""
}
return p, k
}
func systemProxyName() string {
if codexProxyOS == "windows" {
return "Windows' proxy settings"
}
return "the system's proxy settings"
}
// reqwestNoProxy is hyper-util's NoProxy.contains: entries apart by commas;
// an address is matched only by an IP or a CIDR that holds it, a name by
// itself or a domain it is under; "*" matches every name, never an
// address.
func reqwestNoProxy(host, list string) bool {
host = strings.Trim(host, "[]")
ip := net.ParseIP(host)
for _, e := range strings.Split(list, ",") {
e = strings.TrimSpace(e)
if e == "" {
continue
}
if ip != nil {
if _, n, err := net.ParseCIDR(e); err == nil && n.Contains(ip) {
return true
}
if x := net.ParseIP(e); x != nil && x.Equal(ip) {
return true
}
continue
}
d := strings.TrimPrefix(e, ".")
if e == "*" || strings.EqualFold(host, d) || strings.HasSuffix(strings.ToLower(host), "."+strings.ToLower(d)) {
return true
}
}
return false
}
// systemBypassed is Codex's own match of a host against the system's bypass
// list (codex-rs outbound_proxy/windows.rs): <local> is a name with no dot,
// an entry with * a wildcard, any other the host itself or, with a leading
// dot, a domain it is under.
func systemBypassed(host string, bypass []string) bool {
host = strings.ToLower(strings.Trim(host, "[]"))
for _, e := range bypass {
e = strings.ToLower(strings.TrimSpace(e))
e = strings.TrimPrefix(strings.TrimPrefix(e, "http://"), "https://")
switch {
case e == "":
case e == "<local>":
if !strings.Contains(host, ".") {
return true
}
case e == "*":
return true
case strings.HasPrefix(e, "."):
if host == e[1:] || strings.HasSuffix(host, e) {
return true
}
case strings.Contains(e, "*"):
if ok, _ := path.Match(e, host); ok {
return true
}
case host == e:
return true
}
}
return false
}
// proxyProbe says whether a request for base sent through proxy is answered
// by magpie: its gateway's GET / names it. A proxy's own 502, or anything
// else that isn't magpie, is not. A var for tests.
var proxyProbe = realProxyProbe
func realProxyProbe(base, proxy string) bool {
p, err := netproxy.Parse(proxy)
if err != nil {
return false
}
c := &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{Proxy: http.ProxyURL(p)}}
res, err := c.Get(strings.TrimSuffix(base, "/") + "/")
if err != nil {
return false
}
defer res.Body.Close()
var info struct {
Name string `json:"name"`
}
return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(&info) == nil && info.Name == "magpie"
}
// codexThroughProxy says whether Codex, configured by cfg, gets to the
// gateway at base: true when it goes there directly, or through a proxy
// that is known to pass its requests on. known is false while that proxy
// hasn't been tried yet; a try is started then (see reachable).
func codexThroughProxy(cfg, base string) (ok, known bool, proxy, from string) {
proxy, from = codexProxyFor(cfg, base)
if proxy == "" {
return true, true, "", ""
}
ok, known = probed("proxy "+proxy+" "+base, func() bool { return proxyProbe(base, proxy) })
return ok, known, proxy, from
}
// codexProxyOK is codexThroughProxy waited for: whether Codex gets to the
// gateway at base, a proxy in its way tried now when it hasn't been.
func codexProxyOK(cfg, base string) bool {
proxy, _ := codexProxyFor(cfg, base)
return proxy == "" || probedNow("proxy "+proxy+" "+base, func() bool { return proxyProbe(base, proxy) })
}
// codexProxiedDetail says what keeps Codex off magpie through proxy, and
// how to get it there.
func codexProxiedDetail(base, proxy, from string) string {
host := strings.TrimPrefix(base, "http://")
d := "Codex sends its requests for magpie (" + host + ") through the proxy at " + proxy + ", set in " + from + ", and that proxy doesn't pass them on to magpie: every turn fails, with 502 Bad Gateway, whichever model it is on. " +
"Have the proxy send 127.0.0.1 direct (a DIRECT rule for 127.0.0.0/8, or rule mode rather than global), "
switch {
case strings.Contains(from, "PROXY"):
d += "or add 127.0.0.1 to NO_PROXY, "
case codexProxyOS == "windows":
d += "or add 127.0.0.1 to \"Don't use the proxy server for addresses beginning with\" in Windows' proxy settings (127.* there is not enough for Codex), "
default:
d += "or set NO_PROXY=127.0.0.1 for Codex, "
}
return d + "then quit and reopen Codex. Until then, Disconnect from magpie puts Codex's config back as it was."
}
+272
View File
@@ -0,0 +1,272 @@
package agent
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
)
// proxyAs has codexProxyFor read env, sys and goos, and proxyProbe answer
// with *works, until the test ends.
func proxyAs(t *testing.T, env map[string]string, sys netproxy.Proxy, goos string, works *bool) {
t.Helper()
e, s, o, p := codexProxyEnv, codexSystemProxy, codexProxyOS, proxyProbe
codexProxyEnv = func(k string) string { return env[k] }
codexSystemProxy = func() netproxy.Proxy { return sys }
codexProxyOS = goos
proxyProbe = func(string, string) bool { return works != nil && *works }
reachForget()
t.Cleanup(func() {
codexProxyEnv, codexSystemProxy, codexProxyOS, proxyProbe = e, s, o, p
reachForget()
})
}
// Which proxy Codex sends a request for magpie's 127.0.0.1 through, the way
// its reqwest does (hyper-util's Matcher::from_system) and, with
// respect_system_proxy on, the way codex-rs outbound_proxy does.
func TestCodexProxyFor(t *testing.T) {
const base = "http://127.0.0.1:3425/v1"
clash := "http://127.0.0.1:7890"
plain := filepath.Join(t.TempDir(), "config.toml")
os.WriteFile(plain, []byte("model = \"gpt-5.5\"\n"), 0o600)
respect := filepath.Join(t.TempDir(), "config.toml")
os.WriteFile(respect, []byte("model = \"gpt-5.5\"\n\n[features]\nrespect_system_proxy = true\n"), 0o600)
win := netproxy.Proxy{URL: clash, Bypass: []string{"localhost", "127.*", "<local>"}}
cases := []struct {
name string
cfg string
env map[string]string
sys netproxy.Proxy
goos string
want string
}{
{"none", plain, nil, netproxy.Proxy{}, "darwin", ""},
{"HTTP_PROXY", plain, map[string]string{"HTTP_PROXY": clash}, netproxy.Proxy{}, "darwin", clash},
{"https_proxy only", plain, map[string]string{"HTTPS_PROXY": clash}, netproxy.Proxy{}, "darwin", ""},
{"ALL_PROXY", plain, map[string]string{"ALL_PROXY": clash}, netproxy.Proxy{}, "linux", clash},
{"NO_PROXY 127.0.0.1", plain, map[string]string{"HTTP_PROXY": clash, "NO_PROXY": "localhost,127.0.0.1"}, netproxy.Proxy{}, "darwin", ""},
{"NO_PROXY CIDR", plain, map[string]string{"HTTP_PROXY": clash, "NO_PROXY": "127.0.0.0/8"}, netproxy.Proxy{}, "darwin", ""},
{"NO_PROXY localhost is not 127.0.0.1", plain, map[string]string{"HTTP_PROXY": clash, "NO_PROXY": "localhost"}, netproxy.Proxy{}, "darwin", clash},
{"NO_PROXY * is names only", plain, map[string]string{"HTTP_PROXY": clash, "NO_PROXY": "*"}, netproxy.Proxy{}, "darwin", clash},
// the reporter's: Windows' proxy on, with 127.* in its bypass list,
// which reqwest doesn't read as 127.0.0.1
{"Windows 127.*", plain, nil, win, "windows", clash},
{"Windows 127.0.0.1", plain, nil, netproxy.Proxy{URL: clash, Bypass: []string{"127.0.0.1"}}, "windows", ""},
{"Windows NO_PROXY wins over its list", plain, map[string]string{"NO_PROXY": "example.com"}, netproxy.Proxy{URL: clash, Bypass: []string{"127.0.0.1"}}, "windows", clash},
{"macOS exceptions not read", plain, nil, netproxy.Proxy{URL: clash, Bypass: []string{"127.0.0.1"}}, "darwin", clash},
{"respect: Windows 127.* goes around", respect, nil, win, "windows", ""},
{"respect: system proxy", respect, nil, netproxy.Proxy{URL: clash, Bypass: []string{"*.local"}}, "darwin", clash},
// the system says direct, and the environment isn't asked (codex-cli
// 0.162.1 with HTTP_PROXY set sent nothing to it)
{"respect: no system proxy, env not read", respect, map[string]string{"HTTP_PROXY": clash}, netproxy.Proxy{}, "darwin", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
proxyAs(t, c.env, c.sys, c.goos, nil)
if got, from := codexProxyFor(c.cfg, base); got != c.want || (got != "" && from == "") {
t.Fatalf("got %q from %q, want %q", got, from, c.want)
}
})
}
}
// A proxy's own 502 isn't magpie; a proxy that passes the request on is.
func TestRealProxyProbe(t *testing.T) {
gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"name":"magpie"}`)
}))
defer gw.Close()
dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "upstream", http.StatusBadGateway)
}))
defer dead.Close()
pass := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, _ := url.Parse(r.RequestURI)
res, err := http.Get(u.String())
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer res.Body.Close()
w.WriteHeader(res.StatusCode)
io.Copy(w, res.Body)
}))
defer pass.Close()
if realProxyProbe(gw.URL+"/v1", dead.URL) {
t.Fatal("a proxy answering 502 counted as reaching magpie")
}
if !realProxyProbe(gw.URL+"/v1", pass.URL) {
t.Fatal("a proxy passing the request on didn't count")
}
}
// Muma102kMichael on X: Codex 502 on every project and every new chat once
// magpie took it over, its requests for 127.0.0.1 sent through a proxy that
// didn't pass them on. Failover, which magpie writes uninvited, is never
// written then, and one written before goes again; once the proxy passes
// them on, it is.
func TestCodexFailoverHeldWhileProxyDoesNotPassOn(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
auth := func(email, acct string) map[string]any {
return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": email}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
"refresh_token": "r-" + acct, "account_id": acct}}
}
me, _ := json.Marshal(auth("me@example.com", "acct-1"))
home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": true,
"seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}})
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
works := false
proxyAs(t, nil, netproxy.Proxy{URL: "http://127.0.0.1:7890", Bypass: []string{"localhost", "127.*"}}, "windows", &works)
cx := codex(home)
sync := func() string {
t.Helper()
reachForget()
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
return read()
}
if cfg := sync(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("written while the proxy doesn't pass it on:\n%s", cfg)
}
works = true
if cfg := sync(); !strings.Contains(cfg, `openai_base_url = "`+gateway.URL()) {
t.Fatalf("not written once the proxy passes it on:\n%s", cfg)
}
works = false
if cfg := sync(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("kept once the proxy stopped passing it on:\n%s", cfg)
}
}
// Connected to magpie, with the gateway up but Codex's way to it through a
// proxy that answers 502: the row says so, which proxy and where it is set,
// rather than connected (kind "proxied"); once the proxy passes it on, or
// 127.0.0.1 goes around it, connected again.
func TestCodexProxiedDrift(t *testing.T) {
fakeReach(t, map[string]bool{gateway.URL(): true})
home, _ := codexAt(t, gateway.URL())
works := false
env := map[string]string{"HTTP_PROXY": "http://127.0.0.1:7890"}
proxyAs(t, env, netproxy.Proxy{}, "darwin", &works)
d := driftSettled(t, codex(home))
if d == nil || d.Kind != "proxied" || d.Addr != "http://127.0.0.1:7890" {
t.Fatalf("drift %+v", d)
}
if !strings.Contains(d.Detail, "HTTP_PROXY") || !strings.Contains(d.Detail, "NO_PROXY") || !strings.Contains(d.Detail, "Disconnect") {
t.Fatalf("detail: %s", d.Detail)
}
works = true
reachForget()
if d := driftSettled(t, codex(home)); d != nil {
t.Fatalf("proxy passes it on: %+v", d)
}
works = false
env["NO_PROXY"] = "127.0.0.1"
reachForget()
if d := driftSettled(t, codex(home)); d != nil {
t.Fatalf("127.0.0.1 around the proxy: %+v", d)
}
}
// Leon920717 on X: with magpie quit, Codex CLI kept retrying the gateway
// till magpie was open again. The failover base URL magpie wrote goes as
// the magpie serving the gateway quits (EndCodexFailover), and the next
// start's Sync writes it again; a base URL the user wrote stays.
func TestCodexFailoverEndsWithMagpie(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
auth := func(email, acct string) map[string]any {
return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": email}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
"refresh_token": "r-" + acct, "account_id": acct}}
}
me, _ := json.Marshal(auth("me@example.com", "acct-1"))
home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
logins := func(on bool) {
b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": on,
"seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}})
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
}
logins(true)
cx := codex(home)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("failover not written:\n%s", cfg)
}
wasKeep := keepCodexDaemon
t.Cleanup(func() { keepCodexDaemon = wasKeep })
var asked []string
keepCodexDaemon = func(_ context.Context, h string, _ time.Time) provider.CodexDaemonCheck {
asked = append(asked, h)
return provider.CodexDaemonCheck{}
}
if err := EndCodexFailover(); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("magpie quit, Codex still pointed at it:\n%s", cfg)
}
// the app-server keeps the base URL it started with: asked to restart
if len(asked) != 1 || asked[0] != filepath.Dir(cx.Path) {
t.Fatalf("app-server not brought up to date on quit: %q", asked)
}
asked = nil
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("not written again on the next start:\n%s", cfg)
}
// the user's own base URL, with no failover on, stays
logins(false)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
base := gateway.URL() + gateway.CodexPath
if err := edit.SetTOMLTop(cx.Path, edit.KV{Path: "openai_base_url", Value: base}); err != nil {
t.Fatal(err)
}
if err := EndCodexFailover(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, `openai_base_url = "`+base+`"`) {
t.Fatalf("the user's base URL was taken:\n%s", cfg)
}
if len(asked) != 0 {
t.Fatalf("app-server restarted with nothing changed: %q", asked)
}
}
+6
View File
@@ -6,6 +6,7 @@ import (
"os"
"testing"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/testenv"
)
@@ -41,5 +42,10 @@ func TestMain(m *testing.M) {
// an address an agent is pointed at is tried over the network (Drift,
// #1013); never from a test, whose reach tests stand in for it
reachProbe = func(string) bool { return true }
// nor is the way Codex goes there read from this machine's proxy
// settings, or a proxy tried; the proxy tests say both
codexProxyEnv = func(string) string { return "" }
codexSystemProxy = func() netproxy.Proxy { return netproxy.Proxy{} }
proxyProbe = func(string, string) bool { return true }
os.Exit(testenv.Run(m))
}
+53 -5
View File
@@ -1,6 +1,7 @@
package agent
import (
"cmp"
"net"
"net/http"
"net/url"
@@ -55,26 +56,52 @@ type reachAnswer struct {
// (known); a probe older than reachAge, or none, is started in the
// background and never waited for, so Drift stays quick.
func reachable(base string) (ok, known bool) {
probe := reachProbe
return probed(base, func() bool { return probe(base) })
}
// probed is reachable for any probe, kept under key: its last answer, and
// whether there is one, with a new one started in the background when
// that is older than reachAge.
func probed(key string, probe func() bool) (ok, known bool) {
reach.Lock()
defer reach.Unlock()
if reach.m == nil {
reach.m = map[string]reachAnswer{}
}
a := reach.m[base]
a := reach.m[key]
if !a.busy && time.Since(a.at) > reachAge {
a.busy = true
reach.m[base] = a
probe := reachProbe
reach.m[key] = a
go func() {
ok := probe(base)
ok := probe()
reach.Lock()
reach.m[base] = reachAnswer{at: time.Now(), ok: ok}
reach.m[key] = reachAnswer{at: time.Now(), ok: ok}
reach.Unlock()
}()
}
return a.ok, !a.at.IsZero()
}
// probedNow is probed waited for: the last answer while it is fresh, else
// one asked now, which the next probed of key gets too.
func probedNow(key string, probe func() bool) bool {
reach.Lock()
a := reach.m[key]
reach.Unlock()
if !a.at.IsZero() && time.Since(a.at) <= reachAge {
return a.ok
}
ok := probe()
reach.Lock()
if reach.m == nil {
reach.m = map[string]reachAnswer{}
}
reach.m[key] = reachAnswer{at: time.Now(), ok: ok}
reach.Unlock()
return ok
}
// offLoopback: base is an http address on a host other than this
// machine's loopback and the gateway's own.
func offLoopback(base string) bool {
@@ -172,3 +199,24 @@ func wslMovedFrom(base string) (to, name string) {
}
return "", ""
}
// proxied is the drift of an agent whose requests for the gateway go
// through a proxy that doesn't pass them on to it, while the gateway
// answers here; nil when they get there, or it isn't known yet.
func (a *Agent) proxied(on Field, now string) *Drift {
if a.viaProxy == nil {
return nil
}
// with no proxy in the way, nothing is tried; with one, both are asked
// at once, so one round of probes settles it
ok, known, proxy, from := a.viaProxy()
if proxy == "" {
return nil
}
up, upKnown := reachable(gateway.URL())
if ok || !known || !up || !upKnown {
return nil
}
base := cmp.Or(a.pointedAt(), gateway.URL())
return &Drift{Kind: "proxied", Field: on.Key, Now: now, Want: now, Addr: proxy, Detail: codexProxiedDetail(base, proxy, from)}
}
+10
View File
@@ -19,6 +19,7 @@ import (
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/library"
@@ -337,8 +338,17 @@ func Run(version string, showMain bool, link string) error {
// way out, so the next launch is the new one.
// Quitting doesn't come back to main on a Mac (NSApp terminate:
// exits), so the CLIs still being asked something end here.
// Account failover magpie wrote into Codex goes with the gateway
// this process serves: Codex left pointed at it would retry till
// magpie is open again (Leon920717 on X). The next start writes it
// again (Sync).
OnShutdown: func() {
proc.EndProbes()
if served.Load() != nil {
if err := agent.EndCodexFailover(); err != nil {
log.Println("codex failover:", err)
}
}
updates.install(false)
},
// Wails exits on some webview errors; say why before it does.
+16 -4
View File
@@ -818,13 +818,15 @@ function profileDetail(p, footed) {
// An agent whose config is right but whose address doesn't answer (#1013)
// has nothing to set again: its pill says what has to listen there, unless
// WSL now reaches Windows at another address, which it moves the config to.
// Likewise one whose requests for magpie go through a proxy that doesn't
// pass them on (proxied: Codex, Muma102kMichael on X).
function driftFix(a, label = "Apply again") {
const d = a.drift, f = a.fields.find((x) => x.key === d.field);
const want = (f && optionFor(f, d.want)?.label) || d.want;
const fix = el("button", "ag-fix");
fix.type = "button";
fix.title = `${t(DRIFT_WHY[d.kind] || DRIFT_WHY.unwired, { agent: a.name, model: want })}\n${d.detail}`;
const deaf = d.kind === "unreachable";
const deaf = d.kind === "unreachable" || d.kind === "proxied";
if (deaf && d.move) label = t("Use {url}", { url: d.move.replace(/^https?:\/\//, "") });
else if (deaf) label = "How to fix";
fix.setAttribute("aria-label", t(label));
@@ -838,17 +840,26 @@ function driftFix(a, label = "Apply again") {
}
// explainDrift: what has to listen at an address an agent can't reach
// magpie by — too long for the status line, so a dialog of its own.
// magpie by, or let it through a proxy — too long for the status line, so a
// dialog of its own. Until it is fixed, Disconnect puts the agent's config
// back as it was, one click away.
function explainDrift(a) {
const ed = el("div", "editor");
const head = el("div", "ehead");
head.append(el("b", "", t(DRIFT_WHY.unreachable, { agent: a.name })));
head.append(el("b", "", t(DRIFT_WHY[a.drift.kind] || DRIFT_WHY.unreachable, { agent: a.name })));
ed.append(head);
ed.append(el("p", "lib-confirm drift-why", a.drift.detail));
const bar = el("div", "bar");
const ok = el("button", "text primary", t("OK"));
ok.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
bar.append(el("span", "grow"), ok);
bar.append(el("span", "grow"));
if (a.wired) {
const off = el("button", "text drift-off", t("Disconnect from magpie"));
off.title = t(DISCONNECT_TIP, { agent: a.name });
off.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); askDisconnect(a); };
bar.append(off);
}
bar.append(ok);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
@@ -861,6 +872,7 @@ const DRIFT_WHY = {
replaced: "{agent} was switched off {model} outside magpie",
bypassed: "{agent} was used without going through magpie — restart it after applying",
unreachable: "{agent} is set up, but nothing answers at the address it reaches magpie by",
proxied: "{agent} reaches magpie through a proxy that doesn't pass its requests on",
};
// an i in a circle: the pill that explains rather than acts
+4
View File
@@ -462,6 +462,7 @@ const I18N = {
"{agent} was switched off {model} outside magpie": "{agent} 已在 magpie 之外换掉 {model}",
"{agent} was used without going through magpie — restart it after applying": "{agent} 最近绕过了 magpie,重新应用后请重启",
"{agent} is set up, but nothing answers at the address it reaches magpie by": "{agent} 已设好,但它连 magpie 用的地址没有回应",
"{agent} reaches magpie through a proxy that doesn't pass its requests on": "{agent} 经代理连 magpie,但这个代理没把它的请求转给 magpie",
"How to fix": "如何修复",
"{agent} goes through magpie again": "{agent} 已重新经过 magpie",
"Drag to reorder · click to move, hide or disconnect from magpie": "拖动以调整顺序 · 点击可移动、隐藏或断开 magpie",
@@ -4792,6 +4793,7 @@ const I18N = {
"{agent} was switched off {model} outside magpie": "{agent} 已在 magpie 之外換掉 {model}",
"{agent} was used without going through magpie — restart it after applying": "{agent} 最近繞過了 magpie,重新應用後請重啟",
"{agent} is set up, but nothing answers at the address it reaches magpie by": "{agent} 已設好,但它連 magpie 用的位址沒有回應",
"{agent} reaches magpie through a proxy that doesn't pass its requests on": "{agent} 經代理連 magpie,但這個代理沒把它的請求轉給 magpie",
"How to fix": "如何修復",
"{agent} goes through magpie again": "{agent} 已重新經過 magpie",
"Drag to reorder · click to move, hide or disconnect from magpie": "拖動以調整順序 · 點選可移動、隱藏或斷開 magpie",
@@ -9087,6 +9089,7 @@ const I18N = {
"{agent} was switched off {model} outside magpie": "{agent} は magpie の外で {model} から切り替えられました",
"{agent} was used without going through magpie — restart it after applying": "{agent} は magpie を経由せずに使われました — 適用後に再起動してください",
"{agent} is set up, but nothing answers at the address it reaches magpie by": "{agent} は設定済みですが、magpie につなぐアドレスから応答がありません",
"{agent} reaches magpie through a proxy that doesn't pass its requests on": "{agent} はプロキシ経由で magpie につなぎますが、そのプロキシがリクエストを magpie に渡していません",
"How to fix": "直し方",
"{agent} goes through magpie again": "{agent} は再び magpie を経由しています",
"Drag to reorder · click to move, hide or disconnect from magpie": "ドラッグで並べ替え · クリックで移動、非表示、magpie からの切断",
@@ -13400,6 +13403,7 @@ const I18N = {
"{agent} was switched off {model} outside magpie": "{agent} wurde außerhalb von magpie von {model} weggeschaltet",
"{agent} was used without going through magpie — restart it after applying": "{agent} wurde ohne magpie verwendet — nach dem Anwenden neu starten",
"{agent} is set up, but nothing answers at the address it reaches magpie by": "{agent} ist eingerichtet, aber unter der Adresse, über die es magpie erreicht, antwortet nichts",
"{agent} reaches magpie through a proxy that doesn't pass its requests on": "{agent} erreicht magpie über einen Proxy, der seine Anfragen nicht an magpie weitergibt",
"How to fix": "So beheben",
"{agent} goes through magpie again": "{agent} läuft wieder über magpie",
"Drag to reorder · click to move, hide or disconnect from magpie": "Ziehen zum Umsortieren · klicken zum Verschieben, Ausblenden oder Trennen von magpie",
+115
View File
@@ -0,0 +1,115 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Codex connected to magpie while its requests for 127.0.0.1 go through a
// proxy that doesn't pass them on (Muma102kMichael on X: every project and
// every new chat 502) is not shown connected. Its row says a proxy is in the
// way; its pill says how to fix it, in a dialog, and the dialog has
// Disconnect from magpie, which asks to put Codex's config back. The window
// at 560px and the tray panel at 440px; nothing runs off the side. English,
// Chinese (both), Japanese and German, Chromium and WebKit.
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 detail = "Codex sends its requests for magpie (127.0.0.1:3425/v1) through the proxy at http://127.0.0.1:7890, set in Windows' proxy settings, and that proxy doesn't pass them on to magpie: every turn fails, with 502 Bad Gateway, whichever model it is on. Have the proxy send 127.0.0.1 direct (a DIRECT rule for 127.0.0.0/8, or rule mode rather than global), or add 127.0.0.1 to \"Don't use the proxy server for addresses beginning with\" in Windows' proxy settings (127.* there is not enough for Codex), then quit and reopen Codex. Until then, Disconnect from magpie puts Codex's config back as it was.";
const codex = { id: "codex", name: "Codex", icon: "codex", path: "/c", wired: true,
fields: [{ key: "model", label: "model", value: "fake/m1", options: [{ value: "fake/m1", label: "m1", ref: "fake/m1" }] }] };
const filler = Array.from({ length: 4 }, (_, i) => ({ id: "pi" + i, name: "Pi " + i, path: "/p", fields: [{ key: "model", label: "model", value: "", options: [] }] }));
function serve(lang, calls) {
const drift = { kind: "proxied", field: "model", now: "fake/m1", want: "fake/m1", addr: "http://127.0.0.1:7890", detail };
return async (route) => {
const url = new URL(route.request().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: { agents: [{ ...codex, drift }, ...filler], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/drift") return route.fulfill({ json: { codex: drift } });
if (url.pathname.startsWith("/api/agents/reapply/") || url.pathname.startsWith("/api/agents/disconnect")) {
calls.push(url.pathname);
return route.fulfill({ json: { agents: [codex, ...filler], profiles: [], settings: { lang, theme: "light" } } });
}
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const words = {
en: { why: "Codex reaches magpie through a proxy that doesn't pass its requests on", fix: "How to fix", off: "Disconnect from magpie", ask: "Disconnect Codex from magpie?" },
zh: { why: "Codex 经代理连 magpie,但这个代理没把它的请求转给 magpie", fix: "如何修复", off: "断开 magpie(还原配置)", ask: null },
"zh-TW": { why: "Codex 經代理連 magpie,但這個代理沒把它的請求轉給 magpie", fix: "如何修復", off: "斷開 magpie(還原設定)", ask: null },
ja: { why: "Codex はプロキシ経由で magpie につなぎますが、そのプロキシがリクエストを magpie に渡していません", fix: "直し方", off: "magpie から切断", ask: null },
de: { why: "Codex erreicht magpie über einen Proxy, der seine Anfragen nicht an magpie weitergibt", fix: "So beheben", off: "Von magpie trennen", ask: null },
};
const row = `.row.agent[data-id="codex"]`;
const noSideScroll = (page) => page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: a proxy in Codex's way is told, with Disconnect at hand`, 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();
});
const open = async (mode, calls) => {
const page = await (await browser.newContext({ viewport: { width: mode ? 440 : 560, height: 640 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/" + (mode ? "?mode=" + mode : ""));
await page.locator(`${row}.drifted .ag-fix`).waitFor();
return page;
};
for (const mode of ["", "panel"]) {
await t.test(`${mode || "window"}: how to fix, then disconnect`, async () => {
const calls = [];
const page = await open(mode, calls);
const fix = page.locator(`${row} .ag-fix`);
assert.equal(await fix.getAttribute("aria-label"), w.fix);
assert.match(await fix.getAttribute("title"), new RegExp(w.why));
if (!mode) assert.equal((await fix.textContent()).trim(), w.fix);
assert(await noSideScroll(page), "scrolls sideways");
await fix.click();
const dialog = page.locator("#modal:not([hidden])");
await dialog.waitFor();
assert.equal(await dialog.locator(".ehead b").textContent(), w.why);
assert.match(await dialog.locator(".drift-why").textContent(), /127\.0\.0\.1 to/);
const width = mode ? 440 : 560;
for (const b of [await dialog.locator(".editor").boundingBox(), await dialog.locator(".drift-off").boundingBox()]) {
assert(b.x >= 0 && b.x + b.width <= width, `runs off: ${JSON.stringify(b)}`);
}
assert(await noSideScroll(page), "scrolls sideways with the dialog");
assert.deepEqual(calls, [], "explaining set something");
const off = dialog.locator(".drift-off");
assert.equal((await off.textContent()).trim(), w.off);
await off.click();
const ask = page.locator("#modal:not([hidden]) .editor.disconnect-ask");
await ask.waitFor();
if (w.ask) assert.equal(await ask.locator(".ehead b").textContent(), w.ask);
assert.deepEqual(calls, [], "asking disconnected already");
});
}
await t.test("window: the line under the name", async () => {
const page = await open("", []);
const st = page.locator(`${row} .ag-st`);
assert.match(await st.getAttribute("class"), /\bbad\b/);
assert.equal(await st.locator(".ag-st-t").textContent(), w.why);
assert.match(await st.locator(".ag-st-t").getAttribute("title"), /502 Bad Gateway/);
});
assert.deepEqual(errors, []);
});
}
}