An agent that cancels its request before it is answered is logged 499 "the agent canceled the request": a person stops the reply, or sends the next message while it is coming and Claude Desktop cancels it and asks again, or Codex takes a subagent's report (#2398). The gateway already says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody), but Record.Failed is a status >= 400 or an error, so every page counted it as a failure: the Requests card's "N failed" and success share, its Failed filter, the CSV's error column, the Routing page's "errors your agent saw", the Context page's error rate, the failed colour in the Requests list, Routing and Recent calls, and the OTLP export's error status. A Claude Desktop session on 2026-10-27 had four, each a message sent mid-reply; #2398 had 91 of a day's 92 failures. usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from magpie's own limit on a request it asked of itself, logged 499 too and still a failure (#2318). The cancel is logged with an error type of its own, agent_canceled (usage.CanceledErrType, set in failedWith), so the record says what it was and nothing guesses it from a 499, as #2398 asked. Record.Canceled reads the type, and a record logged before it by its status and message, so the old log reads the same with nothing migrated. A middleware's usage rows carry the type, so a module can tell the cancel from magpie's own limit, which its rows (no error text) couldn't. Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in count and plus); RetriedRequest and the first-token and speed sums ask Answered, so a canceled request is timed nowhere, as before; Codex's memory of the last model still skips it. Routes and Recent calls say canceled (set as a route is done and as a day's history is read, so old days read the same); the Routing totals and the Context page's errors leave it out. Ledger rows say canceled, and the pages show it muted, in neither the failed nor the answered colour: the Requests list and its detail ("499 · canceled"), the Requests card ("N canceled", the success share of the requests not canceled), the overview tile, the Routing page (a "gone" outcome, no speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de. The OTLP export: the records the gateway gives its observers for a request and its try carry the type too (canceledAs), and a root span's error.type follows Record.Failed, so a canceled request's span and its try's go with status code 499, no error and no error.type. TestOTelWaterfallFailureAndCancellation's canceled case held two failed spans (the try the vendor refused as the agent left is recorded canceled, as the request is); it now holds neither failed, both 499 and no error.type. That change to the test is the point of this one. mdwsk88's patch (aea0027fd) ran its tests ate056779a,a3768cdd,c86fa2a3andfcc0daa2, broke each check by hand (each red), and sent real Claude Desktop cancels through a nogui build with a stand-in upstream and OTLP collector. Its full record is on aea0027fd. Since58541e5b(#4866) Codex's own-sign-in relay logs Codex gone mid-reply as 499 through canceled() too, so it counts as canceled (TestCodexGoneMidReplyIsNoFailure). drawing_route.go still reads a canceled request as not served when it decides whether a picture's next request may stay on its provider: that is routing, not a count. Ported to origin/main400b66ec3on 2026-11-07, reviewed line by line. Two siblings it left on the old rule, and a colour, now covered: - usage.Row.Floor (the Claude Code speed floor) asked !Failed, so a canceled row, whose Failed is now false, told a floor: "3000 tokens in 4000 ms" for a reply no one waited for. It asks Answered now, as the speed and first-token sums do. TestAgentCanceledTellsNoFloor. - The route-events feed (activityOf, #3387) told a canceled try and done route as failed. It leaves usage.CanceledBy out, and still counts magpie's own 499 limit. TestRouteEventsCanceledIsNoFailure. - routing.css: a canceled Routing row ("rt-req gone") had the answered green dot. Its dot is muted now. routing-canceled-row.test.cjs checks the row, its dot and the errors stat in Chromium and WebKit, in en, zh, zh-TW, ja and de. Run at this tree (mote-run, macOS): - go test -count=1 internal/usage, usageapi, otlp, settings, settingsapi and cli: ok. internal/gateway: ok with -timeout 45m (847s; the default 10m ran out under load). internal/gui: ok but TestMainWindowCorners/macOS_26_SDK (#3949, mote is on macOS 27). - Broken by hand: Floor on Failed again makes TestAgentCanceledTellsNoFloor fail ("a canceled row tells a speed floor: 3000 tokens in 4000 ms"). activityOf without CanceledBy makes TestRouteEventsCanceledIsNoFailure fail ("a done route its agent canceled is told failed"). Restored, both pass. - GUI: node --test --test-concurrency=4 over routing-*, usage-*, ledger-*, panel-*, call-*, search-*, searcher-*, settings-*, i18n-* and gui-* (Chromium and WebKit; the files cover en, zh, zh-TW, ja and de), with #2398 and #5545 in one tree: 4961 of 5016 ok. The 55 reds are in 12 files. i18n-keys' "a plugin's words are its own" names other files' strings (#5327, #5426, #5482). The other 11 files were run alone at dc49feca9 (this tree without either change) and at this tree: 52 and 51 reds, the same tests. The one apart is usage-focus-steady, which flakes (#3501). Each is filed: #5392, #3414, #5048, #3799, #3415, #3954, #4627, #4628, #5223, #1529. routing-canceled-row.test.cjs: 10 of 10. With the .rt-req.gone rule taken out, its dot is the answered green rgb(24, 154, 88) and it fails. Restored, it passes. - Not tried: a real Claude Desktop cancel through this tree; Windows and Linux runs. Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com> Reported-by: mdwsk88 (dawei on Discord)
369 lines
12 KiB
Go
369 lines
12 KiB
Go
package gateway
|
|
|
|
import (
|
|
"cmp"
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// The route-events feed (#3387, joe21_eee on Discord, sywyyhykkk on
|
|
// GitHub): a display on the LAN, an ESP32 screen, shows every agent's
|
|
// requests as they are routed (started, each try, its first content,
|
|
// fallback, done) without knowing their sessions, which
|
|
// /v1/magpie/route asks for, and without the full trace, which names
|
|
// accounts, folders and errors and is told to this computer alone.
|
|
//
|
|
// GET routeSnapshotPath is the requests going now and a cursor; GET
|
|
// routeEventsPath?after=<cursor> streams each change after it as SSE. A
|
|
// route here is routeActivity, an allow list of fields, never a Route
|
|
// with some taken out. They are told as the usage log is: to this
|
|
// computer, and to another with an enabled gateway key while magpie is
|
|
// shared (a read-only key reads them too, readOnlyRoutes), never to a
|
|
// key held to a budget, models or accounts, which is told no one else's
|
|
// requests.
|
|
const (
|
|
routeSnapshotPath = "/v1/magpie/route-events/snapshot"
|
|
routeEventsPath = "/v1/magpie/route-events"
|
|
// routeEventsKeep is how many changes the feed keeps for a reader
|
|
// that fell behind, or reconnects with the cursor it last had
|
|
routeEventsKeep = 512
|
|
// routeEventsBeat is how often an idle stream is sent a heartbeat,
|
|
// and the longest a key turned off keeps an idle stream open
|
|
routeEventsBeat = 15 * time.Second
|
|
)
|
|
|
|
// routeEventsRecheck is how often a stream with changes to send asks
|
|
// again whether its key is still on (a var for the tests)
|
|
var routeEventsRecheck = time.Second
|
|
|
|
// routeEventsRefused is what another machine is told while magpie isn't
|
|
// shared with it.
|
|
const routeEventsRefused = "magpie's routing events are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries an enabled gateway key (Authorization: Bearer <key> or x-api-key: <key>); a read-only key reads them too"
|
|
|
|
// routeActivity is what the feed tells of a request. ID is the route's,
|
|
// never a session's, an account's or a key's; Attempt counts from 1.
|
|
type routeActivity struct {
|
|
ID string `json:"id"`
|
|
Time time.Time `json:"time"`
|
|
Agent string `json:"agent"`
|
|
Provider string `json:"provider,omitempty"`
|
|
Model string `json:"model,omitempty"`
|
|
Attempt int `json:"attempt"`
|
|
Fallback bool `json:"fallback"`
|
|
Phase string `json:"phase"`
|
|
Status int `json:"status,omitempty"`
|
|
Failed bool `json:"failed,omitempty"`
|
|
Millis int64 `json:"ms,omitempty"`
|
|
TTFT int64 `json:"ttft_ms,omitempty"`
|
|
}
|
|
|
|
// The phases a route is in.
|
|
const (
|
|
phaseStarted = "started" // no try yet
|
|
phaseAttempt = "attempt" // its last try is out
|
|
phaseResponding = "responding" // its last try's content is coming
|
|
phaseTryDone = "attempt_done" // its last try ended, the next not yet out
|
|
phaseDone = "done" // answered, one way or the other
|
|
phaseDropped = "dropped" // gone from the trace unfinished (drop, trim)
|
|
)
|
|
|
|
func activityOf(r *Route) routeActivity {
|
|
a := routeActivity{ID: strconv.FormatInt(r.ID, 36), Time: r.Time, Agent: r.Agent,
|
|
Phase: phaseStarted, Attempt: len(r.Tries)}
|
|
if n := len(r.Tries); n > 0 {
|
|
tr := r.Tries[n-1]
|
|
a.Model, a.Status, a.Millis, a.TTFT = cmp.Or(tr.Served, tr.Model), tr.Status, tr.Millis, cmp.Or(tr.TTFT, tr.firstMs)
|
|
a.Failed, a.Fallback, a.Phase = (tr.Error != "" || tr.Status >= 400) && !usage.CanceledBy(tr.Status, tr.Error), n > 1, phaseAttempt
|
|
// a try's ID is its seat's, which names an account or a key's
|
|
// fingerprint: only the seat's provider is told
|
|
for _, seat := range r.Order {
|
|
if seat.ID == tr.ID && seat.Model == tr.Model {
|
|
a.Provider = seat.Provider
|
|
break
|
|
}
|
|
}
|
|
if a.TTFT > 0 {
|
|
a.Phase = phaseResponding
|
|
}
|
|
if tr.Done {
|
|
a.Phase = phaseTryDone
|
|
}
|
|
}
|
|
if r.Done {
|
|
a.Phase, a.Status, a.Millis = phaseDone, r.Status, r.Millis
|
|
// one its agent canceled is no failure (usage.CanceledBy), as the
|
|
// Routing page and the usage log count it
|
|
a.Failed = (r.Status >= 400 || r.Error != "") && !usage.CanceledBy(r.Status, r.Error)
|
|
}
|
|
return a
|
|
}
|
|
|
|
func activityChange(before, after routeActivity) string {
|
|
switch {
|
|
case after.Phase == phaseDone && before.Phase != phaseDone:
|
|
return "request_finished"
|
|
case after.Attempt > before.Attempt:
|
|
return "attempt_started"
|
|
case after.Phase == phaseTryDone && before.Phase != phaseTryDone:
|
|
return "attempt_finished"
|
|
case after.TTFT > 0 && before.TTFT == 0:
|
|
return "first_content"
|
|
default:
|
|
return "route_changed"
|
|
}
|
|
}
|
|
|
|
// firstContent is a try's firstToken.onFirst: it tells the route's last
|
|
// try, still going, that its first content came ms after it began.
|
|
func (t *trace) firstContent(r *Route) func(int64) {
|
|
return func(ms int64) {
|
|
t.update(r, func(r *Route) {
|
|
if n := len(r.Tries); n > 0 && !r.Tries[n-1].Done {
|
|
r.Tries[n-1].firstMs = max(ms, 1)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
type routeActivityEvent struct {
|
|
Cursor string `json:"cursor"`
|
|
Kind string `json:"kind"`
|
|
// Active is how many requests were going once this change was made
|
|
Active int `json:"active"`
|
|
Route routeActivity `json:"route"`
|
|
}
|
|
|
|
// routeActivityLog is the feed's last routeEventsKeep changes, a ring
|
|
// held under trace.mu: a request that begins and ends between two reads
|
|
// is told step by step, not as its end alone. epoch is this process's,
|
|
// so a cursor from before a restart is told to take a snapshot.
|
|
type routeActivityLog struct {
|
|
epoch string
|
|
seq int64
|
|
events []routeActivityEvent
|
|
}
|
|
|
|
func (l *routeActivityLog) init() {
|
|
if l.epoch == "" {
|
|
l.epoch = rand.Text()
|
|
l.events = make([]routeActivityEvent, routeEventsKeep)
|
|
}
|
|
}
|
|
|
|
func (l *routeActivityLog) cursor() string {
|
|
return l.epoch + ":" + strconv.FormatInt(l.seq, 10)
|
|
}
|
|
|
|
// after is every change after cursor; false when cursor isn't one of
|
|
// this process's, or the changes after it are no longer all kept.
|
|
func (l *routeActivityLog) after(cursor string) ([]routeActivityEvent, bool) {
|
|
epoch, raw, ok := strings.Cut(cursor, ":")
|
|
n, err := strconv.ParseInt(raw, 10, 64)
|
|
if !ok || err != nil || epoch != l.epoch || n < 0 || n > l.seq || n < l.seq-routeEventsKeep {
|
|
return nil, false
|
|
}
|
|
out := make([]routeActivityEvent, 0, l.seq-n)
|
|
for i := n; i < l.seq; i++ {
|
|
out = append(out, l.events[i%routeEventsKeep])
|
|
}
|
|
return out, true
|
|
}
|
|
|
|
// noteActivity records a change of r, under t.mu: none once r left the
|
|
// trace unfinished and the feed was told it went (noteDropped), though
|
|
// the request that holds r goes on writing to it.
|
|
func (t *trace) noteActivity(r *Route, kind string) {
|
|
if r.offFeed {
|
|
return
|
|
}
|
|
l := &t.activity
|
|
l.init()
|
|
l.seq++
|
|
l.events[(l.seq-1)%routeEventsKeep] = routeActivityEvent{l.cursor(), kind, t.going(), activityOf(r)}
|
|
}
|
|
|
|
// noteDropped tells the feed r left the trace unfinished, under t.mu,
|
|
// after it was taken off t.routes.
|
|
func (t *trace) noteDropped(r *Route) {
|
|
if r.offFeed {
|
|
return
|
|
}
|
|
l := &t.activity
|
|
l.init()
|
|
l.seq++
|
|
a := activityOf(r)
|
|
a.Phase = phaseDropped
|
|
l.events[(l.seq-1)%routeEventsKeep] = routeActivityEvent{l.cursor(), "request_dropped", t.going(), a}
|
|
r.offFeed = true
|
|
}
|
|
|
|
// going counts the requests still going, under t.mu.
|
|
func (t *trace) going() int {
|
|
n := 0
|
|
for _, r := range t.routes {
|
|
if !r.Done {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// routeEventsAllowed: r may read the feed. It is answered as the usage
|
|
// log's routes are (usageSummary), and refused otherwise.
|
|
func routeEventsAllowed(w http.ResponseWriter, r *http.Request) bool {
|
|
if !local(r) && !sharedWith(r) {
|
|
writeError(w, provider.Chat, http.StatusForbidden, routeEventsRefused)
|
|
return false
|
|
}
|
|
return !refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it is told no one else's routing: GET /v1/magpie/usage/requests tells it its own calls")
|
|
}
|
|
|
|
// activitySnapshot is the requests going now, by id, and the cursor of
|
|
// the last change, read together.
|
|
func (t *trace) activitySnapshot() (string, []routeActivity) {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
t.activity.init()
|
|
routes := []routeActivity{}
|
|
for _, r := range t.routes {
|
|
if !r.Done && !r.offFeed {
|
|
routes = append(routes, activityOf(r))
|
|
}
|
|
}
|
|
return t.activity.cursor(), routes
|
|
}
|
|
|
|
func (s *Server) routeSnapshot(w http.ResponseWriter, r *http.Request) {
|
|
if !routeEventsAllowed(w, r) {
|
|
return
|
|
}
|
|
cursor, routes := s.trace.activitySnapshot()
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
writeJSON(w, http.StatusOK, map[string]any{"cursor": cursor, "active": len(routes), "routes": routes})
|
|
}
|
|
|
|
// routeEvents streams the feed's changes after a cursor (Last-Event-ID,
|
|
// else ?after=). It ends when the client goes, when the gateway stops
|
|
// serving (streamsEnding: Shutdown would wait its whole drain for it),
|
|
// when the key it came with is turned off, removed or runs out, and when
|
|
// magpie stops being shared with a reader on another machine.
|
|
func (s *Server) routeEvents(w http.ResponseWriter, r *http.Request) {
|
|
if !routeEventsAllowed(w, r) {
|
|
return
|
|
}
|
|
cursor := r.Header.Get("Last-Event-ID")
|
|
if cursor == "" {
|
|
cursor = r.URL.Query().Get("after")
|
|
}
|
|
keyID, remote := access.Caller(r.Context()).KeyID, !local(r)
|
|
// still: the reader may still be told the feed, read again at most
|
|
// once routeEventsRecheck, as it reads the key store and settings
|
|
// from disk under the lock every request's key check takes
|
|
var checked time.Time
|
|
still := func() bool {
|
|
if time.Since(checked) < routeEventsRecheck {
|
|
return true
|
|
}
|
|
checked = time.Now()
|
|
return (keyID == "" || access.On(keyID)) && (!remote || remoteKeyed())
|
|
}
|
|
t := &s.trace
|
|
beat := time.NewTicker(routeEventsBeat)
|
|
defer beat.Stop()
|
|
rc := http.NewResponseController(w)
|
|
defer rc.SetWriteDeadline(time.Time{})
|
|
started := false
|
|
write := func(event, id string, data any) bool {
|
|
b, err := json.Marshal(data)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
if id != "" {
|
|
if _, err = fmt.Fprintf(w, "id: %s\n", id); err != nil {
|
|
return false
|
|
}
|
|
}
|
|
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
|
|
return err == nil
|
|
}
|
|
for {
|
|
t.mu.Lock()
|
|
t.activity.init()
|
|
events, ok := t.activity.after(cursor)
|
|
if t.wake == nil {
|
|
t.wake = make(chan struct{})
|
|
}
|
|
wake := t.wake
|
|
t.mu.Unlock()
|
|
if !ok {
|
|
reset := map[string]string{"error": "snapshot_required", "snapshot": routeSnapshotPath}
|
|
if started {
|
|
write("reset", "", reset)
|
|
rc.Flush()
|
|
} else {
|
|
writeJSON(w, http.StatusConflict, reset)
|
|
}
|
|
return
|
|
}
|
|
if !started {
|
|
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.Header().Set("X-Accel-Buffering", "no")
|
|
w.WriteHeader(http.StatusOK)
|
|
if err := rc.Flush(); err != nil {
|
|
return
|
|
}
|
|
started = true
|
|
}
|
|
if len(events) > 0 {
|
|
if !still() {
|
|
return
|
|
}
|
|
for _, event := range events {
|
|
if !write("route", event.Cursor, event) {
|
|
return
|
|
}
|
|
cursor = event.Cursor
|
|
}
|
|
if rc.Flush() != nil {
|
|
return
|
|
}
|
|
}
|
|
select {
|
|
case <-r.Context().Done():
|
|
return
|
|
case <-s.streamsEnding():
|
|
return
|
|
case <-wake:
|
|
case <-beat.C:
|
|
checked = time.Time{}
|
|
if !still() || !write("heartbeat", "", struct{}{}) || rc.Flush() != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// streamsEnding closes once the gateway stops serving.
|
|
func (s *Server) streamsEnding() <-chan struct{} {
|
|
s.endingOnce.Do(func() { s.ending = make(chan struct{}) })
|
|
return s.ending
|
|
}
|
|
|
|
// endStreams ends every stream waiting on streamsEnding.
|
|
func (s *Server) endStreams() {
|
|
s.streamsEnding()
|
|
s.endOnce.Do(func() { close(s.ending) })
|
|
}
|