diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 432c63241..9862d8481 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1128,6 +1128,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st window := cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model)) tr = s.trace.beginFor(r, Route{turn: turn, window: window, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: callerOf(r).agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: tier, Provider: "openai", Subagent: subagentPickOf(r), Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Tier: tier, Start: start}}}) + noteChecked(r, sentWhole, maskedHits) if m := noteMasked(r, "chat", maskedHits, sentOf(maskedHits, body), tr.ID, "openai", model); m != nil { s.trace.update(tr, func(t *Route) { t.Masked = m }) } diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go index 466ab57f4..874f9149b 100644 --- a/internal/gateway/codex_backend_test.go +++ b/internal/gateway/codex_backend_test.go @@ -1392,7 +1392,15 @@ func TestCodexOwnSignInKeepsItsMaskingTime(t *testing.T) { rec := httptest.NewRecorder() req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`)) req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("User-Agent", "codex_cli_rs/0.140.0") + who := agentOf(req) // as its record would name it + looked := checkedOf(who).Looked s.Handler().ServeHTTP(rec, req) + // and is counted as looked over for the Masking page, nothing masked + // in it (eiyuuzaki2333 on X) + if c := checkedOf(who); c.Looked != looked+1 || c.Whole != 0 { + t.Fatalf("Codex's turn counted %+v, %d before", c, looked) + } st := s.Trace(t.Context(), 0, 0) if rec.Code != 200 || len(st.Routes) != 1 { t.Fatalf("%d %+v", rec.Code, st.Routes) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8e762f3fa..09c9ce488 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3477,6 +3477,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // request went as written. The record names the provider and model // the last try went to, not the group's first member, which a // failover may never have reached + noteChecked(r, sentWhole, maskedHits) if !sentWhole { m, done := noteMaskedUntil(r, "chat", maskedHits, sentOf(maskedHits, body), tr.ID, p.ID, call.Model) if m != nil { diff --git a/internal/gateway/masked.go b/internal/gateway/masked.go index c750fd7f0..6bcd24e58 100644 --- a/internal/gateway/masked.go +++ b/internal/gateway/masked.go @@ -112,6 +112,19 @@ func noteMaskedUntil(r *http.Request, what string, h maskHits, sent string, rout return m, done } +// noteChecked counts r's turn (a chat turn, or a native API call) for +// the Masking page while masking is on for it (maskrec.Checked): looked +// over, and whether it changed something (h, which noteMasked records), +// or sent as written (whole) to a model the user set to go unmasked. A turn with nothing to mask has no +// record, and without the count an agent's page read the same as one +// never masked (eiyuuzaki2333 on X). +func noteChecked(r *http.Request, whole bool, h maskHits) { + if !redactionWantedFor(r.Context()) { + return + } + maskrec.Checked(callerOf(r).agent, !whole, h.n > 0 || len(h.hits) > 0) +} + // noteBlocked records a request held back for a value the user set to // block: what it had, nothing of what it would have sent. func noteBlocked(h maskHits) { diff --git a/internal/gateway/masked_checked_test.go b/internal/gateway/masked_checked_test.go new file mode 100644 index 000000000..17180c870 --- /dev/null +++ b/internal/gateway/masked_checked_test.go @@ -0,0 +1,115 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/maskrec" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// checkedOf is agent's count in the summary's checked turns. +func checkedOf(agent string) maskrec.Looked { + for _, c := range maskrec.Sum(1).Checked { + if c.Name == agent { + return c + } + } + return maskrec.Looked{Name: agent} +} + +// Pi's turns, on each API it asks magpie's models on (pi_protocol.go), +// are masked as any agent's are: one carrying a key is recorded under +// Pi, and one with nothing to mask is counted as checked, which the +// Masking page shows, so an agent with no records reads as "checked, +// nothing found" rather than as not masked (eiyuuzaki2333 on X: only +// dsh had records, Pi none). A turn to a model the user set to go +// unmasked is counted as sent as written. +func TestPiTurnsCountedAsChecked(t *testing.T) { + const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst" + var got []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = append(got, string(b)) + if strings.Contains(string(b), `"stream":true`) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "data: {\"id\":\"c1\",\"model\":\"m1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"}}]}\n\n"+ + "data: {\"id\":\"c1\",\"model\":\"m1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"c1","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`) + })) + defer up.Close() + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "mine", Name: "Mine", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1", Unredacted: true}); err != nil { + t.Fatal(err) + } + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + s := New() + send := func(path, body string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + // as Pi sends it: magpie's token, its own name, session affinity + req.Header.Set("Authorization", "Bearer "+Token) + req.Header.Set("User-Agent", "pi/0.70.2") + req.Header.Set("X-Session-Affinity", "pi-session-1") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", path, rec.Code, rec.Body) + } + } + chat := func(model, text string) string { + return `{"model":"` + model + `","stream":false,"messages":[{"role":"system","content":"You are pi."},{"role":"user","content":"` + text + `"}]}` + } + before := checkedOf("pi") + send("/v1/chat/completions", chat("fake/m1", "hello there")) + send("/v1/responses", `{"model":"fake/m1","stream":false,"input":[{"role":"user","content":[{"type":"input_text","text":"hello again"}]}]}`) + send("/v1/messages", `{"model":"fake/m1","max_tokens":64,"messages":[{"role":"user","content":"and once more"}]}`) + if c := checkedOf("pi"); c.Looked-before.Looked != 3 || c.Masked != before.Masked || c.Whole != before.Whole { + t.Fatalf("three turns with nothing to mask: %+v, before %+v", c, before) + } + if rs, _ := maskrec.List(0, 5, maskrec.Filter{Agent: "pi"}); len(rs) != 0 { + t.Fatalf("a record with nothing masked: %+v", rs) + } + + send("/v1/chat/completions", chat("fake/m1", "my key is "+key)) + if strings.Contains(got[len(got)-1], key) { + t.Fatalf("Pi's key went out: %s", got[len(got)-1]) + } + if rs, _ := maskrec.List(0, 5, maskrec.Filter{Agent: "pi"}); len(rs) != 1 || rs[0].Provider != "fake" { + t.Fatalf("Pi's masked turn: %+v", rs) + } + if c := checkedOf("pi"); c.Looked-before.Looked != 4 || c.Masked-before.Masked != 1 { + t.Fatalf("a turn masked: %+v", c) + } + + // to a model set to go unmasked: as written, and counted so + send("/v1/chat/completions", chat("mine/m1", "my key is "+key)) + if !strings.Contains(got[len(got)-1], key) { + t.Fatalf("an unmasked provider got it masked: %s", got[len(got)-1]) + } + if c := checkedOf("pi"); c.Looked-before.Looked != 4 || c.Whole-before.Whole != 1 { + t.Fatalf("a turn sent as written: %+v", c) + } + + // masking off: nothing is counted, nothing is said to be checked + if err := settings.Save(settings.Settings{}); err != nil { + t.Fatal(err) + } + send("/v1/chat/completions", chat("fake/m1", "hello there")) + if c := checkedOf("pi"); c.Looked-before.Looked != 4 || c.Whole-before.Whole != 1 { + t.Fatalf("masking off, counted: %+v", c) + } +} diff --git a/internal/gateway/native.go b/internal/gateway/native.go index ae82c8a53..e91e47899 100644 --- a/internal/gateway/native.go +++ b/internal/gateway/native.go @@ -144,8 +144,8 @@ func (s *Server) nativeArk(w http.ResponseWriter, r *http.Request, p provider.Pr return } // as nativeAny's: one the user set to go unmasked goes as written + var hits maskHits if !p.SkipsRedaction() { - var hits maskHits if err := maskStrings(r.Context(), obj, &hits); err != nil { // fails closed fail(maskStatus(err), err.Error()) return @@ -155,6 +155,7 @@ func (s *Server) nativeArk(w http.ResponseWriter, r *http.Request, p provider.Pr noteMasked(r, "native", hits, string(b), 0, p.ID, model) } } + noteChecked(r, p.SkipsRedaction(), hits) body, _ = json.Marshal(obj) } w, done := restoring(w) @@ -396,6 +397,7 @@ func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Pr fail(http.StatusForbidden, msg) return } + var hits maskHits if redactionWantedFor(r.Context()) && !p.SkipsRedaction() { var v any dec := json.NewDecoder(bytes.NewReader(body)) @@ -406,7 +408,6 @@ func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Pr } // the value inside a list, so a lone string is masked as well box := []any{v} - var hits maskHits if err := maskStrings(r.Context(), box, &hits); err != nil { // fails closed fail(maskStatus(err), err.Error()) return @@ -424,6 +425,7 @@ func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Pr noteMasked(r, "native", hits, string(body), 0, p.ID, call.Model) } } + noteChecked(r, p.SkipsRedaction(), hits) } if masked { var done func() diff --git a/internal/gui/assets/plugins/redact/i18n.js b/internal/gui/assets/plugins/redact/i18n.js index a7b92633f..380d0e333 100644 --- a/internal/gui/assets/plugins/redact/i18n.js +++ b/internal/gui/assets/plugins/redact/i18n.js @@ -2,6 +2,14 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "{n} checked": "检查了 {n} 个", + "{n} masked": "{n} 个有脱敏", + "none to mask": "没有要脱敏的", + "{n} sent as written": "{n} 个按原样发出", + "1 request checked, and it carried nothing to mask": "检查了 1 个请求,里面没有要脱敏的内容", + "{n} requests checked, and none carried anything to mask": "检查了 {n} 个请求,都没有要脱敏的内容", + "1 request from {name} checked, and it carried nothing to mask": "检查了 {name} 的 1 个请求,里面没有要脱敏的内容", + "{n} requests from {name} checked, and none carried anything to mask": "检查了 {name} 的 {n} 个请求,都没有要脱敏的内容", "Turn on masking": "打开脱敏", "Nothing is masked yet": "还没有要脱敏的内容", "Turn off masking": "关闭脱敏", @@ -123,6 +131,14 @@ magpie.strings({ "Sent as written in new messages; earlier ones stay masked, so the cache still holds": "新消息起按原样发送;之前的消息仍脱敏,缓存不受影响", }, "zh-TW": { + "{n} checked": "檢查了 {n} 個", + "{n} masked": "{n} 個有脫敏", + "none to mask": "沒有要脫敏的", + "{n} sent as written": "{n} 個照原樣發出", + "1 request checked, and it carried nothing to mask": "檢查了 1 個請求,裡面沒有要脫敏的內容", + "{n} requests checked, and none carried anything to mask": "檢查了 {n} 個請求,都沒有要脫敏的內容", + "1 request from {name} checked, and it carried nothing to mask": "檢查了 {name} 的 1 個請求,裡面沒有要脫敏的內容", + "{n} requests from {name} checked, and none carried anything to mask": "檢查了 {name} 的 {n} 個請求,都沒有要脫敏的內容", "Turn on masking": "開啟脫敏", "Nothing is masked yet": "還沒有要脫敏的內容", "Turn off masking": "關閉脫敏", @@ -244,6 +260,14 @@ magpie.strings({ "Sent as written in new messages; earlier ones stay masked, so the cache still holds": "新訊息起照原樣送出;之前的訊息仍脫敏,快取不受影響", }, ja: { + "{n} checked": "{n} 件を確認", + "{n} masked": "{n} 件でマスク", + "none to mask": "マスク対象なし", + "{n} sent as written": "{n} 件はそのまま送信", + "1 request checked, and it carried nothing to mask": "1 件のリクエストを確認しました。マスクするものはありませんでした", + "{n} requests checked, and none carried anything to mask": "{n} 件のリクエストを確認しました。どれにもマスクするものはありませんでした", + "1 request from {name} checked, and it carried nothing to mask": "{name} のリクエスト 1 件を確認しました。マスクするものはありませんでした", + "{n} requests from {name} checked, and none carried anything to mask": "{name} のリクエスト {n} 件を確認しました。どれにもマスクするものはありませんでした", "Turn on masking": "マスクをオンにする", "Nothing is masked yet": "まだ何もマスクしていません", "Turn off masking": "マスクをオフにする", @@ -365,6 +389,14 @@ magpie.strings({ "Sent as written in new messages; earlier ones stay masked, so the cache still holds": "新しいメッセージからそのまま送信します。以前のメッセージはマスクしたままなので、キャッシュは保たれます", }, de: { + "{n} checked": "{n} geprüft", + "{n} masked": "{n} maskiert", + "none to mask": "nichts zu maskieren", + "{n} sent as written": "{n} unverändert gesendet", + "1 request checked, and it carried nothing to mask": "1 Anfrage geprüft, sie enthielt nichts zu maskieren", + "{n} requests checked, and none carried anything to mask": "{n} Anfragen geprüft, keine enthielt etwas zu maskieren", + "1 request from {name} checked, and it carried nothing to mask": "1 Anfrage von {name} geprüft, sie enthielt nichts zu maskieren", + "{n} requests from {name} checked, and none carried anything to mask": "{n} Anfragen von {name} geprüft, keine enthielt etwas zu maskieren", "Turn on masking": "Maskierung einschalten", "Nothing is masked yet": "Noch wird nichts maskiert", "Turn off masking": "Maskierung ausschalten", diff --git a/internal/gui/assets/plugins/redact/page.js b/internal/gui/assets/plugins/redact/page.js index eed93227f..819d8973d 100644 --- a/internal/gui/assets/plugins/redact/page.js +++ b/internal/gui/assets/plugins/redact/page.js @@ -59,7 +59,7 @@ function maskLoad(force) { maskBusyDays = days; const p = maskBusy = api("masking/summary?days=" + days).then((sum) => { if (days !== maskDays) return; - maskSum = { days: [], kinds: [], agents: [], providers: [], values: [], by: {}, n: 0, distinct: 0, requests: 0, ...(sum || {}) }; + maskSum = { days: [], kinds: [], agents: [], providers: [], values: [], checked: [], by: {}, n: 0, distinct: 0, requests: 0, ...(sum || {}) }; maskSumDays = days; maskAt = Date.now(); }).catch(() => {}).finally(() => { if (maskBusy === p) maskBusy = null; }); @@ -173,6 +173,7 @@ function drawMaskCard() { if (move && sum.n) maskCountUp(num, sum.n); if (sum.agents.length && sum.providers.length) band.append(maskFlow(sum, move)); else band.append(maskNone()); + if (sum.checked?.length) box.append(maskChecked(sum)); if (move) for (const [i, n] of [...band.children].entries()) n.animate([{ opacity: 0, transform: "translateY(6px)", filter: "blur(6px)" }, {}], { duration: 900, delay: i * 120, easing: "cubic-bezier(.2, .7, .1, 1)", fill: "backwards" }); } @@ -210,6 +211,31 @@ function maskNone() { box.append(" ", link); return box; } +// maskChecked: each agent's requests masking looked over before they +// left, something masked in them or not, and those sent as written to a +// model set to go unmasked. A request with nothing to mask has no record, +// so without it an agent read the same here as one never masked +// (eiyuuzaki2333 on X: Pi's calls on the Gateway page, only dsh's here) +function maskChecked(sum) { + const row = el("div", "msk-checked"); + for (const c of sum.checked.slice(0, 8)) { + const other = c.name === "other", who = other ? { name: t("Other") } : maskWho(c.name, "agent"); + const b = el("button", "mo-node" + (maskL.agent === c.name ? " on" : "")); + b.type = "button"; + b.dataset.agent = c.name; + const says = []; + if (c.looked) says.push(t("{n} checked", { n: fmtN(c.looked) }), c.masked ? t("{n} masked", { n: fmtN(c.masked) }) : t("none to mask")); + if (c.whole) says.push(t("{n} sent as written", { n: fmtN(c.whole) })); + const tx = el("span", "tx"); + tx.append(el("span", "nm", who.name), el("span", "ct", says.join(" · "))); + b.append(icon(who.icon || "generic"), tx); + // a request no agent was named for has no record of its own to show + if (other) b.disabled = true; + else b.onclick = () => maskNarrow({ agent: maskL.agent === c.name ? "" : c.name }); + row.append(b); + } + return row; +} // the way off, beside the way on (ZekeXiao on X: "脱敏好像只有一个打开 // 开关,不能关?"). Both switches go off at once. Your own words mask with neither // on, and only Settings › Privacy can take them out, so with words the @@ -471,7 +497,10 @@ function drawMaskList() { sessPick(b, all, maskL[key], opts, head, (v) => maskNarrow({ [key]: v || "" })); bar.append(b); }; - pick("agent", "Every agent", "Agent", (sum?.agents || []).map((a) => ({ v: a.name, name: maskWho(a.name, "agent").name }))); + // an agent masking looked over with nothing to mask has no record, + // and is in the list too + const agents = [...new Set([...(sum?.agents || []), ...(sum?.checked || [])].map((a) => a.name))].filter((n) => n && n !== "other"); + pick("agent", "Every agent", "Agent", agents.map((n) => ({ v: n, name: maskWho(n, "agent").name }))); pick("provider", "Every provider", "Provider", (sum?.providers || []).map((p) => ({ v: p.name, name: maskWho(p.name, "provider").name }))); } box.append(bar); @@ -550,7 +579,7 @@ async function maskClear() { function maskRequestList(box) { const filtered = maskL.facet || maskL.kind || maskL.agent || maskL.provider; if (maskL.error) return void box.append(el("div", "msk-none err", t(maskL.error))); - if (!maskL.records.length) return void box.append(el("div", "msk-none", maskL.busy || !maskL.read ? t("Loading…") : filtered ? t("Nothing masked matches these filters") : t("Nothing masked yet"))); + if (!maskL.records.length) return void box.append(el("div", "msk-none", maskL.busy || !maskL.read ? t("Loading…") : maskNoneChecked() || (filtered ? t("Nothing masked matches these filters") : t("Nothing masked yet")))); let day = "", list = null; for (const r of maskL.records) { const d = new Date(r.t).toDateString(); @@ -565,6 +594,17 @@ function maskRequestList(box) { list.append(maskRecordRow(r)); } } +// maskNoneChecked: with no record to list, the requests masking looked +// over and found nothing in, for the agent picked or for all +function maskNoneChecked() { + if (maskL.facet || maskL.kind || maskL.provider || maskSumDays !== maskDays) return ""; + const cs = (maskSum?.checked || []).filter((c) => !maskL.agent || c.name === maskL.agent); + const n = cs.reduce((a, c) => a + c.looked, 0); + if (!n || cs.some((c) => c.masked)) return ""; + if (!maskL.agent) return t(n === 1 ? "1 request checked, and it carried nothing to mask" : "{n} requests checked, and none carried anything to mask", { n: fmtN(n) }); + const name = maskWho(maskL.agent, "agent").name; + return t(n === 1 ? "1 request from {name} checked, and it carried nothing to mask" : "{n} requests from {name} checked, and none carried anything to mask", { n: fmtN(n), name }); +} // who to whom, an icon where there is one function maskRoute(into, r) { const a = maskWho(r.agent, "agent"), p = maskWho(r.provider, "provider"); diff --git a/internal/gui/assets/plugins/redact/redact.css b/internal/gui/assets/plugins/redact/redact.css index 740d9d68a..4118e21cd 100644 --- a/internal/gui/assets/plugins/redact/redact.css +++ b/internal/gui/assets/plugins/redact/redact.css @@ -72,6 +72,8 @@ .mo-dot.out { fill: var(--accent); } .mo-cap { margin-top: 8px; text-align: center; font-size: 11px; letter-spacing: .12em; color: var(--muted); } .mo-node.on { background: var(--accent-soft); } +.msk-checked { display: flex; flex-wrap: wrap; gap: 2px 6px; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--line); } +.msk-checked .mo-node { max-width: 100%; } .mo-node .nm { line-height: 16px; } .mo-node .ct { line-height: 13px; } .msk-hub { position: absolute; left: 50%; top: 50%; width: 30px; height: 30px; margin: -15px 0 0 -15px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: var(--card); box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 55%, transparent), 0 0 0 5px var(--card); color: var(--accent); } diff --git a/internal/gui/tests/masking-records.test.cjs b/internal/gui/tests/masking-records.test.cjs index fc602fb6f..54a26cacb 100644 --- a/internal/gui/tests/masking-records.test.cjs +++ b/internal/gui/tests/masking-records.test.cjs @@ -42,6 +42,7 @@ function summary(days) { by: { rule: 7, model: 4 }, agents: [{ name: "claude", n: 30, distinct: 8 }, { name: "codex", n: 12, distinct: 3 }], providers: [{ name: "anthropic", n: 30, distinct: 8 }, { name: "openai", n: 12, distinct: 3 }], + checked: [{ name: "claude", looked: 40, masked: 8 }, { name: "codex", looked: 12, masked: 1, whole: 2 }], values: [ { p: KEY, kind: "API_KEY", by: "rule", head: "sk-p", len: 24, n: 14, requests: 5, last: ago(60e3) }, { p: NAME, kind: "PERSON", by: "model", head: "", len: 3, n: 6, requests: 3, last: ago(3600e3) }, @@ -76,7 +77,7 @@ function serve(lang, sum, asked, opts = {}) { 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({ agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", fields: [] }, { id: "codex", name: "Codex", icon: "codex-color", fields: [] }], profiles: [], settings }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", fields: [] }, { id: "codex", name: "Codex", icon: "codex-color", fields: [] }, { id: "pi", name: "Pi", fields: [] }], profiles: [], settings }); if (url.pathname === "/api/settings") { if (req.method() === "POST") { asked.push("settings " + req.postData()); Object.assign(settings, JSON.parse(req.postData())); } return json(settings); @@ -101,7 +102,7 @@ function serve(lang, sum, asked, opts = {}) { } if (url.pathname === "/api/masking/summary") { const s = sum(+url.searchParams.get("days")); - return json(cleared ? { ...s, days: s.days.map((d) => ({ ...d, requests: 0, n: 0, distinct: 0 })), requests: 0, n: 0, distinct: 0, blocked: 0, kinds: [], by: {}, agents: [], providers: [], values: [] } : s); + return json(cleared ? { ...s, days: s.days.map((d) => ({ ...d, requests: 0, n: 0, distinct: 0 })), requests: 0, n: 0, distinct: 0, blocked: 0, kinds: [], by: {}, agents: [], providers: [], values: [], checked: [] } : s); } if (url.pathname === "/api/masking/records") { asked.push(url.search); @@ -236,12 +237,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const bird = await card.locator(".msk-hub svg").boundingBox(); assert(Math.abs(bird.x + bird.width / 2 - (hub.x + hub.width / 2)) < 1 && Math.abs(bird.y + bird.height / 2 - (hub.y + hub.height / 2)) < 1, "the bird in the middle of its ring"); // each agent and provider with its logo - assert.deepEqual(await card.locator(".mo-node .ic").evaluateAll((ns) => ns.map((n) => n.dataset.icon)), ["claudecode-color", "codex-color", "anthropic", "openai"]); + assert.deepEqual(await card.locator(".mo-flow .mo-node .ic").evaluateAll((ns) => ns.map((n) => n.dataset.icon)), ["claudecode-color", "codex-color", "anthropic", "openai"]); // on both sides the logo first, then the name; a side's logos in one // column and its names on one edge; every logo on a disc of one size // (bare, a logo that fills its box and one that doesn't read as two // sizes) - const nodes = await card.locator(".mo-node:not(:disabled)").evaluateAll((ns) => ns.map((b) => { + const nodes = await card.locator(".mo-flow .mo-node:not(:disabled)").evaluateAll((ns) => ns.map((b) => { const ic = b.querySelector(".ic").getBoundingClientRect(), nm = b.querySelector(".nm").getBoundingClientRect(); return { side: b.parentElement.classList.contains("agent") ? "agent" : "provider", ic: { x: ic.x, w: ic.width, h: ic.height, r: getComputedStyle(b.querySelector(".ic")).borderRadius }, nm: nm.x }; })); @@ -551,6 +552,54 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // strict masking had kept many records): Cancel sends nothing, Clear posts // once and the page reads again to nothing; a failed clear says why and // lists what is still there +// an agent whose requests carried nothing to mask has no record, and the +// card says it was checked all the same, its requests counted, as the +// list does once it is picked (eiyuuzaki2333 on X: Pi's calls on the +// Gateway page, only dsh's on this one); one sent as written to a model +// set to go unmasked says so +const piChecked = (d) => ({ ...summary(d), checked: [{ name: "pi", looked: 128, masked: 0, whole: 3 }, { name: "claude", looked: 40, masked: 8 }, { name: "other", looked: 2, masked: 0 }] }); +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of lang === "en" ? [1100, 640] : [640]) { + test(`${engine} ${lang} ${width}px: an agent with nothing masked shows as checked`, async (t) => { + const { browser, page, errors, asked } = await open(engine, lang, width, piChecked); + t.after(() => browser.close()); + const chips = page.locator("#maskCard .msk-checked .mo-node"); + await chips.first().waitFor(); + assert.deepEqual(await chips.evaluateAll((ns) => ns.map((n) => n.dataset.agent)), ["pi", "claude", "other"]); + const pi = chips.nth(0); + assert.equal(await pi.locator(".nm").innerText(), "Pi"); + const says = await pi.locator(".ct").innerText(); + assert.match(says, /128/); + assert.match(says, /3/); + if (lang === "en") { + assert.equal(says, "128 checked · none to mask · 3 sent as written"); + assert.equal(await chips.nth(1).locator(".ct").innerText(), "40 checked · 8 masked"); + assert.equal(await chips.nth(2).locator(".nm").innerText(), "Other"); + } else for (const w of ["checked", "none to mask", "sent as written", "Other"]) assert(!(await page.locator("#maskCard .msk-checked").innerText()).includes(w), `${w} left in English`); + assert(await chips.nth(2).isDisabled(), "requests no agent was named for have no records to list"); + assert.deepEqual(await wide(page), { page: false, over: [] }); + await shot(page, `checked-${engine}-${lang}-${width}`); + // picked, the list says what was checked rather than a bare empty + await stillClick(page, pi); + await until(() => asked.some((a) => a.includes("agent=pi"))); + const none = page.locator("#maskList .msk-none", { hasText: "128" }); + await none.waitFor(); + const said = await none.innerText(); + assert.match(said, /128/); + assert.match(said, /Pi/); + if (lang === "en") assert.equal(said, "128 requests from Pi checked, and none carried anything to mask"); + else for (const w of ["requests from", "none carried", "Nothing masked"]) assert(!said.includes(w), `${w} left in English: ${said}`); + assert.equal(await page.locator("#maskCard .msk-checked .mo-node.on").getAttribute("data-agent"), "pi"); + // and the agent picker has it, records or not + assert.match(await page.locator("#maskList .msk-bar .sess-pick").first().innerText(), /Pi/); + assert.deepEqual(await wide(page), { page: false, over: [] }); + assert.deepEqual(errors, []); + }); + } + } +} + for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { for (const width of [1100, 640]) { diff --git a/internal/maskrec/checked.go b/internal/maskrec/checked.go new file mode 100644 index 000000000..809ec2bc0 --- /dev/null +++ b/internal/maskrec/checked.go @@ -0,0 +1,234 @@ +package maskrec + +import ( + "encoding/json" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +// A record is made only for a request masking changed, so an agent whose +// requests carried nothing to mask had none, and the page couldn't tell +// "masked, nothing found" from "not masked" (eiyuuzaki2333 on X: Pi's +// calls were on the Gateway page, only dsh's on the Masking page). +// Checked counts each agent's turns by day while masking is on: the ones +// masking looked over before they left, and the ones that went as +// written to a model the user set to go unmasked. A count holds no text. +// +// A day's counts are a file of their own beside its records, +// checked-.json, written over whole (temp and rename) at most every +// checkedEvery while turns come in, kept and cleared as the records are. + +// checkedEvery is how long a count waits in memory before its day's file +// is written again. +const checkedEvery = 5 * time.Second + +// Looked is an agent's turns over some days, as Checked counted them. +type Looked struct { + Name string `json:"name"` + // Looked: turns masking looked over before they left; Masked: those + // it changed, each with a record + Looked int `json:"looked"` + Masked int `json:"masked"` + // Whole: turns sent as written to a model the user set to go unmasked + Whole int `json:"whole,omitempty"` +} + +// tally is an agent's counts in a day's file. +type tally struct { + Looked int `json:"looked,omitempty"` + Masked int `json:"masked,omitempty"` + Whole int `json:"whole,omitempty"` +} + +var checked struct { + mu sync.Mutex + days map[string]map[string]*tally // day → agent → counts, as read and since + dirty map[string]bool + timer *time.Timer + pruned time.Time +} + +// Checked counts one turn of agent's that went to a vendor while masking +// was on: masked says masking looked it over (changed says it changed +// something, and the turn has a record), else it went as written to a +// model the user set to go unmasked. A turn with no agent named is +// counted as "other". +func Checked(agent string, masked, changed bool) { + if agent == "" { + agent = "other" + } + d := clock().Local().Format(dayForm) + checked.mu.Lock() + defer checked.mu.Unlock() + c := checkedDay(d)[agent] + if c == nil { + c = &tally{} + checked.days[d][agent] = c + } + switch { + case !masked: + c.Whole++ + case changed: + c.Looked++ + c.Masked++ + default: + c.Looked++ + } + if inTest() { + return + } + if checked.dirty == nil { + checked.dirty = map[string]bool{} + } + checked.dirty[d] = true + if checked.timer == nil { + checked.timer = time.AfterFunc(checkedEvery, flushChecked) + } +} + +// checkedDay is day d's counts, read from its file the first time; +// checked.mu is held. +func checkedDay(d string) map[string]*tally { + if checked.days == nil { + checked.days = map[string]map[string]*tally{} + } + if m := checked.days[d]; m != nil { + return m + } + m := map[string]*tally{} + if !inTest() { + // a file that can't be read or parsed counts from nothing: it is + // written over with what is counted from now, never a record + if b, err := os.ReadFile(checkedPath(Dir(), d)); err == nil { + _ = json.Unmarshal(b, &m) + for k, v := range m { + if v == nil { + delete(m, k) + } + } + } + } + checked.days[d] = m + return m +} + +func checkedPath(dir, d string) string { return filepath.Join(dir, "checked-"+d+".json") } + +// flushChecked writes each day counted since it was last written. +func flushChecked() { + checked.mu.Lock() + defer checked.mu.Unlock() + checked.timer = nil + dir := Dir() + if os.MkdirAll(dir, 0o700) != nil { + return + } + for d := range checked.dirty { + b, err := json.Marshal(checked.days[d]) + if err == nil && writeWhole(checkedPath(dir, d), b) == nil { + delete(checked.dirty, d) + } + } + if now := clock(); now.Sub(checked.pruned) > time.Hour { + checked.pruned = now + pruneChecked(dir, now) + } +} + +// writeWhole writes b to path through a temp file renamed over it, so a +// reader never has half of it. +func writeWhole(path string, b []byte) error { + f, err := os.CreateTemp(filepath.Dir(path), ".checked-*") + if err != nil { + return err + } + _, err = f.Write(b) + if e := f.Close(); err == nil { + err = e + } + if err == nil { + err = os.Rename(f.Name(), path) + } + if err != nil { + os.Remove(f.Name()) + } + return err +} + +// pruneChecked drops the days' counts older than keepDays. +func pruneChecked(dir string, now time.Time) { + oldest := now.Local().AddDate(0, 0, -keepDays).Format(dayForm) + for _, f := range checkedFiles(dir) { + d := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(f), "checked-"), ".json") + if d < oldest { + os.Remove(f) + delete(checked.days, d) + } + } +} + +func checkedFiles(dir string) []string { + es, _ := os.ReadDir(dir) + var out []string + for _, e := range es { + n := e.Name() + if d, ok := strings.CutPrefix(n, "checked-"); ok { + if d, ok := strings.CutSuffix(d, ".json"); ok { + if _, err := time.Parse(dayForm, d); err == nil { + out = append(out, filepath.Join(dir, n)) + } + } + } + } + return out +} + +// clearChecked deletes the counts, on disk and in memory, as Clear does +// the records; the files that can't be removed are its errors. +func clearChecked() []error { + checked.mu.Lock() + defer checked.mu.Unlock() + var errs []error + for _, f := range checkedFiles(Dir()) { + if err := os.Remove(f); err != nil && !os.IsNotExist(err) { + errs = append(errs, err) + } + } + checked.days, checked.dirty = nil, nil + return errs +} + +// lookedOver is each agent's counts over days, the most first. +func lookedOver(days []string) []Looked { + checked.mu.Lock() + defer checked.mu.Unlock() + by := map[string]*Looked{} + for _, d := range days { + for name, c := range checkedDay(d) { + l := by[name] + if l == nil { + l = &Looked{Name: name} + by[name] = l + } + l.Looked += c.Looked + l.Masked += c.Masked + l.Whole += c.Whole + } + } + out := []Looked{} + for _, l := range by { + out = append(out, *l) + } + sort.Slice(out, func(i, j int) bool { + a, b := out[i], out[j] + if a.Looked+a.Whole != b.Looked+b.Whole { + return a.Looked+a.Whole > b.Looked+b.Whole + } + return a.Name < b.Name + }) + return out +} diff --git a/internal/maskrec/checked_test.go b/internal/maskrec/checked_test.go new file mode 100644 index 000000000..8a16d3326 --- /dev/null +++ b/internal/maskrec/checked_test.go @@ -0,0 +1,112 @@ +package maskrec + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func resetChecked() { + checked.mu.Lock() + defer checked.mu.Unlock() + if checked.timer != nil { + checked.timer.Stop() + } + checked.days, checked.dirty, checked.timer, checked.pruned = nil, nil, nil, time.Time{} +} + +// An agent's turns are counted while masking is on, nothing masked or +// not: the summary says each agent's turns looked over, those masking +// changed and those sent as written, over the days asked for, after a +// restart too (the day's file), and Clear takes them with the records. +// The file holds counts alone. +func TestCheckedCountsEachAgent(t *testing.T) { + now := time.Date(2026, 11, 14, 15, 0, 0, 0, time.Local) + dir := sandbox(t, now) + resetChecked() + t.Cleanup(resetChecked) + for range 3 { + Checked("pi", true, false) + } + Checked("pi", false, false) + Checked("dsh", true, true) + Checked("", true, false) + want := map[string]Looked{"pi": {Name: "pi", Looked: 3, Whole: 1}, "dsh": {Name: "dsh", Looked: 1, Masked: 1}, "other": {Name: "other", Looked: 1}} + check := func(when string, sum Summary) { + t.Helper() + if len(sum.Checked) != 3 || sum.Checked[0].Name != "pi" { + t.Fatalf("%s: %+v", when, sum.Checked) + } + for _, c := range sum.Checked { + if c != want[c.Name] { + t.Fatalf("%s: %+v, want %+v", when, c, want[c.Name]) + } + } + } + check("in memory", Sum(7)) + + flushChecked() + path := filepath.Join(dir, "checked-2026-11-14.json") + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.ContainsAny(string(b), "\n") || !strings.Contains(string(b), `"pi"`) { + t.Fatalf("file: %s", b) + } + // a restart reads the day again, and counts on from it + resetChecked() + check("read back", Sum(7)) + Checked("pi", true, false) + if c := Sum(7).Checked[0]; c.Name != "pi" || c.Looked != 4 { + t.Fatalf("counted on: %+v", c) + } + // a day out of the days asked for isn't counted + clock = func() time.Time { return now.AddDate(0, 0, 3) } + if got := Sum(1).Checked; len(got) != 0 { + t.Fatalf("today's, with nothing counted: %+v", got) + } + if got := Sum(7).Checked; len(got) != 3 { + t.Fatalf("over seven days: %+v", got) + } + // a file that doesn't parse counts from nothing + resetChecked() + os.WriteFile(path, []byte("{half"), 0o600) + if got := Sum(7).Checked; len(got) != 0 { + t.Fatalf("unparsed file: %+v", got) + } + + Checked("pi", true, false) + flushChecked() + if err := Clear(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("Clear left %s: %v", path, err) + } + if got := Sum(7).Checked; len(got) != 0 { + t.Fatalf("after Clear: %+v", got) + } +} + +// A day's counts older than the records are kept goes with them. +func TestCheckedPruned(t *testing.T) { + now := time.Date(2026, 11, 14, 15, 0, 0, 0, time.Local) + dir := sandbox(t, now) + resetChecked() + t.Cleanup(resetChecked) + old := filepath.Join(dir, "checked-2026-10-01.json") + os.WriteFile(old, []byte(`{"pi":{"looked":2}}`), 0o600) + kept := filepath.Join(dir, "checked-2026-11-01.json") + os.WriteFile(kept, []byte(`{"pi":{"looked":2}}`), 0o600) + Checked("pi", true, false) + flushChecked() + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Fatalf("%s kept: %v", old, err) + } + if _, err := os.Stat(kept); err != nil { + t.Fatal(err) + } +} diff --git a/internal/maskrec/maskrec.go b/internal/maskrec/maskrec.go index d06ae08c1..6d89a6f35 100644 --- a/internal/maskrec/maskrec.go +++ b/internal/maskrec/maskrec.go @@ -243,7 +243,8 @@ func settle(r Record, provider, model string) { } // Clear deletes every record kept: each day's file, and what memory has -// of them (their snips, the requests' text). A day goes whole, never +// of them (their snips, the requests' text), and each agent's counts of +// turns looked over (checked.go). A day goes whole, never // rewritten, so nothing is left half-cleared for a reader; a request still // going is written to a new day's file once it is done. A day that can't // be removed stays, and is named in the error. What a placeholder stood @@ -261,6 +262,7 @@ func Clear() error { delete(store.days, d.path) } store.snips, store.sent, store.sentBytes = nil, nil, 0 + errs = append(errs, clearChecked()...) return errors.Join(errs...) } diff --git a/internal/maskrec/summary.go b/internal/maskrec/summary.go index 772ae0b89..e6f24377f 100644 --- a/internal/maskrec/summary.go +++ b/internal/maskrec/summary.go @@ -133,6 +133,9 @@ type Summary struct { Providers []Count `json:"providers"` Values []Seen `json:"values"` // the most masked first, at most topValues Since string `json:"since,omitempty"` + // Checked: each agent's turns masking looked over, or that went as + // written to a model set to go unmasked, nothing masked or not + Checked []Looked `json:"checked"` } const topValues = 60 @@ -150,6 +153,7 @@ func Sum(days int) Summary { if fs := files(dir); len(fs) > 0 { out.Since = fs[0].day } + var dayNames []string vals := map[string]*Seen{} kinds := map[string]*Count{} kindVals := map[string]map[string]bool{} @@ -157,6 +161,7 @@ func Sum(days int) Summary { whom := map[string]map[string]int{} for i := days - 1; i >= 0; i-- { d := now.AddDate(0, 0, -i).Format(dayForm) + dayNames = append(dayNames, d) var a *dayAgg if inTest() { a = memDay(d) @@ -218,6 +223,7 @@ func Sum(days int) Summary { out.Kinds = ranked(out.Kinds) out.Agents = counts(who) out.Providers = counts(whom) + out.Checked = lookedOver(dayNames) return out }