Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
settings: a notification when masking swaps a value for the first time (Must2333 on X)
yetone5637cca1418c
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 19baeaee0..1227a3ee0 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -195,6 +195,7 @@ recorded as a prediction failure (`noPrediction`).- A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.+- A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`.- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.- A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`.- A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`.diff --git a/internal/gateway/masked.go b/internal/gateway/masked.goindex c5d741041..c750fd7f0 100644--- a/internal/gateway/masked.go+++ b/internal/gateway/masked.go@@ -26,6 +26,13 @@ type Masked struct {Key int64 `json:"key,omitempty,string"`}+// OnMasked is told of each request's record as masking makes it, for the+// notification that a value was masked (Must2333 on X); set by the app,+// nil (magpie serve, the CLI) for none. It is on the request's way, so it+// only takes the record: which of its values are new is asked later+// (maskrec.Fresh). The record holds no value and no text around one.+var OnMasked func(maskrec.Record)+// maskHits are what a masker swapped: each value from a gwmw.Teller, and// how many places in all.type maskHits struct {@@ -84,6 +91,11 @@ func noteMaskedUntil(r *http.Request, what string, h maskHits, sent string, routif h.key != nil {*h.key = rec.Key}+ if f := OnMasked; f != nil {+ told := rec+ told.Snips, told.Back = nil, nil // the text around a value stays here+ f(told)+ }m := &Masked{N: rec.N, Key: rec.Key}for _, v := range rec.Values {if v.Action == "warn" {diff --git a/internal/gui/api.go b/internal/gui/api.goindex 5d709cbfe..1b9f61908 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -656,7 +656,7 @@ func settingsState() settingsJSON {s.TerminalDefault = found.Default}s.FX = currentFX()- if (s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0) && notifyProblem != nil {+ if (s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0 || s.MaskAlert) && notifyProblem != nil {s.NotifyProblem = notifyProblem()}s.ProxyNow, s.ProxySource = netproxy.Describe()@@ -1305,6 +1305,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {if _, sent := fields["reduceMotion"]; !sent {in.ReduceMotion = cur.ReduceMotion}+ // nor whether a value masked for the first time is told (Must2333)+ if _, sent := fields["maskAlert"]; !sent {+ in.MaskAlert = cur.MaskAlert+ }in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShownin.Window, in.WindowMaximised = cur.Window, cur.WindowMaximised // the window's own, as it was last resized// and what other pages keep here: which models an agent is shown, and@@ -1447,8 +1451,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {}// an alert turned on or moved is looked at now, the Mac asked for its// leave to notify as it is turned on (#368)- if (in.UsageAlert != cur.UsageAlert || in.BalanceAlert != cur.BalanceAlert || in.ResetReminder != cur.ResetReminder || in.TurnDoneAlert != cur.TurnDoneAlert) &&- (in.UsageAlert > 0 || in.BalanceAlert > 0 || in.ResetReminder > 0 || in.TurnDoneAlert > 0) && onAlerts != nil {+ if (in.UsageAlert != cur.UsageAlert || in.BalanceAlert != cur.BalanceAlert || in.ResetReminder != cur.ResetReminder || in.TurnDoneAlert != cur.TurnDoneAlert || in.MaskAlert != cur.MaskAlert) &&+ (in.UsageAlert > 0 || in.BalanceAlert > 0 || in.ResetReminder > 0 || in.TurnDoneAlert > 0 || in.MaskAlert) && onAlerts != nil {onAlerts()}// the tray menu follows the page's language (#301)diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 92de86a55..4fb7a536d 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -19645,7 +19645,7 @@ function renderSettings() {row(t("Community"), t("questions, ideas and feedback, on Discord or GitHub"), "", join, repo);// gateway mode leaves out what is written into this computer's agents'// files, and the alerts its desktop would show- for (const r of [$("#plainNamesSegs").parentElement, $("#usageAlertRow"), $("#balanceAlertRow"), $("#resetReminderRow"), $("#turnDoneRow")]) r.hidden = gatewayMode;+ for (const r of [$("#plainNamesSegs").parentElement, $("#usageAlertRow"), $("#balanceAlertRow"), $("#resetReminderRow"), $("#turnDoneRow"), $("#maskAlertRow")]) r.hidden = gatewayMode;// the parts' tabs, one gone whose rows are all hidden heresetSetTab(setTab);}@@ -20828,6 +20828,8 @@ function renderAlerts(s, keep) {const turnOpts = [["0", t("Off")], ...mins.map((m) => [String(m * 60), t("{n} min", { n: m })])];if (d && !mins.some((m) => m * 60 === d)) turnOpts.push([String(d), d % 60 ? t("{n} s", { n: d }) : t("{n} min", { n: d / 60 })]);$("#turnDoneSegs").replaceChildren(segs(turnOpts, String(d), (v) => savePrefs({ ...keep, turnDoneAlert: Number(v) })));+ // a value masked for the first time (Must2333 on X): off until turned on+ $("#maskAlertSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.maskAlert ? "on" : "off", (v) => savePrefs({ ...keep, maskAlert: v === "on" })));}// AGENT_PREFS: an agent's own settings, by its id, each a row kept in@@ -22754,7 +22756,7 @@ function prefsKeep(s) {noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,- turnDoneAlert: s.turnDoneAlert || 0 };+ turnDoneAlert: s.turnDoneAlert || 0, maskAlert: !!s.maskAlert };}// savePrefs sends what the page was drawn with (prefsBase) and the choicediff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex a8096ac5b..ed21bcee8 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1048,6 +1048,8 @@ const I18N = {"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "每周或每月窗口用量不到 85% 即将重置时,或重置卡将过期未用时,提前这么久通知","{n} h before": "提前 {n} 小时","Task done alert": "任务完成提醒",+ "Masking alert": "脱敏提醒",+ "A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "首次脱敏某个值时通知:只说类型和个数,从不显示值本身","A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode 等经由 magpie 的智能体完成一个至少跑了这么久的任务时通知","Notifications are turned off for magpie in the system's settings": "系统设置里关闭了 magpie 的通知","Notifications can't be shown on this system": "此系统无法显示通知",@@ -5113,6 +5115,8 @@ const I18N = {"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "每週或每月時段用量不到 85% 即將重置時,或重置卡將過期未用時,提前這麼久通知","{n} h before": "提前 {n} 小時","Task done alert": "任務完成提醒",+ "Masking alert": "脫敏提醒",+ "A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "首次脫敏某個值時通知:只說類型和個數,從不顯示值本身","A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode 等經由 magpie 的智慧體完成一個至少跑了這麼久的任務時通知","Notifications are turned off for magpie in the system's settings": "系統設定裡關閉了 magpie 的通知","Notifications can't be shown on this system": "此係統無法顯示通知",@@ -9140,6 +9144,8 @@ const I18N = {"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "週間・月間の枠が 85% 未満の使用でリセットされる前、または未使用のリセットが期限切れになる前に、この時間だけ早く通知します","{n} h before": "{n} 時間前","Task done alert": "タスク完了通知",+ "Masking alert": "マスク通知",+ "A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "値を初めてマスクしたときに通知:種類と件数だけで、値そのものは表示しません","A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode など magpie を通るエージェントが、少なくともこの時間かかったタスクを終えたときに通知","Notifications are turned off for magpie in the system's settings": "システム設定で magpie の通知がオフになっています","Notifications can't be shown on this system": "このシステムでは通知を表示できません",@@ -13201,6 +13207,8 @@ const I18N = {"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "Eine Benachrichtigung so lange bevor ein wöchentliches oder monatliches Fenster mit unter 85 % Verbrauch erneuert wird oder ungenutzte Resets verfallen","{n} h before": "{n} Std. vorher","Task done alert": "Benachrichtigung bei fertiger Aufgabe",+ "Masking alert": "Benachrichtigung beim Maskieren",+ "A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "Eine Benachrichtigung, wenn ein Wert zum ersten Mal maskiert wird: Art und Anzahl, nie der Wert selbst","A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Eine Benachrichtigung, wenn Claude Code, Codex, OpenCode oder ein anderer Agent über magpie eine Aufgabe beendet, die mindestens so lange lief","Notifications are turned off for magpie in the system's settings": "Benachrichtigungen für magpie sind in den Systemeinstellungen ausgeschaltet","Notifications can't be shown on this system": "Benachrichtigungen können auf diesem System nicht angezeigt werden",diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.htmlindex 56f7817fb..f97f27226 100644--- a/internal/gui/assets/index.html+++ b/internal/gui/assets/index.html@@ -305,6 +305,10 @@<div class="who"><div class="name" data-t>Task done alert</div><div class="sub" id="turnDoneSub"></div></div><div id="turnDoneSegs"></div></div>+ <div class="row pref" id="maskAlertRow" data-feature="redact">+ <div class="who"><div class="name" data-t>Masking alert</div><div class="sub wraps" data-t>A notification when masking swaps a value for the first time: its kind and how many, never the value itself</div></div>+ <div id="maskAlertSegs"></div>+ </div></div><div class="row-head warm-head" data-feature="warmups"><div class="warm-tabs" id="warmTabs" role="tablist"><button type="button" role="tab" id="warmTab-codex" data-warm="codex" aria-controls="codexWarmList">Codex</button>diff --git a/internal/gui/mask_alert.go b/internal/gui/mask_alert.gonew file mode 100644index 000000000..31ee5d377--- /dev/null+++ b/internal/gui/mask_alert.go@@ -0,0 +1,239 @@+package gui++import (+ "fmt"+ "slices"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/maskrec"+)++// The notification that masking swapped a value (Must2333 on X: "我还希望+// 能即时的知道发生了替换,但不是通过随时监控网关的方式"). It says what kind of+// value and how many, and which agent sent it; never the value, nor any+// part of it (a record's Head is not read here).+//+// It stays quiet: only a value masked for the first time is news+// (maskrec.Fresh), since a conversation sends its whole history again each+// turn; the records of a burst (an agent's tool calls, one after another)+// are gathered for maskGather and said as one; and one is said at most+// every maskGap, what comes in between said after it.++// maskGather is how long after a record its notification waits for more;+// maskGap is the least time from one notification to the next.+var (+ maskGather = 3 * time.Second+ maskGap = time.Minute+)++// maskPendingMax bounds the records waiting; past it a record is dropped,+// its values still masked and in the 脱敏 page, only not told.+const maskPendingMax = 5000++// maskNote is one notification: the new values by kind, the agents that+// sent them in the order they came, and the latest record with one, which+// a click opens the 脱敏 page on.+type maskNote struct {+ Kinds map[string]int+ Agents []string+ Key int64+}++func (n maskNote) total() int {+ t := 0+ for _, c := range n.Kinds {+ t += c+ }+ return t+}++type maskAlerts struct {+ mu sync.Mutex+ pending []maskrec.Record+ waiting bool // a flush is set to run+ last time.Time // the last notification said++ on func() bool // the setting, read as a record comes and as it is said+ fresh func(maskrec.Record) []maskrec.Value+ send func(maskNote)+ now func() time.Time+ after func(time.Duration, func())+}++func newMaskAlerts(on func() bool, send func(maskNote)) *maskAlerts {+ return &maskAlerts{on: on, send: send, fresh: maskrec.Fresh, now: time.Now,+ after: func(d time.Duration, f func()) { time.AfterFunc(d, f) }}+}++// add takes a request's record; it is on the request's way, so it only+// keeps it.+func (m *maskAlerts) add(r maskrec.Record) {+ if !m.on() {+ return+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if len(m.pending) >= maskPendingMax {+ return+ }+ m.pending = append(m.pending, r)+ if m.waiting {+ return+ }+ m.waiting = true+ wait := maskGather+ if !m.last.IsZero() {+ wait = max(wait, m.last.Add(maskGap).Sub(m.now()))+ }+ m.after(wait, m.flush)+}++// flush says what the records waiting masked for the first time, if any.+func (m *maskAlerts) flush() {+ m.mu.Lock()+ rs := m.pending+ m.pending, m.waiting = nil, false+ m.mu.Unlock()+ if !m.on() {+ return+ }+ n := maskNote{Kinds: map[string]int{}}+ seen := map[string]bool{}+ for _, r := range rs {+ got := false+ for _, v := range m.fresh(r) {+ if seen[v.Placeholder] {+ continue+ }+ seen[v.Placeholder] = true+ n.Kinds[v.Kind]+++ got = true+ }+ if !got {+ continue+ }+ n.Key = max(n.Key, r.Key)+ if r.Agent != "" && !slices.Contains(n.Agents, r.Agent) {+ n.Agents = append(n.Agents, r.Agent)+ }+ }+ if len(n.Kinds) == 0 {+ return+ }+ m.mu.Lock()+ m.last = m.now()+ m.mu.Unlock()+ m.send(n)+}++// maskKinds are the kinds' names in a notification, in en, zh, zh-TW, ja+// and de: the 脱敏 page's own words for them (MASK_KINDS in app.js).+var maskKinds = map[string][5]string{+ "API_KEY": {"API keys", "API 密钥", "API 金鑰", "API キー", "API-Schlüssel"},+ "PRIVATE_KEY": {"Private keys", "私钥", "私鑰", "秘密鍵", "Private Schlüssel"},+ "TOKEN": {"Tokens", "Token", "Token", "トークン", "Token"},+ "PASSWORD": {"Passwords", "密码", "密碼", "パスワード", "Passwörter"},+ "SECRET": {"Secrets", "机密", "機密", "シークレット", "Geheimnisse"},+ "EMAIL": {"Emails", "邮箱", "電子郵件", "メール", "E-Mails"},+ "PHONE": {"Phone numbers", "手机号", "電話號碼", "電話番号", "Telefonnummern"},+ "ID_CARD": {"ID numbers", "身份证号", "身分證號", "身分証番号", "Ausweisnummern"},+ "BANK_CARD": {"Bank cards", "银行卡号", "銀行卡號", "銀行カード", "Bankkarten"},+ "PERSON": {"Names", "姓名", "姓名", "氏名", "Namen"},+ "ADDRESS": {"Addresses", "地址", "地址", "住所", "Adressen"},+ "ACCOUNT": {"Account numbers", "账号", "帳號", "口座番号", "Kontonummern"},+ "SSN": {"SSNs", "社会安全号", "社會安全號碼", "社会保障番号", "SSNs"},+ "PASSPORT": {"Passports", "护照号", "護照號碼", "パスポート番号", "Reisepässe"},+ "IBAN": {"IBANs", "IBAN", "IBAN", "IBAN", "IBANs"},+ "BIRTHDAY": {"Birthdays", "生日", "生日", "誕生日", "Geburtstage"},+ "MAC": {"MAC addresses", "MAC 地址", "MAC 位址", "MAC アドレス", "MAC-Adressen"},+ "SERIAL": {"Serial numbers", "序列号", "序號", "シリアル番号", "Seriennummern"},+ "USERNAME": {"User names", "用户名", "使用者名稱", "ユーザー名", "Benutzernamen"},+ "HOSTNAME": {"Computer names", "电脑名", "電腦名稱", "コンピュータ名", "Computernamen"},+ "IP": {"IP addresses", "IP 地址", "IP 位址", "IP アドレス", "IP-Adressen"},+ "BUCKET": {"Buckets", "存储桶", "儲存桶", "バケット", "Buckets"},+ "TERM": {"Your words", "你的词", "你的詞", "あなたの語", "Deine Wörter"},+}++func langIndex(lang string) int {+ switch lang {+ case "zh":+ return 1+ case "zh-TW":+ return 2+ case "ja":+ return 3+ case "de":+ return 4+ }+ return 0+}++// maskKindName is a kind as the notification names it; one of the user's+// own rules is named by the kind they gave it.+func maskKindName(lang, kind string) string {+ if names, ok := maskKinds[kind]; ok {+ return names[langIndex(lang)]+ }+ return kind+}++// maskAlertText is the notification in lang: how many values were masked+// for the first time, then each kind with its count, the most first, and+// the agents that sent them.+func maskAlertText(lang string, n maskNote, agentName func(string) string) (title, body string) {+ kinds := make([]string, 0, len(n.Kinds))+ for k := range n.Kinds {+ kinds = append(kinds, k)+ }+ sort.Slice(kinds, func(i, j int) bool {+ if n.Kinds[kinds[i]] != n.Kinds[kinds[j]] {+ return n.Kinds[kinds[i]] > n.Kinds[kinds[j]]+ }+ return kinds[i] < kinds[j]+ })+ colon, comma := ": ", ", "+ if lang == "zh" || lang == "zh-TW" || lang == "ja" {+ colon, comma = ":", "、"+ }+ var parts []string+ for _, k := range kinds {+ parts = append(parts, fmt.Sprintf("%s%s%d", maskKindName(lang, k), colon, n.Kinds[k]))+ }+ body = strings.Join(parts, comma)+ if len(n.Agents) > 0 {+ names := make([]string, 0, 2)+ for _, a := range n.Agents[:min(2, len(n.Agents))] {+ names = append(names, agentName(a))+ }+ who := strings.Join(names, comma)+ if more := len(n.Agents) - 2; more > 0 {+ who += fmt.Sprintf(" +%d", more)+ }+ body += " · " + who+ }+ t := n.total()+ switch lang {+ case "zh":+ title = fmt.Sprintf("已脱敏 %d 个新值", t)+ case "zh-TW":+ title = fmt.Sprintf("已脫敏 %d 個新值", t)+ case "ja":+ title = fmt.Sprintf("新しい値を %d 件マスクしました", t)+ case "de":+ if t == 1 {+ title = "1 neuer Wert maskiert"+ } else {+ title = fmt.Sprintf("%d neue Werte maskiert", t)+ }+ default:+ if t == 1 {+ title = "Masked 1 new value"+ } else {+ title = fmt.Sprintf("Masked %d new values", t)+ }+ }+ return title, body+}diff --git a/internal/gui/mask_alert_test.go b/internal/gui/mask_alert_test.gonew file mode 100644index 000000000..ef2ffdabf--- /dev/null+++ b/internal/gui/mask_alert_test.go@@ -0,0 +1,178 @@+package gui++import (+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/maskrec"+ "github.com/yetone/magpie/internal/redact"+)++// fakeMaskAlerts is maskAlerts on a clock the test moves, its flush run+// when the test says, what it said kept.+type fakeMaskAlerts struct {+ *maskAlerts+ clock time.Time+ waits []time.Duration+ flushF func()+ said []maskNote+ on bool+}++func newFakeMaskAlerts(t *testing.T) *fakeMaskAlerts {+ t.Helper()+ f := &fakeMaskAlerts{clock: time.Date(2026, 10, 29, 10, 0, 0, 0, time.Local), on: true}+ f.maskAlerts = newMaskAlerts(func() bool { return f.on }, func(n maskNote) { f.said = append(f.said, n) })+ f.now = func() time.Time { return f.clock }+ f.after = func(d time.Duration, fn func()) { f.waits = append(f.waits, d); f.flushF = fn }+ return f+}++// fire runs the flush set, as its wait is over.+func (f *fakeMaskAlerts) fire(t *testing.T) {+ t.Helper()+ if f.flushF == nil {+ t.Fatal("no notification was set to be said")+ }+ fn := f.flushF+ f.flushF = nil+ f.clock = f.clock.Add(f.waits[len(f.waits)-1])+ fn()+}++// mask masks text as the gateway does, and records it as noteMasked does,+// for agent: the record OnMasked is told.+func mask(t *testing.T, text, agent string) maskrec.Record {+ t.Helper()+ var vals []maskrec.Value+ o := redact.Options{Secrets: true, Personal: true, Seen: func(h redact.Hit) {+ vals = append(vals, maskrec.Value{Placeholder: h.Placeholder, Kind: h.Kind, By: h.By, Head: h.Head, Len: h.Len, Action: h.Action})+ }}+ out, n := redact.Mask(text, o)+ if n == 0 {+ t.Fatalf("nothing masked in %q", text)+ }+ if out == text {+ t.Fatalf("text went as written: %q", out)+ }+ return maskrec.Add(maskrec.Record{What: "chat", Agent: agent, N: n, Values: vals})+}++// A conversation sends its history again every turn, so a value masked in+// its first turn is masked in each turn after. Only the first is said;+// a value new in a later turn is said on its own.+func TestMaskAlertFirstTimeOnly(t *testing.T) {+ f := newFakeMaskAlerts(t)+ key := "sk-ant-api03-" + strings.Repeat("Q7vR2mXk", 5)+ turn1 := "deploy with ANTHROPIC_API_KEY=" + key+ f.add(mask(t, turn1, "claude"))+ f.fire(t)+ if len(f.said) != 1 || f.said[0].Kinds["API_KEY"] != 1 || f.said[0].total() != 1 {+ t.Fatalf("turn 1 said %+v, want one API key", f.said)+ }+ // turns 2 and 3: the history again, the key with it, nothing new+ f.clock = f.clock.Add(5 * time.Minute)+ f.add(mask(t, turn1+"\nok, done. what next?", "claude"))+ f.add(mask(t, turn1+"\nok, done. what next?\nrun the tests", "claude"))+ f.fire(t)+ if len(f.said) != 1 {+ t.Fatalf("the history masked again was said again: %+v", f.said[1:])+ }+ // turn 4 brings an email the conversation never had+ f.clock = f.clock.Add(5 * time.Minute)+ f.add(mask(t, turn1+"\nmail the report to [email protected]", "claude"))+ f.fire(t)+ if len(f.said) != 2 || f.said[1].Kinds["EMAIL"] != 1 || f.said[1].total() != 1 {+ t.Fatalf("turn 4 said %+v, want the email alone", f.said[1:])+ }+}++// What is said is the kind, how many and the agent: never the value, no+// piece of it, nor the hint the 脱敏 page keeps of it (a key's prefix).+func TestMaskAlertNeverSaysTheValue(t *testing.T) {+ f := newFakeMaskAlerts(t)+ key := "sk-proj-" + strings.Repeat("Zx9Lm3Pq", 5)+ mail, phone := "[email protected]", "13987654321"+ r := mask(t, "OPENAI_API_KEY="+key+"\ncontact "+mail+" or "+phone, "codex")+ for _, v := range r.Values {+ if v.Head == "" {+ t.Fatalf("the record has no hint to leak, the test proves nothing: %+v", r.Values)+ }+ }+ f.add(r)+ f.fire(t)+ if len(f.said) != 1 || f.said[0].total() != 3 {+ t.Fatalf("said %+v, want the key, the email and the phone", f.said)+ }+ for _, lang := range []string{"en", "zh", "zh-TW", "ja", "de"} {+ title, body := maskAlertText(lang, f.said[0], agentName)+ text := title + "\n" + body+ for _, v := range []string{key, mail, phone} {+ for i := 0; i+4 <= len(v); i++ {+ if strings.Contains(text, v[i:i+4]) {+ t.Fatalf("%s says %q of %q: %s", lang, v[i:i+4], v, text)+ }+ }+ }+ for _, v := range r.Values {+ if len(v.Head) > 1 && strings.Contains(text, v.Head) {+ t.Fatalf("%s says the hint %q: %s", lang, v.Head, text)+ }+ }+ if !strings.Contains(body, "Codex") || !strings.Contains(title, "3") {+ t.Fatalf("%s doesn't say how many or who: %s", lang, text)+ }+ }+}++// An agent's tool calls come one after another, each a request with a new+// value: they are said once, together. What comes while the last one is+// fresh waits a minute from it, and is said then, together too.+func TestMaskAlertCoalesces(t *testing.T) {+ f := newFakeMaskAlerts(t)+ texts := []string{+ "GITHUB_TOKEN=ghp_" + strings.Repeat("aB3dE5fG7h", 4),+ "db: postgres://app:[email protected]:5432/app",+ "write to [email protected]",+ "call 13711112222 tomorrow",+ "AWS key AKIAQWERTYUIOPASDFGH",+ }+ for i, s := range texts {+ f.add(mask(t, s, []string{"claude", "codex", "opencode"}[i%3]))+ }+ if len(f.waits) != 1 || f.waits[0] != maskGather {+ t.Fatalf("waits %v, want one of %v for the burst", f.waits, maskGather)+ }+ f.fire(t)+ if len(f.said) != 1 || f.said[0].total() != len(texts) {+ t.Fatalf("said %d notifications %+v, want one of %d values", len(f.said), f.said, len(texts))+ }+ if got := f.said[0].Agents; len(got) != 3 {+ t.Fatalf("agents %v, want the three that sent them", got)+ }+ if _, body := maskAlertText("en", f.said[0], agentName); !strings.Contains(body, "+1") {+ t.Fatalf("a third agent isn't counted: %s", body)+ }+ // ten seconds on, two more: said a minute after the last, as one+ f.clock = f.clock.Add(10 * time.Second)+ f.add(mask(t, "the admin is [email protected]", "claude"))+ f.add(mask(t, "her phone is 15822223333", "claude"))+ if w := f.waits[len(f.waits)-1]; w != maskGap-10*time.Second {+ t.Fatalf("waits %v after one said 10s ago, want %v", w, maskGap-10*time.Second)+ }+ if len(f.waits) != 2 {+ t.Fatalf("waits %v, want one more for both", f.waits)+ }+ f.fire(t)+ if len(f.said) != 2 || f.said[1].total() != 2 {+ t.Fatalf("said %+v, want the two together", f.said[1:])+ }+ // turned off, nothing is kept or said+ f.on = false+ f.clock = f.clock.Add(time.Hour)+ f.add(mask(t, "and [email protected]", "claude"))+ if f.flushF != nil || len(f.pending) != 0 {+ t.Fatal("a record was kept with the alert off")+ }+}diff --git a/internal/gui/quota_alert_notify.go b/internal/gui/quota_alert_notify.goindex fcfbb4f2e..03e38e226 100644--- a/internal/gui/quota_alert_notify.go+++ b/internal/gui/quota_alert_notify.go@@ -7,6 +7,7 @@ import ("fmt""log""runtime"+ "strconv""strings""sync""sync/atomic"@@ -49,8 +50,8 @@ func (n *notifier) start() error {_ = ns.RegisterNotificationCategory(clickCategory)}ns.OnNotificationResponse(func(r notifications.NotificationResult) {- if opensUsage(runtime.GOOS, r.Response) {- n.h.whenReady(func() { application.InvokeAsync(func() { n.h.ShowMain("usage") }) })+ if v := clickView(runtime.GOOS, r.Response); v != "" {+ n.h.whenReady(func() { application.InvokeAsync(func() { n.h.ShowMain(v) }) })}})n.ns = ns@@ -92,8 +93,12 @@ func (n *notifier) problem() string {}// turnNotice is the id a turn's end is notified under, an alert's-// "magpie-alert-"-const turnNotice = "magpie-turn-"+// "magpie-alert-"; maskNotice a value masked for the first time, followed+// by its record's key and "-"+const (+ turnNotice = "magpie-turn-"+ maskNotice = "magpie-mask-"+)func (n *notifier) send(title, body string) { n.sendAs("magpie-alert-", title, body) }@@ -133,16 +138,24 @@ func notice(goos, id, title, body string) notifications.NotificationOptions {return o}-// opensUsage says whether a response to a notification opens the Usage-// page: a click on an alert does. On a turn's end, where the user goes is-// their agent, not magpie. On Linux only a click (linuxClick) is one: an-// alert dismissed there opened the main window, maximised if it was left-// so, over the desktop with the focus (#2513).-func opensUsage(goos string, r notifications.NotificationResponse) bool {- if strings.HasPrefix(r.ID, turnNotice) {- return false+// clickView is the page a response to a notification opens, "" for none.+// A click on an alert opens Usage; on a value masked, the 脱敏 page at the+// request that masked it. On a turn's end, where the user goes is their+// agent, not magpie. On Linux only a click (linuxClick) is one: an alert+// dismissed there opened the main window, maximised if it was left so,+// over the desktop with the focus (#2513).+func clickView(goos string, r notifications.NotificationResponse) string {+ if strings.HasPrefix(r.ID, turnNotice) || goos == "linux" && r.ActionIdentifier != linuxClick {+ return ""}- return goos != "linux" || r.ActionIdentifier == linuxClick+ if rest, ok := strings.CutPrefix(r.ID, maskNotice); ok {+ key, _, _ := strings.Cut(rest, "-")+ if _, err := strconv.ParseInt(key, 10, 64); err != nil || key == "0" {+ return "masking"+ }+ return "masking&key=" + key+ }+ return "usage"}// watchAlerts tells the user, with a notification, of a window used past@@ -163,9 +176,15 @@ func (h *host) watchAlerts() {go func() {<-h.ready// set before this run: asked now, so Settings can say if it was refused- if s := settings.Load(); s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0 {+ if s := settings.Load(); s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0 || s.MaskAlert {go n.allowed()}+ // a value masked for the first time (Must2333 on X)+ masks := newMaskAlerts(func() bool { return settings.Load().MaskAlert }, func(m maskNote) {+ title, body := maskAlertText(trayLang(settings.Load().Lang, systemLang), m, agentName)+ n.sendAs(fmt.Sprintf("%s%d-", maskNotice, m.Key), title, body)+ })+ gateway.OnMasked = masks.add// an agent's turn done, past the length set (itieniu on X)gateway.TurnDone = func(t gateway.TurnEnd) {title, body := turnDoneText(trayLang(settings.Load().Lang, systemLang), agentName(t.Agent), t)diff --git a/internal/gui/quota_alert_notify_test.go b/internal/gui/quota_alert_notify_test.goindex 02ad16f3d..e5e47c709 100644--- a/internal/gui/quota_alert_notify_test.go+++ b/internal/gui/quota_alert_notify_test.go@@ -12,21 +12,26 @@ import (// desktop with the focus (#2513): Wails reports the dismissal as// DefaultActionIdentifier, so there only the click's own id opens Usage.func TestDismissedAlertOpensNothing(t *testing.T) {- alert, turn := "magpie-alert-1", turnNotice+"1"+ alert, turn, mask := "magpie-alert-1", turnNotice+"1", maskNotice+"1761700000000000001-17617"for _, c := range []struct {goos, id, action string- want bool+ want string}{- {"linux", alert, notifications.DefaultActionIdentifier, false}, // dismissed- {"linux", alert, linuxClick, true}, // clicked- {"linux", turn, linuxClick, false},- {"darwin", alert, notifications.DefaultActionIdentifier, true},- {"windows", alert, notifications.DefaultActionIdentifier, true},- {"windows", turn, notifications.DefaultActionIdentifier, false},+ {"linux", alert, notifications.DefaultActionIdentifier, ""}, // dismissed+ {"linux", alert, linuxClick, "usage"}, // clicked+ {"linux", turn, linuxClick, ""},+ {"linux", mask, notifications.DefaultActionIdentifier, ""},+ {"linux", mask, linuxClick, "masking&key=1761700000000000001"},+ {"darwin", alert, notifications.DefaultActionIdentifier, "usage"},+ {"darwin", mask, notifications.DefaultActionIdentifier, "masking&key=1761700000000000001"},+ {"darwin", maskNotice + "0-1", notifications.DefaultActionIdentifier, "masking"},+ {"windows", alert, notifications.DefaultActionIdentifier, "usage"},+ {"windows", turn, notifications.DefaultActionIdentifier, ""},+ {"windows", mask, notifications.DefaultActionIdentifier, "masking&key=1761700000000000001"},} {r := notifications.NotificationResponse{ID: c.id, ActionIdentifier: c.action}- if got := opensUsage(c.goos, r); got != c.want {- t.Errorf("opensUsage(%s, %s %s) = %v, want %v", c.goos, c.id, c.action, got, c.want)+ if got := clickView(c.goos, r); got != c.want {+ t.Errorf("clickView(%s, %s %s) = %q, want %q", c.goos, c.id, c.action, got, c.want)}}}diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.mdindex 5e2b9d2aa..cd3f238b1 100644--- a/internal/gui/tests/README.md+++ b/internal/gui/tests/README.md@@ -132,6 +132,12 @@ node --test --test-concurrency=1 internal/gui/tests/gateway-caller-keys.test.cjs## Other Browser Regressions+`mask-alert.test.cjs` checks Settings › Usage's Masking alert (Must2333 on+X): after the task done alert, Off to begin with; On saves `maskAlert`,+another setting saved later keeps it, Off saves false, no click moves the+page, and the row goes while masking is switched off. Every language at 900+and 380 wide, in Chromium and WebKit, with the API faked.+`local-address.test.cjs` checks the Address of a local server's provider(Ollama, LM Studio, oMLX, MLX-Serve): under the key in a Server addresssection, folded unless the provider is away from the preset's default or an address typed ordiff --git a/internal/gui/tests/mask-alert.test.cjs b/internal/gui/tests/mask-alert.test.cjsnew file mode 100644index 000000000..15d37d5dd--- /dev/null+++ b/internal/gui/tests/mask-alert.test.cjs@@ -0,0 +1,135 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// The masking alert (Must2333 on X: 我还希望能即时的知道发生了替换,但不是+// 通过随时监控网关的方式): Settings › Usage has "Masking alert" after the+// task done alert, Off to begin with; On saves maskAlert, another setting+// saved later keeps it, Off saves false, and no click moves the page. With+// masking switched off in Plugins › Built-in the row goes with it. Every+// language, wide and narrow, both engines; the API is faked here.+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 { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");++const assets = path.resolve(__dirname, "../assets");++function server(lang, posts, featuresOff) {+ const fixed = {+ theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", dock: false, dockWindow: false, proxy: "",+ redact: true, redactPersonal: false, redactWords: [], codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "",+ trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "", version: "0.1.900", dir: "~/.config/magpie",+ gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], lanURLs: [],+ fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, turnDoneAlert: 0, featuresOff,+ };+ let cur = fixed;+ return async (route) => {+ const req = route.request(), url = new URL(req.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:false,featuresOff:${JSON.stringify(featuresOff)}};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: fixed.fx });+ if (url.pathname === "/api/settings") {+ if (req.method() === "POST") {+ const body = req.postDataJSON();+ posts.push(body);+ cur = { ...fixed, ...body };+ }+ return json(cur);+ }+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });+ 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 words = {+ en: { name: "Masking alert", off: "Off", on: "On",+ sub: "A notification when masking swaps a value for the first time: its kind and how many, never the value itself" },+ zh: { name: "脱敏提醒", off: "关闭", on: "开启", sub: "首次脱敏某个值时通知:只说类型和个数,从不显示值本身" },+ "zh-TW": { name: "脫敏提醒", off: "關閉", on: "開啟", sub: "首次脫敏某個值時通知:只說類型和個數,從不顯示值本身" },+ ja: { name: "マスク通知", off: "オフ", on: "オン", sub: "値を初めてマスクしたときに通知:種類と件数だけで、値そのものは表示しません" },+ de: { name: "Benachrichtigung beim Maskieren", off: "Aus", on: "An",+ sub: "Eine Benachrichtigung, wenn ein Wert zum ersten Mal maskiert wird: Art und Anzahl, nie der Wert selbst" },+};++async function open(engine, width, lang, posts, featuresOff, t, name) {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();+ 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}-${width}-${name}.png`) });+ }+ await browser.close();+ });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", server(lang, posts, featuresOff));+ await watchSettingsReads(page);+ await page.goto("http://magpie.test/?view=settings&tab=usage");+ await settingsDrawn(page); // rows found are the ones that stay (#1659)+ return { page, errors };+}++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of Object.keys(words)) {+ for (const width of [900, 380]) {+ test(`${engine} ${lang} ${width}px: the masking alert is turned on and off on the Settings page`, async (t) => {+ const posts = [];+ const { page, errors } = await open(engine, width, lang, posts, [], t, "mask-alert");+ const posted = async (n) => { for (let i = 0; i < 100 && posts.length < n; i++) await page.waitForTimeout(20); assert.equal(posts.length, n, "posts"); return posts[n - 1]; };+ const w = words[lang];+ const opts = page.locator("#maskAlertSegs .opt");+ await opts.first().waitFor();++ assert.equal((await page.locator("#maskAlertRow .name").textContent()).trim(), w.name);+ assert.equal((await page.locator("#maskAlertRow .sub").textContent()).trim(), w.sub);+ assert.deepEqual(await opts.allTextContents(), [w.off, w.on]);+ assert.equal(await page.locator("#maskAlertSegs .opt.on").textContent(), w.off, "off until turned on");+ // it is the row after the task done alert, in the same group+ assert.equal(await page.locator("#turnDoneRow + #maskAlertRow").count(), 1);+ const over = await page.evaluate(() => {+ const row = document.querySelector("#maskAlertRow").getBoundingClientRect();+ return [...document.querySelectorAll("#maskAlertRow *")].filter((e) => e.getBoundingClientRect().right > Math.max(row.right, innerWidth) + 1).map((e) => e.className || e.id);+ });+ assert.deepEqual(over, [], "nothing past the edge");++ const scrolled = () => page.locator("#view-settings").evaluate((v) => v.scrollTop);+ await reach(page, opts.nth(1));+ let top = await scrolled();+ await opts.nth(1).click();+ assert.equal((await posted(1)).maskAlert, true);+ await page.waitForTimeout(300);+ assert.equal(await page.locator("#maskAlertSegs .opt.on").textContent(), w.on);+ assert.equal(await scrolled(), top, "the click moved the page");++ // another setting saved later keeps it+ await reach(page, page.locator("#currencySegs .opt").nth(1));+ top = await scrolled();+ await page.locator("#currencySegs .opt").nth(1).click();+ assert.equal((await posted(2)).maskAlert, true, "kept by another save");+ await page.waitForTimeout(300);+ assert.equal(await scrolled(), top, "no click moved the page");++ await reach(page, opts.nth(0));+ await opts.nth(0).click();+ assert.equal((await posted(3)).maskAlert, false, "Off saves false");+ assert.equal(await page.locator("#maskAlertRow").evaluate((e) => getComputedStyle(e).borderLeftWidth), "0px");+ assert.deepEqual(errors, []);+ });+ }+ }+ test(`${engine}: with masking switched off, its alert goes too`, async (t) => {+ const { page, errors } = await open(engine, 900, "en", [], ["redact"], t, "mask-alert-off");+ await page.locator("#turnDoneSegs .opt").first().waitFor();+ assert.equal(await page.locator("#maskAlertRow").isVisible(), false);+ assert.equal(await page.locator("#turnDoneRow").isVisible(), true);+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/maskrec/first.go b/internal/maskrec/first.gonew file mode 100644index 000000000..8d8ba2e11--- /dev/null+++ b/internal/maskrec/first.go@@ -0,0 +1,82 @@+package maskrec++import "sync"++// Which values a record has for the first time, for the notification that+// a value was masked (Must2333 on X): told at once, and only once. A+// conversation's history is sent again in full every turn, so a value+// masked in its first turn is masked again in every turn after; only the+// record that masked it first is news.+//+// first is each placeholder by the key of the first record that had it.+// A placeholder is the same for the same value across restarts (redact's+// key is kept on disk), so the index is read from the days kept, the last+// keepDays, as well as from memory: a restart doesn't make the history of+// a conversation new again. Clear leaves it as it is: the user who+// cleared the records was told of those values already.++var firstLoad sync.Mutex // one reading of the days at a time++// noteFirst puts r's values in the index; called with store.mu held.+func noteFirst(m map[string]int64, r Record) {+ for _, v := range r.Values {+ if k, ok := m[v.Placeholder]; !ok || r.Key < k {+ m[v.Placeholder] = r.Key+ }+ }+}++// loadFirst makes the index: what memory has at once, under the lock, then+// the days on disk read without it, since they can be many megabytes and+// Hold, on the request's way, takes the same lock. A record held while+// the days are read is put in the index by Hold, as store.first is there.+func loadFirst() {+ store.mu.Lock()+ store.first = map[string]int64{}+ for _, r := range store.snips {+ noteFirst(store.first, r)+ }+ dir := Dir()+ store.mu.Unlock()+ disk := map[string]int64{}+ if !inTest() {+ for _, d := range files(dir) {+ read(d.path, func(r Record) { noteFirst(disk, r) })+ }+ }+ store.mu.Lock()+ for p, k := range disk {+ if cur, ok := store.first[p]; !ok || k < cur {+ store.first[p] = k+ }+ }+ store.firstRead = true+ store.mu.Unlock()+}++// Fresh are the values r masked that no record before it had: masked for+// the first time. A value sent as written (Action "warn") is not one+// masked. r is a record as Hold returned it, its Key set.+func Fresh(r Record) []Value {+ firstLoad.Lock()+ store.mu.Lock()+ read := store.firstRead+ store.mu.Unlock()+ if !read {+ loadFirst()+ }+ firstLoad.Unlock()+ store.mu.Lock()+ defer store.mu.Unlock()+ var out []Value+ for _, v := range r.Values {+ if v.Action == "warn" {+ continue+ }+ if k, ok := store.first[v.Placeholder]; ok && k < r.Key {+ continue+ }+ out = append(out, v)+ }+ return out+}diff --git a/internal/maskrec/first_test.go b/internal/maskrec/first_test.gonew file mode 100644index 000000000..e24fb1e95--- /dev/null+++ b/internal/maskrec/first_test.go@@ -0,0 +1,65 @@+package maskrec++import (+ "testing"+ "time"+)++func placeholders(vs []Value) []string {+ var out []string+ for _, v := range vs {+ out = append(out, v.Placeholder)+ }+ return out+}++// A value is fresh only in the record that masked it first. The next turn+// of the same conversation, which sends it again with the history, is+// not; nor is it after a restart, when only the days on disk know it; a+// value sent as written was never masked.+func TestFreshOnlyTheFirstTime(t *testing.T) {+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.Local)+ sandbox(t, now)+ key := Value{Placeholder: "{{API_KEY_aaaabbbb}}", Kind: "API_KEY", By: "rule", Head: "sk-", Len: 40}+ mail := Value{Placeholder: "{{EMAIL_ccccdddd}}", Kind: "EMAIL", By: "rule", Head: "a", Len: 12}+ warned := Value{Placeholder: "{{PHONE_eeeeffff}}", Kind: "PHONE", By: "rule", Head: "1", Len: 11, Action: "warn"}++ turn1 := Add(Record{Time: now, What: "chat", Agent: "claude", N: 1, Values: []Value{key}})+ if got := placeholders(Fresh(turn1)); len(got) != 1 || got[0] != key.Placeholder {+ t.Fatalf("turn 1 fresh = %v, want the key", got)+ }+ // turn 2: the key again with the history, a new email, a phone sent as written+ turn2 := Add(Record{Time: now.Add(time.Minute), What: "chat", Agent: "claude", N: 3,+ Values: []Value{{Placeholder: key.Placeholder, Kind: "API_KEY", By: "known", Len: 40}, mail, warned}})+ if got := placeholders(Fresh(turn2)); len(got) != 1 || got[0] != mail.Placeholder {+ t.Fatalf("turn 2 fresh = %v, want the email alone", got)+ }+ // asked again, turn 1 still says its key: the answer is by key, not by+ // when it was asked (the notifier asks after the turns went on)+ if got := placeholders(Fresh(turn1)); len(got) != 1 {+ t.Fatalf("turn 1 asked late = %v", got)+ }++ // a restart: memory is gone, the days on disk are what is left+ store.mu.Lock()+ store.snips, store.first, store.firstRead = nil, nil, false+ store.mu.Unlock()+ turn3 := Add(Record{Time: now.Add(2 * time.Minute), What: "chat", Agent: "claude", N: 2, Values: []Value{key, mail}})+ if got := Fresh(turn3); len(got) != 0 {+ t.Fatalf("after a restart the history is new again: %v", placeholders(got))+ }+}++// A record held while the days are read (Hold on a request's way, Fresh+// in the notifier) is in the index whichever came first.+func TestFreshHeldWhileReading(t *testing.T) {+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.Local)+ sandbox(t, now)+ v := Value{Placeholder: "{{SECRET_gggghhhh}}", Kind: "SECRET", By: "rule", Len: 20}+ a := Add(Record{Time: now, What: "chat", N: 1, Values: []Value{v}})+ _ = Fresh(a) // the index is read+ b := Add(Record{Time: now.Add(time.Second), What: "chat", N: 1, Values: []Value{v}})+ if got := Fresh(b); len(got) != 0 {+ t.Fatalf("a value held after the index was read is fresh again: %v", placeholders(got))+ }+}diff --git a/internal/maskrec/maskrec.go b/internal/maskrec/maskrec.goindex 43716ea1d..d06ae08c1 100644--- a/internal/maskrec/maskrec.go+++ b/internal/maskrec/maskrec.go@@ -110,6 +110,10 @@ var store struct {sent []kept // the latest records' Sent, oldest first// sentBytes is their bodies in all, as storedsentBytes int+ // first is each placeholder by the key of the first record that had+ // it, and firstRead whether the days on disk are in it (first.go)+ first map[string]int64+ firstRead bool}// kept is a record's Sent, zstd.@@ -186,6 +190,9 @@ func Hold(r Record) (Record, func(provider, model string)) {store.sent = store.sent[1:]}store.snips = append(store.snips, r)+ if store.first != nil {+ noteFirst(store.first, r)+ }if len(store.snips) > keepSnips {store.snips = append([]Record(nil), store.snips[len(store.snips)-keepSnips:]...)}diff --git a/internal/maskrec/maskrec_test.go b/internal/maskrec/maskrec_test.goindex af61f10f6..d36bcb4ae 100644--- a/internal/maskrec/maskrec_test.go+++ b/internal/maskrec/maskrec_test.go@@ -16,6 +16,7 @@ func sandbox(t *testing.T, now time.Time) string {Dir, clock, ownTest = func() string { return dir }, func() time.Time { return now }, truestore.mu.Lock()store.days, store.snips, store.sent, store.sentBytes, store.last, store.pruned = nil, nil, nil, 0, 0, time.Time{}+ store.first, store.firstRead = nil, falsestore.mu.Unlock()t.Cleanup(func() { Dir, clock, ownTest = oldDir, oldClock, oldOwn })return dirdiff --git a/internal/settings/settings.go b/internal/settings/settings.goindex c51b161b9..97e26ffa1 100644--- a/internal/settings/settings.go+++ b/internal/settings/settings.go@@ -495,6 +495,11 @@ type Settings struct {// notification (itieniu on X): a long task set going while the user// works elsewhere. Only turns the app's own gateway serves; 0 is off.TurnDoneAlert int `json:"turnDoneAlert,omitempty"`+ // MaskAlert has magpie say with a notification when masking swaps a+ // value it never masked before (Must2333 on X): its kind and how many,+ // never the value, a burst said once and at most once a minute. Only+ // requests the app's own gateway serves; off until turned on.+ MaskAlert bool `json:"maskAlert,omitempty"`// PlainNames has the model lists magpie gives agents name each model// by its name alone, without its provider's or "routing group" after it// (#335) — but for two in one list that would read the same, which keep