From 3300616492b181f5173febc4481f5ea68612e293 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 27 Oct 2026 06:53:41 +0800 Subject: [PATCH] gateway: a request being masked has the phase redact, and its row says masking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/subsystems/gateway-routing.md | 16 +- internal/gateway/active.go | 10 +- internal/gateway/busy.go | 5 + internal/gateway/redact.go | 4 +- internal/gateway/redact_phase.go | 89 +++++++++++ internal/gateway/redact_phase_test.go | 150 ++++++++++++++++++ internal/gateway/trace.go | 3 + internal/gateway/unrouted.go | 3 + internal/gui/assets/plugins/routing/client.js | 10 +- internal/gui/assets/plugins/routing/i18n.js | 4 + internal/gui/tests/routing-masking.test.cjs | 95 +++++++++++ 11 files changed, 380 insertions(+), 9 deletions(-) create mode 100644 internal/gateway/redact_phase.go create mode 100644 internal/gateway/redact_phase_test.go create mode 100644 internal/gui/tests/routing-masking.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 1ea702743..19764e239 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -275,7 +275,16 @@ recorded as a prediction failure (`noPrediction`). empty, until Codex and magpie were restarted; what held it wasn't found). After `unroutedShow` (15s) a route of provider `magpie` shows it on the Routing page as routing, and gives way to the request's own route - once one is begun (`noteRoute`, `trace.drop`). It is answered 504 after + once one is begun (`noteRoute`, `trace.drop`). While the request is + masked its phase is `redact` (`phaseRedact`, `noteRedacting` in + [`redact_phase.go`](../../internal/gateway/redact_phase.go), around + every `redactedHits` and `maskTextHits`), on `/v1/magpie/concurrency` + and on the route that shows it (`Route.Phase`), so the row says + masking, not routing (fremontdango on Discord: a Claude Code request + sat as "routing…" while it was masked). It holds no text. + `TestMaskingIsAPhase`, `TestNoMaskingNoPhase` in + [`redact_phase_test.go`](../../internal/gateway/redact_phase_test.go), + `routing-masking.test.cjs`. It is answered 504 after `unroutedUnknown` (30s) held in no wait magpie knows of, or after `unroutedMost` (2m) in all but masking (sharwowwow on X: two minutes of spinning before a 504). Masking's time, its wait for the local model's @@ -284,11 +293,12 @@ recorded as a prediction failure (`noPrediction`). 480 KB request it took 90s over on an RX 470/580, behind the requests ahead of it, was answered 504 at 2m every time it was sent (#3682). The known waits are counted as they happen and their time added up (`noteWait`, `waited`): the request's body arriving - (`waitedBody`, every read of `r.Body`), masking (`noteMasking`), System + (`waitedBody`, every read of `r.Body`), masking (`noteMasking`, from + `noteRedacting`), System One's or the decision model's classifier (`askWaited`), an image's description (`seenBody`), Codex's auto reset (`autoReset`), plugins' gateway hooks (`GatewayBegin`) and JS gateway middleware, and every - `notePhase` (slot, rpm, upstream). What is left is magpie's own work + `notePhase` (slot, rpm, upstream, redact). What is left is magpie's own work (the catalog, parsing, planning, reading the usage log), ~8.5s at its slowest (a cold catalog sync), so 30s gives it room on a loaded machine. With no route and nothing written, it is answered 504 in its client's diff --git a/internal/gateway/active.go b/internal/gateway/active.go index 4e465ce6c..2f7f6faf3 100644 --- a/internal/gateway/active.go +++ b/internal/gateway/active.go @@ -16,8 +16,10 @@ import ( // been routed; Phase is said only when the gateway knows it: "slot" while // it waits in a key's or account's queue (MaxConcurrency), "rpm" while it // waits for room in the minute (MaxRPM), "upstream" while a try is out at -// the vendor (the request sent, or its reply streaming). A request served -// another way (a subscription bridge, a title helper) has none. +// the vendor (the request sent, or its reply streaming), "redact" while +// it is masked (noteRedacting: the rules, and the local model with its +// wait for a turn). A request served another way (a subscription bridge, +// a title helper) has none. type Active struct { ID int64 `json:"id"` Agent string `json:"agent"` @@ -44,6 +46,10 @@ type inflight struct { begun []*Route // unrouted: its watch while no route is begun for it (unrouted.go) unrouted *unroutedHold + // tr: the trace its routes are in, for the phase they say (under mu) + tr *trace + // redaction: its maskings, their phase and time (redact_phase.go) + redaction redaction } type inflightKey struct{} diff --git a/internal/gateway/busy.go b/internal/gateway/busy.go index 286b5a526..41234ba8a 100644 --- a/internal/gateway/busy.go +++ b/internal/gateway/busy.go @@ -65,6 +65,11 @@ func (s *Server) counted(h http.Handler) http.Handler { } s.inFlight.Add(1) r, done := s.active.add(r) + if f := inflightOf(r.Context()); f != nil { + f.mu.Lock() + f.tr = &s.trace + f.mu.Unlock() + } w, r, unwatch := s.watchUnrouted(w, r, inflightOf(r.Context())) defer func() { // a panic is net/http's to recover, as before; the routes it diff --git a/internal/gateway/redact.go b/internal/gateway/redact.go index afb8528f6..a91d8aaed 100644 --- a/internal/gateway/redact.go +++ b/internal/gateway/redact.go @@ -37,7 +37,7 @@ func redactedHits(ctx context.Context, w http.ResponseWriter, body []byte) (http h maskHits } began := time.Now() - defer noteMasking(ctx)() + defer noteRedacting(ctx)() o, err := gwmw.Safely(func() out { if t, ok := m.(gwmw.ContextTeller); ok { b, hits := t.JSONHitsContext(ctx, body) @@ -122,7 +122,7 @@ func maskTextHits(ctx context.Context, s string) (gwmw.Masker, string, maskHits, h maskHits } began := time.Now() - defer noteMasking(ctx)() + defer noteRedacting(ctx)() o, err := gwmw.Safely(func() out { if t, ok := m.(gwmw.ContextTeller); ok { got, hits := t.TextHitsContext(ctx, s) diff --git a/internal/gateway/redact_phase.go b/internal/gateway/redact_phase.go new file mode 100644 index 000000000..fe637ecf3 --- /dev/null +++ b/internal/gateway/redact_phase.go @@ -0,0 +1,89 @@ +package gateway + +import ( + "context" + "sync" +) + +// phaseRedact is the phase of a request while it is masked (redactedHits, +// maskTextHits): the rules, and Settings → Privacy's local model with its +// wait for a turn. Its route says it too (Route.Phase), so the Routing +// page's row says masking, not routing, while it lasts (fremontdango on +// Discord: a long Claude Code request sat as routing while it was +// being masked). +const phaseRedact = "redact" + +// redaction is a request's maskings: how many are under way, and the +// phase to put back when the last ends. It holds no text. +type redaction struct { + mu sync.Mutex + now int + restore func() +} + +// noteRedacting tells ctx's request it is being masked, until the func it +// answers is called: its phase is phaseRedact, the route that shows it +// says so, its watch counts the time toward neither of its limits +// (noteMasking). Maskings at once are one, from the first's start to the +// last's end. +func noteRedacting(ctx context.Context) func() { + unmasked := noteMasking(ctx) + f := inflightOf(ctx) + if f == nil { + return unmasked + } + f.redaction.mu.Lock() + if f.redaction.now++; f.redaction.now == 1 { + f.redaction.restore = notePhase(ctx, phaseRedact) + } + f.redaction.mu.Unlock() + f.showRedacting() + var once sync.Once + return func() { + once.Do(func() { + f.redaction.mu.Lock() + var restore func() + if f.redaction.now--; f.redaction.now == 0 { + restore, f.redaction.restore = f.redaction.restore, nil + } + f.redaction.mu.Unlock() + if restore != nil { + restore() + } + unmasked() + f.showRedacting() + }) + } +} + +// redacting says whether f is being masked now. +func (f *inflight) redacting() bool { + f.redaction.mu.Lock() + defer f.redaction.mu.Unlock() + return f.redaction.now > 0 +} + +// showRedacting puts f's phase on the route that shows it, its own or the +// one its watch began (unroutedHold.show), while it isn't done. +func (f *inflight) showRedacting() { + rt := f.route.Load() + f.mu.Lock() + tr := f.tr + if rt == nil && f.unrouted != nil { + rt = f.unrouted.shown + } + f.mu.Unlock() + if rt == nil || tr == nil { + return + } + tr.update(rt, func(r *Route) { + if r.Done { + r.Phase = "" + return + } + r.Phase = "" + if f.redacting() { + r.Phase = phaseRedact + } + }) +} diff --git a/internal/gateway/redact_phase_test.go b/internal/gateway/redact_phase_test.go new file mode 100644 index 000000000..1e9cd3c45 --- /dev/null +++ b/internal/gateway/redact_phase_test.go @@ -0,0 +1,150 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/gwmw" + "github.com/yetone/magpie/internal/settings" +) + +// heldMasker masks nothing, and holds each request it is asked about +// until let is closed: masking that takes as long as the test says. +// entered is closed when the first one reaches it. +type heldMasker struct { + let, entered chan struct{} + once *sync.Once +} + +func (m heldMasker) hold(ctx context.Context) { + m.once.Do(func() { close(m.entered) }) + select { + case <-m.let: + case <-ctx.Done(): + } +} + +func (m heldMasker) JSONHitsContext(ctx context.Context, b []byte) ([]byte, []gwmw.Hit) { + m.hold(ctx) + return b, nil +} + +func (m heldMasker) TextHitsContext(ctx context.Context, s string) (string, []gwmw.Hit) { + m.hold(ctx) + return s, nil +} + +func (m heldMasker) JSONHits(b []byte) ([]byte, []gwmw.Hit) { + return m.JSONHitsContext(context.Background(), b) +} + +func (m heldMasker) TextHits(s string) (string, []gwmw.Hit) { + return m.TextHitsContext(context.Background(), s) +} +func (m heldMasker) JSON(b []byte) ([]byte, int) { b, _ = m.JSONHits(b); return b, 0 } +func (m heldMasker) Text(s string) (string, int) { s, _ = m.TextHits(s); return s, 0 } +func (heldMasker) Restore(s string, _ bool) string { return s } +func (heldMasker) Value(string) (string, bool) { return "", false } +func (heldMasker) Writer(w http.ResponseWriter) (http.ResponseWriter, func()) { + return w, func() {} +} + +// fremontdango on Discord: a Claude Code request sat on the Routing page +// as routing for a long while that it was being masked. While a +// request is masked its phase is "redact", on /v1/magpie/concurrency and +// on the route that shows it. +func TestMaskingIsAPhase(t *testing.T) { + unroutedLimits(t, 10*time.Millisecond, time.Minute) + fresh(t) + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + slowOn(t, "a", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, chatStreamOK) + })) + withoutMasker(t) + m := heldMasker{let: make(chan struct{}), entered: make(chan struct{}), once: new(sync.Once)} + var letOnce sync.Once + let := func() { letOnce.Do(func() { close(m.let) }) } + t.Cleanup(gwmw.Mask(m)) + + s := New() + srv := httptest.NewServer(s.Handler()) + t.Cleanup(srv.Close) + t.Cleanup(let) // before srv.Close, which waits for the request + got := posted(srv, strings.NewReader(`{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + + select { + case <-m.entered: + case r := <-got: + t.Fatalf("answered %d %q %v before it was masked", r.code, r.body, r.err) + case <-time.After(10 * time.Second): + t.Fatal("the request never reached the masker") + } + // its phase, and the route that shows it as held, say masking + deadline := time.Now().Add(10 * time.Second) + for { + phase, shown := "", "" + for _, a := range s.Active() { + phase = a.Phase + } + for _, r := range s.Trace(context.Background(), 0, 0).Routes { + if !r.Done && r.Provider == "magpie" { + shown = r.Phase + } + } + if phase == phaseRedact && shown == phaseRedact { + break + } + if time.Now().After(deadline) { + t.Fatalf("while masked: phase %q, its route's %q", phase, shown) + } + time.Sleep(5 * time.Millisecond) + } + let() + var r unroutedReply + select { + case r = <-got: + case <-time.After(15 * time.Second): + t.Fatal("never answered once masked") + } + if r.err != nil || r.code != 200 || !strings.Contains(r.body, "from b") { + t.Fatalf("answered %d %q %v", r.code, r.body, r.err) + } + + rs := routesOf(s, "a/m") + if len(rs) != 1 || !rs[0].Done || rs[0].Provider != "a" { + t.Fatalf("routes: %+v", rs) + } + rt := rs[0] + if rt.Phase != "" { + t.Fatalf("a done route still says %q", rt.Phase) + } +} + +// A request that isn't masked never has the phase. +func TestNoMaskingNoPhase(t *testing.T) { + fresh(t) + slowOn(t, "a", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, chatStreamOK) + })) + s := New() + code, body := postTo(t, s, "/v1/chat/completions", `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 { + t.Fatalf("%d %s", code, body) + } + rs := routesOf(s, "a/m") + if len(rs) != 1 || rs[0].Phase != "" || rs[0].Own == 0 { + t.Fatalf("routes: %+v", rs) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index f0039b5fe..d41458e0b 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -120,6 +120,9 @@ type Route struct { Own int64 `json:"own,omitempty"` Retried int64 `json:"retried,omitempty"` Queued int64 `json:"queued,omitempty"` + // Phase: "redact" while it is being masked and not yet done + // (noteRedacting), so its row says masking rather than routing + Phase string `json:"phase,omitempty"` // Served: the model the reply says answered, as the last try has it; // Swapped: another than the one that try asked for; Routed: that try // asked another magpie's routing group, and Served is its member diff --git a/internal/gateway/unrouted.go b/internal/gateway/unrouted.go index 3ed9b52ab..b1c53a316 100644 --- a/internal/gateway/unrouted.go +++ b/internal/gateway/unrouted.go @@ -459,6 +459,9 @@ func (u *unroutedHold) showLocked() { if rt.Agent == "" { rt.Agent = u.f.agent } + if u.f.redacting() { + rt.Phase = phaseRedact + } rt.callerKey = access.Caller(u.r.Context()).KeyID u.shown = u.s.trace.begin(rt) } diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index d14156463..c198e2eeb 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -2896,11 +2896,17 @@ function routingPage(part) { // try (#1894) const endWord = (r, last) => `${r.status} · ${failWord(last.gone ? "canceled" : last.fail)}`; + // what a request not yet out at a vendor is doing: being masked + // (Settings → Privacy, the gateway's "redact" phase), or being routed + // (fremontdango on Discord: a long request read as routing while it + // was masked) + const waitWord = (r) => t(r.phase === "redact" ? "masking…" : "routing…"); + // who answered a request, or what its agent got function outcome(r) { if (!r.done) { const tr = r.tries[r.tries.length - 1], w = tr && tried(r, tr); - return [w ? t("{who} is answering…", { who: `${who(w)} · ${w.model}` }) : t("routing…"), "wait", tr]; + return [w ? t("{who} is answering…", { who: `${who(w)} · ${w.model}` }) : waitWord(r), "wait", tr]; } const ok = r.tries.find((tr) => tr.done && tryOk(tr)), w = ok && tried(r, ok); // a 200 whose error is a note of its own — Codex's titles off in @@ -7124,7 +7130,7 @@ function routingPage(part) { const to = el("span", "pr-to"); to.append(el("i", "", "→")); const place = w ? where(w) : r.provider; - if (!r.done) to.append(el("span", "pr-where", w ? t("{who} is answering…", { who: place }) : t("routing…"))); + if (!r.done) to.append(el("span", "pr-where", w ? t("{who} is answering…", { who: place }) : waitWord(r))); else if (how === "bad") { const last = r.tries[r.tries.length - 1]; to.append(el("span", "pr-where", last ? endWord(r, last) : `${r.status || ""} ${r.error || ""}`.trim())); diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 78370c262..2c2038dfc 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -499,6 +499,7 @@ magpie.strings({ "as of {time}": "截至 {time}", "{n} used at {time}; it has renewed since": "{time} 时已用 {n},之后已重置", "routing…": "路由中…", + "masking…": "脱敏中…", "back in {d}": "{d}后恢复", "free · costs nothing": "免费 · 不花额度", "back at {time} · in {d}": "{time} 恢复 · 还有 {d}", @@ -1068,6 +1069,7 @@ magpie.strings({ "as of {time}": "截至 {time}", "{n} used at {time}; it has renewed since": "{time} 時已用 {n},之後已重置", "routing…": "路由中…", + "masking…": "脫敏中…", "back in {d}": "{d}後恢復", "free · costs nothing": "免費 · 不花額度", "back at {time} · in {d}": "{time} 恢復 · 還有 {d}", @@ -1635,6 +1637,7 @@ magpie.strings({ "as of {time}": "{time} 時点", "{n} used at {time}; it has renewed since": "{time} に {n} 使用済み。その後更新されました", "routing…": "ルーティング中…", + "masking…": "マスク中…", "back in {d}": "{d} 後に復帰", "free · costs nothing": "無料 · 枠を消費しない", "back at {time} · in {d}": "{time} に復帰 · あと {d}", @@ -2204,6 +2207,7 @@ magpie.strings({ "as of {time}": "Stand {time}", "{n} used at {time}; it has renewed since": "{n} verbraucht um {time}; seitdem erneuert", "routing…": "leitet weiter…", + "masking…": "maskiert…", "back in {d}": "zurück in {d}", "free · costs nothing": "kostenlos · zählt nicht zum Kontingent", "back at {time} · in {d}": "zurück um {time} · in {d}", diff --git a/internal/gui/tests/routing-masking.test.cjs b/internal/gui/tests/routing-masking.test.cjs new file mode 100644 index 000000000..a8731f712 --- /dev/null +++ b/internal/gui/tests/routing-masking.test.cjs @@ -0,0 +1,95 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A request being masked (Settings → Privacy) says so on the Routing page +// (fremontdango on Discord: a long Claude Code request sat as "routing…" +// while it was masked): its row says masking while the gateway's route for +// it has the "redact" phase, and routing once that is over and no try is +// out yet. Both engines, a narrow window, every language. 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 at = (s) => new Date(now.getTime() - s * 1e3).toISOString(); +const key = { id: "deepseek", provider: "deepseek", name: "DeepSeek", kind: "provider", model: "deepseek-flash" }; +const net = { own: 2.4, asks: 1, send: 0.6, wait: 900, head: 950 }; +const routes = [ + // held, being masked: the route that shows it while it isn't routed + { id: 203, seq: 203, time: at(20), agent: "claude", model: "deepseek/deepseek-flash", provider: "magpie", phase: "redact", order: [], tries: [], done: false, status: 0 }, + // held, masked, not yet routed + { id: 202, seq: 202, time: at(40), agent: "claude", model: "deepseek/deepseek-chat", provider: "magpie", order: [], tries: [], done: false, status: 0 }, + // answered + { id: 201, seq: 201, time: at(90), agent: "claude", model: "deepseek/deepseek-flash", provider: "deepseek", order: [key], + tries: [{ id: key.id, model: "deepseek-flash", start: at(87), done: true, status: 200, ms: 3000, ttft: 1200, net }], + done: true, status: 200, ms: 5400, ttft: 3500, own: 2310, sent: 2320, tokens: 900, served: "deepseek-flash" }, +]; + +function serve(lang) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/settings.json", 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: 203, totals: { requests: 3, rerouted: 0, errors: 0 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], 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: 0, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 0, agents: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 0, errors: 0, input: 0, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, 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: { masking: "masking…", routing: "routing…" }, + zh: { masking: "脱敏中…", routing: "路由中…" }, + "zh-TW": { masking: "脫敏中…", routing: "路由中…" }, + ja: { masking: "マスク中…", routing: "ルーティング中…" }, + de: { masking: "maskiert…", routing: "leitet weiter…" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(want)) { + test(`${engine} ${lang}: a request being masked says so`, async (t) => { + 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}-masking.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + const rows = page.locator(".rt-req"); + await rows.nth(routes.length - 1).waitFor({ timeout: 15000 }); + const said = await rows.evaluateAll((bs) => bs.map((b) => b.textContent)); + assert.equal(said.length, 3); + // newest first: the one masked, the one waiting for its route + assert(said[0].includes(want[lang].masking) && !said[0].includes(want[lang].routing), said[0]); + assert(said[1].includes(want[lang].routing) && !said[1].includes(want[lang].masking), said[1]); + assert(!said[2].includes(want[lang].masking), said[2]); + + assert.deepEqual(errors, []); + }); + } +}