Commit Graph
9 Commits
Author SHA1 Message Date
yetoneandCanda15 0f1b40bbc4 gateway: a reply in flight shows on Routing how much has arrived and roughly its tokens (#4951, Canda15)
A long or reasoning reply looked stuck on the Routing page. A request still
out now shows, on its row and beside the account answering it, the bytes
the agent has had, "≈ n tokens" once a rate is learned, and how long ago
content last came; after 15s with no content the account's dot stops
pulsing. Nothing stays once the request is done.

Ported from Canda15's 7f7bdb189 (github.com/Canda15/magpie), the idea and
the per-protocol content extractors kept, the hot path and storage
reworked:
- every write to the agent passes captureResponseWriter.Write, which calls
  liveRow.observe; the row hangs on the request's inflight (an atomic
  pointer), not a context value made per request
- rates are in memory only (256 pairs); the fork wrote a JSON file under
  the estimate lock on every finished request
- a whole JSON reply is counted in bytes only: the fork held and decoded up
  to 8 MiB of it at the end; a stream is cut into lines in place, only a
  line cut by a write's end is copied, a line over 1 MiB passed over, and
  each event decoded once (the fork ran json.Valid then Unmarshal)
- the reply's kind comes from its first byte, not a header read on every
  write; the keepalive check allocates nothing (the fork split each write)
- everything a row counts is under its own lock, and inflight.tr is read
  under f.mu; the estimate is in float64 (the int64 product overflowed)
- the route's Seq is bumped on every write and traceGather batches the
  wake-ups; the fork's global throttle could drop the last update before
  a pause
- learned only from a streamed reply that did not fail and had the
  vendor's output tokens
- left out: the finished row's "Received" metric and the ended caption
  (layout restraint; an ended row has its own metrics), a duplicate
  "Received" i18n key, the receive-monitor doc (the design is in
  gateway-routing.md now), the fork's xmod and Windows CI commits
The Routing plugin and i18n.js are outside TestCoreScriptBudget.

Run on mote at this head unless named: gofmt -l; go vet (darwin),
GOOS=linux -tags nogui and GOOS=windows go vet ./...; go build ./...;
go test -race on the live tests; go test ./internal/gateway ./internal/gui
(gateway ok; gui red only on TestCoreScriptBudget, #5139, 1533907 >
1533802 before this change and untouched by it, and
TestMainWindowCorners/macOS_26_SDK, #3949); routing-live-bytes.test.cjs and i18n-keys in Chromium and
WebKit, en/zh/zh-TW/ja/de, 1100 and 420px (24/24); every routing-* and
panel-routing* GUI file with i18n-keys in WSL Linux (Chromium all green;
WebKit reds in 12 files, the same class at origin/main 7dd2434d3 run
the same way: 25 there, 28 here, the sets differing by timing samples;
routing-live-patch alone red 2 of 3 on main, 1 of 3 here; filed as
#4121, #4520, #5156, #2174).

Rebased onto 38f4f74e6 (gateway.go, trace.go and the Routing plugin
moved): build, gateway vet, the live tests, routing-live-bytes and
i18n-keys run again there, green (24/24).

Broken by hand, each red, then put back:
- no observe in capture.Write: TestLiveCountsARealStream
- commentOnly never true: TestLiveHeartbeatIsBytesNotContent,
  TestCommentOnlyTellsHeartbeatsApart
- learning from failed replies: TestRatesLearnFromRepliesTheVendorFinished
- a whole reply read as a stream: TestContentCounterLeavesAWholeReply
- no Seq bump in liveBytes: TestLiveWritesReachTheRoute
- no quiet class, no per-second repaint: routing-live-bytes 0/20

Not tried: a real vendor's stream in the running app; the ChatGPT backend
chain (codex_backend.go) writes past the capture writer and isn't counted;
the full Go and GUI suites run after the tag.

Co-authored-by: Canda15 <124772373+Canda15@users.noreply.github.com>
2026-11-04 19:39:08 +08:00
yetone 29185e3bbc gateway: a request held too long before routing leaves a report its user can copy
Jason on Discord (#general, v0.1.1995, AirbuildEnvironment over Codex's
/backend-api/codex/responses) got the 2m 504: "magpie held this request
for 2m0s without routing it to any provider ... report it with magpie's
log". The desktop app runs the gateway in-process and logs only to
stderr, so there is no log for him to send.

giveUp now writes a report of the held request to a small file in
magpie's cache (held/, folder 0700, temp file renamed into place, the
newest 5 kept). It holds the time, version, OS, the method and path, the
model and agent, how long it was held, each named wait with its time and
whether it was still under way (noteWait now takes a kind: body, body
room, decision model, image description, plugin hooks, JS middleware,
Codex reset, masking), the body room's state, the requests in flight,
and a goroutine profile (function names and lines only, cut at 128KB).
It holds no body and no headers. Route.Held names the file. On the
Routing page, the request's story then says a report was saved, with
Copy Report and Open Folder (Open Folder is left out in magpie web).
GET /api/gateway/held/{name} reads only a report's own name. The 504's
text no longer points to a log: it names Copy Report on the Routing page
and the folder. The log line names the waits too. i18n is in zh, zh-TW,
ja and de, and docs/subsystems/gateway-routing.md has the section.

What held Jason's request is not known from what he sent. The waits that
count before routing are: the body arriving (idle deadline only), body
room (up to 100s, then 503), the decision model (see the next commit),
plugin hooks (11s), JS middleware (250ms a hook), image description
(bounded by the request) and the Codex reset (20s). Slots, RPM and
upstream come after the route begins. A WebSocket upgrade gets a 426.
The report names the wait, so the next one says which.

Run:
- mote, at 57b21abd9 before the rebase: go test ./internal/gateway
  -run 'Unrouted|Held|...' passed. The full go test ./... -timeout 45m
  was cut off when mote dropped off the network (2 packages ok). The
  full suite then went to the Windows box (see the next commit).
- xiaomi-gpu (Windows), node --test: routing-held-report 50/50 in
  chromium and webkit, 5 languages, 1100/420px, app and web.
  routing-held-request and i18n-keys pass. All routing-* and i18n*:
  1742 tests, 94 reds, none in i18n*. The same files are red alone at
  origin/main 033b17baf (22 of 46 in WebKit), recorded on #4124.
- GOOS=windows/darwin go vet ./internal/gateway ./internal/gui,
  GOOS=linux go vet ./internal/gateway, go build ./... : ok.
Broken by hand: leaving Route.Held unset turned
TestUnroutedHeldReportSaved red ("names no report"). Dropping the
story's report line in client.js turned routing-held-report red in both
engines.
Not tried: a real held request in the real app. Linux vet of
internal/gui (cgo for Wails, cross-compiled). The GUI test on macOS
WebKit, since mote was unreachable.
2026-10-29 15:10:34 +08:00
yetone b92cb2f596 gateway: another magpie's request is masked and shown in flight under its agent (linkaww)
linkaww on Discord: Pi through a local magpie to a remote magpie with
masking on. The remote's masking log named the request "magpie", while
its usage already said Pi. The local magpie already sends the agent
(X-Magpie-Agent / X-Magpie-Via, passOnCaller). The remote's masking log
read agentOf, the real sender, instead of callerOf, the recorded label.
So the fix is on the remote: only the remote magpie needs this version.

There is one rule now, callerFrom/callerOf, for every place the remote
says who sent a request:
- the masking log (noteMasked)
- the requests in flight (/v1/magpie/concurrency). counted runs before
  withCaller, so active.add calls callerFrom itself.
- observed calls
- Codex title / tool-loop answers (answeredHere)
- Codex search and backend records, which recorded agentOf
Usage and sessions already used callerOf. The trust rule is unchanged.
The headers are taken only from a magpie/ User-Agent and are a label
only: access, key limits and behaviour (middleware Info.Agent, models
shown, stand-ins, group rules) still go by the key and agentOf. A client
that isn't magpie is logged as itself.

Run:
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (562s) at bdd6a6c73, this change on 1cbdda25b
- after rebasing onto 430e3050d: go vet (darwin, GOOS=linux,
  GOOS=windows, -tags nogui) ./internal/gateway, gofmt -l, and -run
  'TestRemoteMagpie|TestMasked|Active|Concurrency|CodexTitle|ToolLoop':
  ok
- Two sandbox magpies on 127.0.0.1:47611 (remote, masking on, a fake
  upstream on :47613) and :47612 (local, a Remote magpie provider to
  :47611), each under its own HOME/XDG dirs. A Pi request
  (Bearer magpie-pi) carrying an API key went through the local. With
  the remote on origin/main, its masking/<day>.jsonl line said
  "agent":"magpie" and its usage said "pi". With the remote on this
  change, both said "pi". The upstream got the key masked.

Broken by hand: masked.go back to agentOf made
TestRemoteMagpieMaskedNamesTheAgent fail ("logged as \"magpie\", want
pi"). active.go back to agentOf made TestRemoteMagpieActiveNamesTheAgent
fail (Agent:magpie).

Not tried: the GUI's Privacy page on the remote. It shows the record's
agent field, which the jsonl above has. A remote reached through a
Claude Code or Codex client User-Agent (passUserAgent): there the remote
reads that agent from its own User-Agent, as before.
2026-10-27 15:53:54 +08:00
yetone 3300616492 gateway: a request being masked has the phase redact, and its row says masking
fremontdango on Discord: a Claude Code request to deepseek/deepseek-flash
sat on the Routing page as "routing…" for a long while that it was
actually being masked (Settings → Privacy). The placeholder route shows a
held request after 15s with nothing to say what holds it.

noteRedacting (redact_phase.go) wraps every masking, at the one place
each route masks through: redactedHits and maskTextHits in redact.go
(chat, Codex backend, search, images, video, System One, embeddings,
audio, count_tokens). It keeps noteMasking's exemption from the unrouted
limits, sets the request's phase to "redact" (notePhase, on
/v1/magpie/concurrency) and puts Route.Phase "redact" on the route that
shows it, its own or the unrouted placeholder, until the last masking at
once ends. A route that is done never carries it. It holds no text.

The Routing page says "masking…" for such a row, in the list and the
panel row, in every language (plugins/routing/i18n.js: 脱敏中…, 脫敏中…,
マスク中…, maskiert…).

Run, in a copy of this commit's tree:
- go test -race -count=2 -run 'TestMaskingIsAPhase|TestNoMaskingNoPhase|Unrouted' ./internal/gateway: ok
- routing-masking.test.cjs, chromium and webkit, en zh zh-TW ja de: 10/10
- gofmt -l, go vet ./internal/gateway: clean
The full suite is in the next commit's body, at the pushed head.

Broken by hand, each red: noteRedacting without notePhase (phase ""),
redact.go back to noteMasking (phase and route ""), showLocked without
the phase; waitWord back to "routing…" (5/5 GUI red per engine).

Not tried: a real local masking model (the Windows box, its GPU); a
masking that starts after a route is already shown (showRedacting at
the start) has no test that fails without it.
2026-10-27 08:08:23 +08:00
yetone 5a94eec3ae gateway: a request held 30s before routing in no known wait is answered then
sharwowwow on X: "转圈两分钟才报 504,这个超时阈值本身就很折磨人。网关要是能
早点失败、早点给明确错误,排查能省不少时间。" A request held before any
route was answered 504 only after unroutedMost (2m), whatever held it.

Now the time a request spends in a wait magpie knows of is added up as it
happens (noteWait/waited, the union of overlapping waits), and a request
held unroutedUnknown (30s) outside them gets the same 504 and message
then. unroutedMost (2m) stays the cap for one in known waits. Known waits,
each read from the code between counted and noteRoute:
- the request's body arriving: r.Body is wrapped (waitedBody), so every
  read of it (keyLimited, requestBody, readRequestBody) counts;
- masking (noteMasking);
- System One's or the decision model's classifier (askWaited);
- an image's description (seenBody);
- Codex's auto reset before the route (autoReset);
- plugins' gateway hooks / plugin host start (GatewayBegin) and JS
  gateway middleware (Begin, Request);
- every notePhase (slot, rpm, upstream); these come after the route for
  watched requests today, so it only guards a future change.
What is left is magpie's own work (catalog build, parsing, planning,
affine, reading the usage log), ~8.5s at its slowest (a cold catalog
sync); 30s is about three times that, with room for a loaded machine.
The log says "30s of it in no wait magpie knows of".

Run at this tree (rebased on origin/main 9120acaff):
- gofmt -l internal/gateway: clean.
- go vet ./internal/gateway/... on darwin, GOOS=linux, GOOS=windows: ok.
- go test -timeout 45m ./internal/gateway/...: ok (478.0s).
  Also ok on the earlier bases a5ce158e5 (655.8s) and 7d075df9d (448.1s).
Not run: the full go test ./... and go vet ./..., because the machine's
disk was full (under 1GB free for over 20 minutes; a build and one
gateway run failed with "no space left on device", every red naming it). No -race run.

Broken by hand, each test red, then restored:
- without the 30s answer (u.giveUp(true)),
  TestUnroutedUnknownHoldAnsweredSooner: not answered before unroutedMost;
- without the body wrap, TestUnroutedSlowBodyNotCutOff: answered 504
  while its body was still arriving;
- without masking's excuse, TestUnroutedMaskingNotCutOff: answered 504
  while it was masked.
TestUnroutedSlotWaitNotCutOff stays green without notePhase's excuse (the
slot wait is after the route); it guards that a slot wait is never cut.

Not tried: no test of its own for the classifier, auto reset, gateway
hook, JS middleware or image-description excuses; no run in the real app
or against a real provider.
2026-10-26 19:04:27 +08:00
yetone 07936ca890 gateway: a turn held before routing shows on Routing and is answered 504 after 2m
heyusaku6 on X: Codex desktop thought for over ten minutes on a model
served through magpie (a routing group's DeepSeek, then Qoder CN's
MiniMax, then GPT-6.1 Sol), the Routing page showed none of them, and
only restarting Codex and magpie ended it. Codex waits for a reply's
headers with no limit of its own, and a request shows on the Routing
page only once a route is begun for it, so whatever held these requests
held them before routing, in silence.

The root cause was not found. Every pre-route wait read (the classifier,
image description, plugin GatewayBegin, JS middleware, provider.Hold,
the body read, pluginrt.Refresh, the trace lock) has a bound or follows
the request's context. So this makes the stall visible and bounded
instead, and records where it was held:

- counted watches an agent's turn (Chat, Responses, Messages, Gemini
  generateContent, Codex backend /responses) while no route is begun for
  it (unrouted.go). After 15s a route of provider "magpie" shows it on
  the Routing page as routing; it gives way to the request's own route
  when one begins (noteRoute, trace.drop).
- After 2m with no route and nothing written, the client is answered
  504 in its own protocol, whole (Content-Length, Connection: close) so
  it has the error even if the handler stays stuck. The request's
  context ends with errUnrouted, its route ends with the error, and the
  log gets every goroutine's stack (at most once in 10 minutes), which
  says what held it next time.
- The handler writes through heldWriter, which drops its writes once
  magpie has answered for it.

A request waiting on another request's identical image description for
over 2m is now answered 504 too; the retry finds the description cached.

Run in the worktree at origin/main 5df62c5cd + this change:
- The stall was injected as an image description in flight that never
  ends (a never-closed s.sights entry), which holds pastedImage inside
  serve before beginFor. TestUnroutedRequestShownThenAnswered and
  TestUnroutedShownGivesWayToItsRoute are red with the watch unhooked
  from counted (the request never shows; the client waits out its 20s
  timeout) and green with it; the log's stack names describe at
  vision.go:319 under seenBody.
- go test -race -count=3 on TestUnrouted|TestVision|TestEndBroken|Busy|
  Concurrency|Trace: ok.
- gofmt -l clean; go vet ./internal/gateway on darwin, linux -tags nogui,
  windows: ok.
- go test ./internal/gateway -timeout 45m -count=1: ok (537.9s)

Rebased onto 2f44e075a (internal/agent only); at that head go build ./... and TestUnrouted: ok.

Not run: the full ./... suite (another session's full suite was running
on this machine); a real Codex desktop on Windows.
2026-10-25 20:28:36 +08:00
yetone a7a0122027 gui, gateway: the search grip's place is a class, not :has(), and Go no longer says the Routing plugin's words (batch GUI reds)
The full GUI run on this batch had two reds that are real, both from
commits in it:

- old-webkit "the styles hold up in Safari 15.0": 4b69460d1 (#2286)
  placed a search API's grip with `.search-unit:has(> .search-keys)`,
  which Safari before 15.4 can't parse. The unit now gets a with-keys
  class where its keys' row is added, as other rows in app.css do.
- i18n-keys "a plugin's words are its own": 7ff5f595e's test name
  TestArkDrawsUnmarkedOncePerImage and f9ccca71e's comments in active.go
  and left_in_flight_test.go said "Unmarked" and "answering…", which are
  plugins/routing's words. The test is TestArkDrawsWithoutWatermarkOncePerImage
  (the subsystem page renamed with it) and the comments say it in other words.

Run: node --test i18n-keys (3/3), search-order (16/16), old-webkit and
mobile-web alone; gofmt; go vet -tags nogui ./internal/gateway.
Not checked by a test: the grip's top under a unit with keys; the rule
is the same, only its selector changed.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 0e8fcd7926 routing: an account that answered is lit but still; only a request in flight pulses and flows, and a panicked request's routes end (#2386)
Since af5889085 the account that answered the last request kept a
pulsing dot and a flowing wire after the request was done, which reads
as 正在调用 on every reload, local and remote alike. lightRow now tells
answered (filled dot, solid wire in the agent's colour, nothing moving)
from in flight (pulse and flow), for single rows, key folds and nested
groups. Separately, a request whose handler panicked left its routes and
tries open for good ("answering…", counted in progress, never trimmed):
every route begun is recorded and `counted` ends any still open as 500
before the panic goes on to net/http.

Run: gofmt; go vet -tags nogui ./internal/gateway for darwin, linux,
windows; go test -race -count=5 of TestAgentGoneMidRequestLeavesNothingInFlight
and TestPanicEndsTheRequestsRoutes ok; with endBroken removed by hand
the panic test is red. GUI: routing-answered-still (new; red on the old
client.js/css with flowing 1, moving 1), routing-keys-fold (updated:
expects a lit still wire after the request), group-fold, held-dot,
agent-hue-not-red, mode-goes, busy, agent-gone, live-patch: 203 pass,
0 fail in chromium and webkit. Not tried against a real remote magpie.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 27a0458de1 gateway: /v1/magpie/concurrency lists each request in flight, its agent, model, start and phase, for a status bar's hover (#2132, bigbitbox)
The concurrency read now carries `active` beside requests/waiting/tools:
one entry per agent request counted for Busy, oldest first, [] when idle:
id, agent, model and provider (once routed, from the routing trace),
session when the agent sends one, started and ms, route (the trace id),
and phase only where the gateway knows it: "slot" waiting in a key's or
account's queue, "rpm" waiting for room in the minute, "upstream" while a
try is out at the vendor. No prompt, reply or key. The entry lives on the
request's context from `counted` (so a GET, this poll included, is never
listed), routing ties it to its first route in trace.beginFor, and
lanes.take / rpms.wait / the try loop note the phase, putting the one
before back when they return. Access is the endpoint's: this machine,
another with a gateway key, never a held key (TestHeldKeyToldNoAccounts).
Nothing in routing or limits reads it.

Run (worktree on e98440ae6, sandbox HOME, GOCACHE pinned):
- TestConcurrencyListsEachRequest (new): one request out and one of the
  same agent waiting for a one-slot provider; checks agent, model,
  provider, session, phase upstream/slot, no prompt or key, [] idle and
  after. Broken by hand, each goes red: active left out ("active left
  out or null"), the slot phase removed ("never one out and one
  waiting"), noteRoute removed (model/provider empty), the upstream
  phase removed (phase "").
- go test -race -count=5 -run 'TestConcurrency|TestBusy|TestMaxConcurrency|TestMaxRPM|TestHeldKey' ./internal/gateway: ok
- go test -tags nogui ./internal/gateway (-timeout 28m; 1394s on a loaded
  machine, the default 10m timeout cut the first run short), ./internal/proc,
  ./internal/usageapi: ok
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  on ./internal/gateway: clean
Not run: the full `go test ./...` (disk tight), a real SketchyBar hover;
no GUI change.
2026-10-15 01:13:18 +08:00