routing: a request opens to its request and response (Fate on Discord)

Fate asked on Discord to see what a single request on the Routing page sent
and got back, such as a Codex prediction. The bodies were captured already,
in the Gateway page's 40 recent calls and the opt-in request archive, but
nothing led there from a Routing request.

- gateway: a Call carries the Routing request it was (Call.Route = the
  trace's Route.ID), set where serve, the Codex backend and a refused title
  record it. Server.RouteCall finds it in the ring. A route id is not a
  call id. A route names its archive copy (Route.Archive =
  call.archiveName()), set only when the archive was on, so it reaches the
  saved history too.
- gui: GET /api/gateway/call takes ?route= besides ?id=. It is the same
  handler, the same no-store, the same key guard and the same 404 once the
  ring has let the call go.
- Routing page: the story's head has "Request and response". It fetches
  only when pressed, and shows the masked bodies through callBodyPanel (an
  SSE reply reads as its events). A request the ring no longer has shows
  the archive's copy through archivePanel when the route names one.
  Otherwise it says the last 40 are kept until magpie quits and how to turn
  the archive on. Nothing more is captured or kept than before.
- The head now wraps. At narrow widths its buttons ran past the story
  ("Back to live" was cut off at 440px).
- The two button words live in i18n.js: i18n-keys' "a plugin's words are
  its own" found them inside core strings.
- docs/subsystems/gui-shell.md says how a route reaches its bodies.

Tests:
- TestRoutingRequestOpensItsBodies (new): each of two routes gets its own
  bodies; route 0 and an unknown route get 404. Red without
  `call.Route = tr.ID` ("route …: 404").
- TestArchiveWholeBodies now checks that the route names the archive. Red
  without the t.Archive line (`route names archive ""`).
- routing-bodies.test.cjs (new), chromium and webkit at 440px, en, zh,
  zh-TW, ja and de, 10/10. It covers the ring's copy read only when asked,
  hiding, another request closing it, the archive's copy, the
  how-to-keep note, nothing past the story and no left border.
  - Red with the client asking ?id= and with the head's wrap removed.
- routing-request-metrics.test.cjs: with the head wrapped, its 480px
  picker clicks in WebKit landed on the footer. Playwright's WebKit places
  elements in the scrolled view hundreds of px lower than
  getBoundingClientRect, which elementFromPoint agrees with. The test now
  clicks where the page shows them. 5 runs of both engines, 20/20.

Run in a sandbox HOME at f1c91a99c plus this change:
- gofmt -l: clean. go vet -tags nogui: darwin, linux and windows ok.
- GUI: routing-*, panel-routing*, recent-call*, i18n-keys and
  header-relang in both engines: 1079 tests, 1079 pass (a first run had
  2 reds, both fixed above).
- go test ./internal/gui after the i18n move (TestPanelJoinsFullScreenSpaces
  skipped): ok.

Full suite: `go test -timeout 45m ./...` gave 65 ok, 1 FAIL. The FAIL is
internal/gui TestPanelJoinsFullScreenSpaces ("the panel shown doesn't take
the keyboard"), red 3/3 alone here and red the same on origin/main
1d227a7eb just fetched. It is filed as #2450.
This commit is contained in:
yetone
2026-10-16 07:23:55 +08:00
parent 1d227a7eb9
commit af601541ef
14 changed files with 427 additions and 17 deletions
+13
View File
@@ -286,6 +286,19 @@ remain in the list, preserves them across summary refreshes, and offers a
retry after a failed read. See `TestRecentCallBodiesOnDemand` and
`recent-call-bodies.test.cjs`.
A request on the Routing page opens to the same bodies (Fate on Discord):
its story's head has "Request and response", which fetches
`GET /api/gateway/call?route=…` (`Server.RouteCall`) only when pressed.
A call carries the Routing request it was (`Call.Route`, the trace's
`Route.ID`, set where `serve`, the Codex backend and a refused title
record it); a route id is not a call id. When the ring no longer has it,
the story shows the request archive's copy through `archivePanel` if the
route names one (`Route.Archive`, `call.archiveName()`, set only when the
archive was on for that request), and otherwise says how to turn the
archive on. Nothing more is captured than before. See
`TestRoutingRequestOpensItsBodies`, `TestArchiveWholeBodies` and
`routing-bodies.test.cjs`.
### Plugin check-in switches
A plugin's Usage-card Auto check-in button reads the persisted
+5
View File
@@ -232,6 +232,11 @@ func TestArchiveWholeBodies(t *testing.T) {
if u := lastUsage(t); u.Archive == "" || u.Archive != c.Archive {
t.Errorf("usage row names archive %q, the call %q", u.Archive, c.Archive)
}
// the Routing page's request names it too, for its bodies to be
// read back once the recent calls have let them go
if rts := s.Trace(context.Background(), 0, 0).Routes; len(rts) != 1 || rts[0].Archive != c.Archive || c.Route != rts[0].ID {
t.Errorf("route names archive %q (call %q, route %d of %d)", rts[0].Archive, c.Archive, c.Route, rts[0].ID)
}
if left, _ := os.ReadDir(tmp); len(left) != 0 {
t.Errorf("files left behind: %v", left)
}
+1
View File
@@ -983,6 +983,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
errType = provider.ErrorType(refusal)
}
end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output)
call.Route = tr.ID
s.record(call)
servedProvider, servedAccount := codexServed(base, r.Header, on)
rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent,
+1 -1
View File
@@ -408,7 +408,7 @@ func (s *Server) sentNowhere(w http.ResponseWriter, r *http.Request, body []byte
t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, 200, ms, why
t.Done, t.Status, t.Error, t.Millis = true, 200, why, ms
})
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: model, Provider: "magpie",
s.record(Call{Route: tr.ID, Time: start, From: provider.Responses, To: provider.Responses, Model: model, Provider: "magpie",
Agent: agentOf(r), Kind: kind, Status: 200, Millis: ms, Error: why})
appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: agentOf(r), Provider: "magpie", Model: model, Requested: model,
Millis: ms, Status: 200, Rejected: true, Error: why, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header),
+19 -1
View File
@@ -305,7 +305,10 @@ func Taken() bool {
type Call struct {
// ID numbers the call in the Recent-calls ring, from 1, for the page
// to ask for its bodies by (the ring's summary leaves them out, #1521)
ID uint64 `json:"id,omitempty"`
ID uint64 `json:"id,omitempty"`
// Route: the Routing page's request (Route.ID) this call is, for it
// to ask for the call's bodies by while the ring still has them
Route int64 `json:"route,omitempty"`
Time time.Time `json:"time"`
Agent string `json:"agent"` // who called, from the client's User-Agent
Via string `json:"via,omitempty"` // the computer a remote magpie's request came from (AgentHeader)
@@ -420,6 +423,19 @@ func (s *Server) Recent() []Call {
return out
}
// RouteCall is the call the Routing page's request route was, while it is
// still in the ring.
func (s *Server) RouteCall(route int64) (Call, bool) {
s.mu.Lock()
defer s.mu.Unlock()
for i := len(s.recent) - 1; i >= 0; i-- {
if route != 0 && s.recent[i].Route == route {
return s.recent[i], true
}
}
return Call{}, false
}
// RecentCall is the call numbered id while it is still in the ring.
func (s *Server) RecentCall(id uint64) (Call, bool) {
s.mu.Lock()
@@ -3288,7 +3304,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
t.Served, t.Swapped, t.Routed = t.Tries[n-1].Served, t.Tries[n-1].Swapped, t.Tries[n-1].Routed
t.Upstream = t.Tries[n-1].Upstream
}
t.Archive = call.archiveName()
})
call.Route = tr.ID
s.record(call)
if call.To != "" {
rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: model,
+4
View File
@@ -125,6 +125,10 @@ type Route struct {
// in (shortFolder), never the whole path; a request that says none
// takes its session's, as said last (#1068)
Folder string `json:"folder,omitempty"`
// Archive: "<date>/<id>", where the request archive keeps the call,
// when it was on (Call.Archive), for the page to read its bodies back
// once the recent calls have let them go
Archive string `json:"archive,omitempty"`
}
// RouteUsage is one billable attempt's pricing inputs, kept in routing history.
+8
View File
@@ -2439,6 +2439,8 @@ const I18N = {
"No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens.": "还没有请求。让 Agent 使用某个模型,或运行上面的示例;调用会实时显示在这里。",
"Show request and response bodies": "查看请求体和响应体",
"Hide request and response bodies": "收起请求体和响应体",
"Request and response": "请求与响应",
"Hide request and response": "收起请求与响应",
"Request Body": "请求体",
"Response Body": "响应体",
"No body captured": "未捕获到内容",
@@ -6086,6 +6088,8 @@ const I18N = {
"No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens.": "還沒有請求。讓 Agent 使用某個模型,或執行上面的範例;呼叫會即時顯示在這裡。",
"Show request and response bodies": "檢視請求體和回應體",
"Hide request and response bodies": "收起請求體和回應體",
"Request and response": "請求與回應",
"Hide request and response": "收起請求與回應",
"Request Body": "請求體",
"Response Body": "回應體",
"No body captured": "未捕獲到內容",
@@ -9731,6 +9735,8 @@ const I18N = {
"No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens.": "まだリクエストはありません。エージェントにモデルを指定するか、上の例を実行してください。呼び出しはすべてリアルタイムでここに表示されます。",
"Show request and response bodies": "リクエストとレスポンスの本文を表示",
"Hide request and response bodies": "リクエストとレスポンスの本文を隠す",
"Request and response": "リクエストとレスポンス",
"Hide request and response": "リクエストとレスポンスを閉じる",
"Request Body": "リクエスト本文",
"Response Body": "レスポンス本文",
"No body captured": "本文は記録されていません",
@@ -13386,6 +13392,8 @@ const I18N = {
"No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens.": "Noch keine Anfragen. Richten Sie einen Agenten auf ein Modell aus oder führen Sie das Beispiel oben aus; jeder Aufruf erscheint hier sofort.",
"Show request and response bodies": "Anfrage- und Antwort-Body anzeigen",
"Hide request and response bodies": "Anfrage- und Antwort-Body ausblenden",
"Request and response": "Anfrage und Antwort",
"Hide request and response": "Anfrage und Antwort ausblenden",
"Request Body": "Anfrage-Body",
"Response Body": "Antwort-Body",
"No body captured": "Kein Body erfasst",
+72 -3
View File
@@ -104,7 +104,10 @@ function routingPage(part) {
const steps = el("ol", "rt-steps");
// what the request's prompt held: its context window (context.js)
const ctxBox = el("div", "rt-ctx");
log.append(logHead, steps, ctxBox);
// the request's own request and response, opened from its head
const bodies = el("div", "rt-bodies");
bodies.hidden = true;
log.append(logHead, steps, bodies, ctxBox);
const off = el("div", "none rt-off");
// over the stage while a replay plays: the time it is replaying, which
// requests are in flight then, and where it is among them
@@ -1793,12 +1796,13 @@ function routingPage(part) {
// the log is drawn again only when what it says changes: it is asked to
// on every trace update (#308)
let logR = null, headKey = "", stepsKey = "";
let bodiesFor = 0, bodiesKey = ""; // the request opened to its bodies (renderBodies)
function renderLog() {
const r = logR = pinned || cur;
log.hidden = !r;
if (!r) return;
const on = () => listed().filter((x) => x.id >= logR.id);
const head = JSON.stringify([document.documentElement.lang, !!rp, pinned?.id, r.id, r.time, r.done, !!pinned && on().length > 1]);
const head = JSON.stringify([document.documentElement.lang, !!rp, pinned?.id, r.id, r.time, r.done, !!pinned && on().length > 1, bodiesFor === r.id]);
if (headKey !== head) {
headKey = head;
logHead.replaceChildren(
@@ -1809,7 +1813,11 @@ function routingPage(part) {
const usage = el("button", "text", t("View usage"));
usage.dataset.feature = "usage"; // it opens on the Usage page
usage.onclick = () => window.openUsageRoute(logR);
logHead.append(usage);
const open = bodiesFor === r.id;
const wire = el("button", "text rt-bodies-b", t(open ? "Hide request and response" : "Request and response"));
wire.setAttribute("aria-expanded", String(open));
wire.onclick = () => { bodiesFor = bodiesFor === logR.id ? 0 : logR.id; renderLog(); };
logHead.append(wire, usage);
const again = el("button", "text", t("Replay"));
again.onclick = () => replay([logR], pinned);
logHead.append(again);
@@ -1828,8 +1836,69 @@ function routingPage(part) {
}
renderSteps(r);
holdStory();
renderBodies(r);
renderCtx(r);
}
// A request's request and response (Fate on Discord: a request on this
// page, a Codex prediction say, couldn't be opened to what was sent and
// what came back). The gateway's recent calls keep the last 40 calls'
// bodies, cut at 256 KB and in memory only, read when asked as the
// Gateway page's are (#1521); once they have let the request go, the
// request archive's copy, when it was on. Nothing more is recorded for
// it: without the archive an older request says how to keep them.
const bodiesGot = new Map(); // route id → { busy } | its bodies | { gone } | { error }
async function loadBodies(id) {
const pending = { busy: true };
bodiesGot.set(id, pending);
let got;
try {
const res = await fetch("/api/gateway/call?route=" + encodeURIComponent(id), { cache: "no-store" });
if (res.status === 404) got = { gone: true };
else if (!res.ok) got = { error: (await res.json().catch(() => null))?.error || res.statusText || String(res.status) };
else got = await res.json();
} catch (e) {
got = { error: e.message };
}
if (bodiesGot.get(id) !== pending) return;
bodiesGot.set(id, got);
bodiesKey = "";
if (logR) renderBodies(logR);
}
function renderBodies(r) {
const open = !rp && r.done && bodiesFor === r.id;
bodies.hidden = !open;
if (!open) {
if (bodiesKey) { bodiesKey = ""; bodies.replaceChildren(); }
return;
}
if (!bodiesGot.has(r.id)) loadBodies(r.id);
const got = bodiesGot.get(r.id);
const key = JSON.stringify([document.documentElement.lang, r.id, r.archive || "", got.busy ? "busy" : got.gone ? "gone" : got.error ? "error" : "in"]);
if (key === bodiesKey) return;
bodiesKey = key;
if (got.busy) { bodies.replaceChildren(el("div", "none", t("Fetching…"))); return; }
if (got.error) {
const again = el("button", "text", t("Try again"));
again.onclick = () => { bodiesGot.delete(r.id); bodiesKey = ""; renderBodies(logR); };
bodies.replaceChildren(el("div", "call-archive-err", t(got.error)), again);
return;
}
if (got.gone) {
if (r.archive) {
const draw = () => { if (bodiesFor === r.id) bodies.replaceChildren(archivePanel(r.archive, "rt|" + r.id, draw)); };
draw();
return;
}
bodies.replaceChildren(el("p", "rt-bodies-gone", t("magpie keeps the request and response of only the last 40 requests, until it quits. To keep every request's, turn on Request archive at the top of Usage › Requests.")));
return;
}
const grid = el("div", "call-details");
grid.append(
callBodyPanel("Request Body", got.requestBody, got.requestTruncated, undefined, "rt|" + r.id + "|req"),
callBodyPanel("Response Body", got.responseBody, got.responseTruncated, "rt|" + r.id),
);
bodies.replaceChildren(grid);
}
// holdStory keeps the story of the live request, its head and its lines,
// as tall as it has been since the reader began following live, at this
// width: a request under way is told in fewer lines than one answered
@@ -78,6 +78,7 @@ magpie.strings({
"Counts since the gateway started": "网关启动以来的统计",
"No failed request in this list": "当前列表中没有失败的请求",
"View usage": "查看用量",
"magpie keeps the request and response of only the last 40 requests, until it quits. To keep every request's, turn on Request archive at the top of Usage › Requests.": "magpie 只保留最近 40 个请求的请求体和响应体,且退出后不再保留。要保留每个请求的,请在「用量 › 请求」顶部打开「请求存档」。",
"Routing history for this request is no longer available.": "此请求的路由历史已不可用。",
"Token breakdown": "Token 明细",
"Input (uncached)": "输入(未缓存)",
@@ -601,6 +602,7 @@ magpie.strings({
"Counts since the gateway started": "閘道啟動以來的統計",
"No failed request in this list": "目前列表中沒有失敗的請求",
"View usage": "檢視用量",
"magpie keeps the request and response of only the last 40 requests, until it quits. To keep every request's, turn on Request archive at the top of Usage › Requests.": "magpie 只保留最近 40 個請求的請求體和回應體,且結束後不再保留。要保留每個請求的,請在「用量 › 請求」頂部開啟「請求存檔」。",
"Routing history for this request is no longer available.": "此請求的路由歷史已不可用。",
"Token breakdown": "Token 明細",
"Input (uncached)": "輸入(未快取)",
@@ -1104,6 +1106,7 @@ magpie.strings({
"Counts since the gateway started": "ゲートウェイ起動以降の集計",
"No failed request in this list": "この一覧に失敗したリクエストはありません",
"View usage": "使用量を表示",
"magpie keeps the request and response of only the last 40 requests, until it quits. To keep every request's, turn on Request archive at the top of Usage › Requests.": "magpie はリクエスト本文とレスポンス本文を直近 40 件のリクエストぶんだけ、終了するまで保持します。すべてのリクエストのものを残すには、「使用量 › リクエスト」の上部で「リクエストアーカイブ」をオンにしてください。",
"Routing history for this request is no longer available.": "このリクエストのルーティング履歴は利用できなくなりました。",
"Token breakdown": "トークン内訳",
"Input (uncached)": "入力(非キャッシュ)",
@@ -1618,6 +1621,7 @@ magpie.strings({
"Counts since the gateway started": "Zähler seit dem Start des Zugangspunkts",
"No failed request in this list": "Keine fehlgeschlagene Anfrage in dieser Liste",
"View usage": "Nutzung anzeigen",
"magpie keeps the request and response of only the last 40 requests, until it quits. To keep every request's, turn on Request archive at the top of Usage › Requests.": "magpie behält Anfrage und Antwort nur der letzten 40 Anfragen, bis es beendet wird. Um sie für jede Anfrage zu behalten, schalte oben unter Nutzung › Anfragen das Anfragearchiv ein.",
"Routing history for this request is no longer available.": "Der Weiterleitungsverlauf dieser Anfrage ist nicht mehr verfügbar.",
"Token breakdown": "Token-Aufschlüsselung",
"Input (uncached)": "Eingabe (nicht gecacht)",
@@ -120,8 +120,16 @@
.rt-stats > span { display: flex; flex-direction: column; }
.rt-stats b { font-size: 19px; line-height: 1.2; font-weight: 650; letter-spacing: -.02em; color: var(--fg); font-variant-numeric: tabular-nums; }
.rt-log { padding-top: 10px; margin-top: 10px; border-top: 1px solid var(--line); }
.rt-log-head { display: flex; align-items: center; font-size: 12px; font-weight: 600; color: var(--fg); }
.rt-log-head { display: flex; flex-wrap: wrap; align-items: center; row-gap: 2px; font-size: 12px; font-weight: 600; color: var(--fg); }
.rt-log-head .grow { flex: 1; }
/* a request's request and response, opened from the story's head */
.rt-bodies { margin-top: 8px; border: 1px solid var(--line-2); border-radius: 8px; overflow: hidden; background: var(--card); }
.rt-bodies[hidden] { display: none; }
.rt-bodies > .call-details { border-top: 0; }
.rt-bodies > .call-archive { border: 0; }
.rt-bodies > .none, .rt-bodies-gone { margin: 0; padding: 10px 12px; font-size: 11.5px; font-weight: 400; color: var(--muted); }
.rt-bodies > .call-archive-err { padding: 10px 12px 4px; }
.rt-bodies > .call-archive-err + button.text { margin: 0 12px 10px; }
.rt-steps { list-style: none; margin: 6px 0 0; padding: 0; display: grid; align-content: start; gap: 5px; counter-reset: rt; }
.rt-steps li { position: relative; padding-left: 20px; font-size: 12.5px; line-height: 1.45; color: var(--fg-2); }
.rt-steps li::before { content: ""; position: absolute; left: 5px; top: .5em; width: 6px; height: 6px; border-radius: 50%; background: var(--muted); }
+15 -8
View File
@@ -957,18 +957,25 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
})
// Recent-call bodies are read only when their row is opened, not with
// every Providers or Gateway refresh (#1521): forty calls' bodies made
// /api/providers 20 MB. The ring may have moved on by then.
// /api/providers 20 MB. The ring may have moved on by then. ?route= is
// the Routing page's request instead of the ring's number (Fate on
// Discord: a request there is opened to its request and response).
mux.HandleFunc("GET /api/gateway/call", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Cache-Control", "no-store")
if gw := served.Load(); gw != nil {
var c gateway.Call
ok := false
if id, err := strconv.ParseUint(r.URL.Query().Get("id"), 10, 64); err == nil {
if c, ok := gw.RecentCall(id); ok {
writeJSON(rw, map[string]any{
"requestBody": c.RequestBody, "responseBody": c.ResponseBody,
"requestTruncated": c.RequestTruncated, "responseTruncated": c.ResponseTruncated,
})
return
}
c, ok = gw.RecentCall(id)
} else if route, err := strconv.ParseInt(r.URL.Query().Get("route"), 10, 64); err == nil {
c, ok = gw.RouteCall(route)
}
if ok {
writeJSON(rw, map[string]any{
"requestBody": c.RequestBody, "responseBody": c.ResponseBody,
"requestTruncated": c.RequestTruncated, "responseTruncated": c.ResponseTruncated,
})
return
}
}
rw.Header().Set("Content-Type", "application/json")
+87
View File
@@ -0,0 +1,87 @@
package gui
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// A request on the Routing page opens to its own request and response
// (Fate on Discord): /api/gateway/call?route= finds the recent call by the
// route's id, each its own, and none for a route the ring doesn't have.
func TestRoutingRequestOpensItsBodies(t *testing.T) {
sandboxHome(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
said := "reply-one"
if strings.Contains(string(b), "second") {
said = "reply-two"
}
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"`+said+`"}}]}`)
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "routed", Name: "Routed", Chat: up.URL, Key: "fixture"}); err != nil {
t.Fatal(err)
}
s := gateway.New()
was := served.Load()
served.Store(s)
t.Cleanup(func() { served.Store(was) })
mux := http.NewServeMux()
providerRoutes(mux, nil)
ask := func(content string) {
t.Helper()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"routed/m","messages":[{"role":"user","content":"`+content+`"}]}`))
r.Header.Set("User-Agent", "codex")
s.Handler().ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("gateway: %d %.200s", w.Code, w.Body)
}
}
ask("first question")
ask("second question")
routes := s.Trace(context.Background(), 0, 0).Routes
if len(routes) != 2 {
t.Fatalf("%d routes, want 2", len(routes))
}
get := func(route int64) (int, map[string]any) {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/gateway/call?route="+strconv.FormatInt(route, 10), nil))
var got map[string]any
json.Unmarshal(w.Body.Bytes(), &got)
return w.Code, got
}
for _, rt := range routes {
if !rt.Done {
t.Fatalf("route %d not done", rt.ID)
}
code, got := get(rt.ID)
if code != http.StatusOK {
t.Fatalf("route %d: %d", rt.ID, code)
}
req, _ := got["requestBody"].(string)
res, _ := got["responseBody"].(string)
second := strings.Contains(req, "second question")
if !second && !strings.Contains(req, "first question") {
t.Fatalf("route %d's request body: %.200s", rt.ID, req)
}
if want := map[bool]string{false: "reply-one", true: "reply-two"}[second]; !strings.Contains(res, want) {
t.Fatalf("route %d's response is not its own: %.200s", rt.ID, res)
}
}
for _, id := range []int64{0, routes[0].ID + routes[1].ID} {
if code, _ := get(id); code != http.StatusNotFound {
t.Fatalf("route %d the ring hasn't: %d", id, code)
}
}
}
+176
View File
@@ -0,0 +1,176 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A request on the Routing page opens to its request and response (Fate
// on Discord: a Codex prediction there couldn't be opened to what was sent
// and what came back). Its story's head has "Request and response": the
// gateway's recent calls' copy by the route's id, read when asked; once
// they have let it go, the request archive's copy when it was on, and
// otherwise how to keep them. Another request picked closes it. Both
// engines, a narrow window, every language; nothing runs out of the story,
// no left-border accent. The API is faked.
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 now = new Date();
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString();
const key = { id: "deepseek", provider: "deepseek", name: "DeepSeek", kind: "provider", model: "deepseek-chat" };
const done = (id, i, extra) => ({ id, seq: id, time: at(i), agent: "codex", kind: "prediction", model: "deepseek/deepseek-chat", provider: "deepseek", order: [key],
tries: [{ id: key.id, model: "deepseek-chat", start: at(i), done: true, status: 200, ms: 900 }],
done: true, status: 200, ms: 900, tokens: 300, served: "deepseek-chat", ...extra });
// 101 still in the recent calls, 100 only in the archive, 99 in neither
const routes = [done(101, 0), done(100, 1, { archive: day + "/abc100" }), done(99, 2)];
let seenCalls = [];
function serve(lang) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
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 json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") {
const d = url.searchParams.get("day");
return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] });
}
if (url.pathname === "/api/gateway/call") {
seenCalls.push(url.search);
const id = url.searchParams.get("route");
if (id === "101") return json({ requestBody: JSON.stringify({ model: "deepseek-chat", messages: [{ role: "user", content: "REQ-101 predict the next words" }] }), responseBody: JSON.stringify({ choices: [{ message: { role: "assistant", content: "RES-101 a prediction" } }] }) });
return route.fulfill({ status: 404, json: { error: "This request is no longer in the recent calls." } });
}
if (url.pathname === "/api/archive") return json({ request: { method: "POST", path: "/v1/chat/completions", headers: { "content-type": ["application/json"] }, body: JSON.stringify({ messages: [{ role: "user", content: "REQ-100 from the archive" }] }), size: 60 }, response: { status: 200, headers: {}, body: JSON.stringify({ choices: [{ message: { content: "RES-100 archived" } }] }), size: 50 } });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/requests") return json({ period: url.searchParams.get("period"), rows: [], offset: 0, total: 0, calls: 0, errors: 0, input: 600, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 2, agents: [{ id: "codex", name: "Codex", icon: "codex-color" }] });
if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ calls: 2, errors: 0, input: 600, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 2, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const want = {
en: { open: "Request and response", hide: "Hide request and response", req: "Request Body", res: "Response Body", gone: "only the last 40 requests", fetch: "Fetch from archive" },
zh: { open: "请求与响应", hide: "收起请求与响应", req: "请求体", res: "响应体", gone: "最近 40 个请求", fetch: "从存档取回" },
"zh-TW": { open: "請求與回應", hide: "收起請求與回應", req: "請求體", res: "回應體", gone: "最近 40 個請求", fetch: "從存檔取回" },
ja: { open: "リクエストとレスポンス", hide: "リクエストとレスポンスを閉じる", req: "リクエスト本文", res: "レスポンス本文", gone: "直近 40 件", fetch: "アーカイブから取得" },
de: { open: "Anfrage und Antwort", hide: "Anfrage und Antwort ausblenden", req: "Anfrage-Body", res: "Antwort-Body", gone: "der letzten 40 Anfragen", fetch: "Aus Archiv abrufen" },
};
// nothing in the bodies' box, nor the head's buttons, runs past the
// story, and none of it has a left-border accent
const fits = (page) => page.locator(".rt-bodies").evaluate((b) => {
const story = b.closest(".rt-log").getBoundingClientRect();
const head = b.closest(".rt-log").querySelector(".rt-log-head");
return {
head: [...head.children].filter((e) => { const r = e.getBoundingClientRect(); return r.width > 0 && (r.left < story.left - 0.5 || r.right > story.right + 0.5); }).map((e) => e.textContent),
out: [...b.querySelectorAll("*")].filter((e) => { const r = e.getBoundingClientRect(); return r.width > 0 && (r.left < story.left - 0.5 || r.right > story.right + 0.5); }).map((e) => e.className),
accent: [...b.querySelectorAll("*")].filter((e) => { const s = getComputedStyle(e); return s.borderLeftWidth !== "0px" && s.borderLeftWidth !== s.borderRightWidth; }).map((e) => e.className),
};
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(want)) {
test(`${engine} ${lang}: a request on the Routing page opens to its request and response`, async (t) => {
seenCalls = [];
const w = want[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width: 440, height: 900 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-routing-bodies.png`), fullPage: true });
}
await browser.close();
});
// a click at the middle of what is shown: with the page scrolled down
// to the story, Playwright's WebKit places what sits in a scroller
// ~700px lower than it shows, and clicks the footer instead
const tap = async (loc) => {
await loc.scrollIntoViewIfNeeded();
const [x, y] = await loc.evaluate((e) => { const r = e.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; });
await page.mouse.click(x, y);
};
const pick = (i) => tap(page.locator(".rt-req").nth(i));
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-day").nth(1).waitFor({ state: "visible", timeout: 15000 });
await page.locator(".rt-day").nth(1).click();
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
// in the recent calls: both bodies, read only when asked
await page.locator(".rt-req").nth(0).click();
const b = page.locator(".rt-log-head .rt-bodies-b");
await b.waitFor();
assert.equal(await b.textContent(), w.open);
assert.equal(await b.getAttribute("aria-expanded"), "false");
assert.equal(await page.locator(".rt-bodies").isVisible(), false);
assert.deepEqual(seenCalls, [], "bodies read before they were asked for");
await tap(b);
await page.locator(".rt-bodies .call-body").nth(1).waitFor();
assert.deepEqual(seenCalls, ["?route=101"]);
assert.equal(await b.textContent(), w.hide);
assert.equal(await b.getAttribute("aria-expanded"), "true");
assert.deepEqual(await page.locator(".rt-bodies .call-body-label").allTextContents(), [w.req, w.res]);
const text = await page.locator(".rt-bodies").innerText();
assert.match(text, /REQ-101/);
assert.match(text, /RES-101/);
assert.deepEqual(await fits(page), { head: [], out: [], accent: [] });
if (process.env.ARTIFACT_DIR) await page.locator(".rt-log").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-routing-bodies-story.png`) });
// closed again by the same button
await tap(b);
await page.locator(".rt-bodies").waitFor({ state: "hidden" });
assert.equal(await page.locator(".rt-log-head .rt-bodies-b").textContent(), w.open);
// another request picked: closed, and opened it reads its own
await tap(page.locator(".rt-log-head .rt-bodies-b"));
await page.locator(".rt-bodies .call-body").nth(1).waitFor();
await pick(1);
await page.locator(".rt-req").nth(1).and(page.locator('[aria-pressed="true"]')).waitFor();
await page.locator(".rt-bodies").waitFor({ state: "hidden" });
assert.equal(await page.locator(".rt-log-head .rt-bodies-b").textContent(), w.open);
// gone from the recent calls, kept by the archive: read back from it
await tap(page.locator(".rt-log-head .rt-bodies-b"));
const fetch = page.locator(".rt-bodies .call-archive button.text").first();
await fetch.waitFor();
assert.equal(await fetch.textContent(), w.fetch);
await tap(fetch);
await page.locator(".rt-bodies .call-archive .call-body").nth(1).waitFor();
const archived = await page.locator(".rt-bodies").innerText();
assert.match(archived, /REQ-100/);
assert.match(archived, /RES-100/);
assert.deepEqual(await fits(page), { head: [], out: [], accent: [] });
// in neither: says how to keep them
await pick(2);
await page.locator(".rt-req").nth(2).and(page.locator('[aria-pressed="true"]')).waitFor();
await tap(page.locator(".rt-log-head .rt-bodies-b"));
const gone = page.locator(".rt-bodies .rt-bodies-gone");
await gone.waitFor();
assert((await gone.textContent()).includes(w.gone), await gone.textContent());
assert.deepEqual(await fits(page), { head: [], out: [], accent: [] });
assert.deepEqual(seenCalls, ["?route=101", "?route=100", "?route=99"]);
assert.deepEqual(errors, []);
});
}
}
@@ -141,13 +141,23 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert(boxes.meta.left >= boxes.to.right - 1 || boxes.meta.top >= boxes.to.bottom - 1, `metadata overlaps destination at ${width}px`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `horizontal page overflow at ${width}px`);
if (width === 480) {
await page.locator("#rtMetrics").click();
// clicks where the page shows the picker and its menu: once the
// story's head wraps at this width (its "Request and response"
// button) the page is scrolled, and Playwright's WebKit then
// places them hundreds of pixels lower, under the footer
const tap = async (loc) => {
const [x, y] = await loc.evaluate((e) => { e.scrollIntoView({ block: "center" }); const r = e.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; });
await page.mouse.click(x, y);
};
await tap(page.locator("#rtMetrics"));
const menu = page.locator(".rt-metric-menu");
const cost = menu.getByRole("menuitemcheckbox", { name: lang === "zh" ? "费用" : "Cost", exact: true });
await cost.click();
await tap(cost);
await page.waitForFunction(() => !document.querySelector(".rt-req .cost"));
assert.equal(await rows.nth(0).locator(".cost").count(), 0, "narrow layout updates before closing the menu");
assert.equal(await menu.isVisible(), true);
await cost.click();
await tap(cost);
await rows.nth(0).locator(".cost").waitFor();
assert.equal(await rows.nth(0).locator(".cost").count(), 1);
assert.equal(await menu.isVisible(), true);
await page.keyboard.press("Escape");