Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gui: Settings > Privacy turns the local model on, and says where it runs (#1977)
yetone07ecdda10f7c
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex ccea32f78..4aeec877d 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -76,6 +76,7 @@ recorded as a prediction failure (`noPrediction`).1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone; the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.+ - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU is started on the CPU for the rest of the run), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, and ends it after 10 minutes with no request ([`internal/pii`](../../internal/pii)). A model that is on and can't answer (not on disk, didn't start, hung) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (`redactionOptions`), so a change applies to the next request.- `DecidesModel` gives a 400.- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model.diff --git a/internal/gui/api.go b/internal/gui/api.goindex 2f6194904..dfcf408eb 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -1127,6 +1127,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {cliBehindRoutes(mux)gatewayFixRoutes(mux)gatewayModeRoutes(mux)+ privacyModelRoutes(mux)builtinRoutes(mux)mux.HandleFunc("GET /api/settings", func(rw http.ResponseWriter, r *http.Request) {access.MigrateLegacyLANKeyBestEffort()@@ -1202,6 +1203,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json onlyin.GatewayConversations = cur.GatewayConversations // Sessions' explicit recording consentin.RedactRules = cur.RedactRules // the masking rules, set on their own+ in.RedactModel = cur.RedactModel // set on its own (privacy-model)in.DisabledModels = cur.DisabledModels // set on their own (disabled-models below, #1867)// used or left is the Usage page's toggle as much as Settings', set on its ownin.QuotaLeft = cur.QuotaLeftdiff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex fb4c6462d..22db3bdee 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -3181,6 +3181,8 @@ body:not(.side-nav) #view-settings .set-head.stuck::before { box-shadow: 0 1px 0.feat-say { margin: 2px 4px 10px; font-size: 12px; line-height: 1.45; color: var(--muted); }.set-searching .feat-say { display: none; }.row.pref .sub.feat-why { color: var(--muted); font-size: 11px; }+/* the local model's row says a download, a device or an error in full */+#privacyModelRow .sub { white-space: normal; overflow-wrap: anywhere; }/* a plugin's settings, under its row (kernel.js ui.form) */.row.pref.feat-set { min-height: 44px; padding-left: 30px; }.row.pref.feat-set .name { font-size: 12.5px; }diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 71452d638..c7c05fb4d 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -21375,6 +21375,8 @@ function renderRedact(s, keep) {r.append(who, val);box.append(r);}+ // the local model finds more of what the switches above mask+ if (s.redact || s.redactPersonal) privacyModelRow(box);// Routing's and Usage's Hide accounts, here too, where privacy is looked forif (window.hideAccounts) row(t("Hide accounts"), t("Email addresses and account names on Usage and Routing are blurred, for a screenshot to share"),onOff(window.hideAccounts.on(), (on) => { window.hideAccounts.set(on); renderSettings(); }));@@ -21397,6 +21399,61 @@ function renderRedact(s, keep) {onOff(!s.noUsageStats, (on) => savePrefs({ ...keep, noUsageStats: !on })));}+// privacyModelRow: the local masking model (internal/pii), downloaded when+// it is turned on and then asked beside the rules. Its state is its own+// (privacy-model): read when the row is drawn, and each second while it+// downloads or starts.+let pmState = null, pmTimer = 0;+function privacyModelRow(box) {+ const r = el("div", "row pref");+ r.id = "privacyModelRow";+ box.append(r);+ let tries = 0;+ const draw = (m) => {+ if (!r.isConnected) return;+ const who = el("div", "who"), val = el("div", "val");+ who.append(el("div", "name", t("Find with a local model")), el("div", "sub", pmSub(m)));+ if (m?.supported || m?.installed) {+ if (m.downloading) {+ const c = el("button", "text", t("Cancel"));+ c.onclick = () => act("cancel");+ val.append(c);+ } else if (m.installed && !m.on) {+ const x = el("button", "text", t("Delete model"));+ x.onclick = async () => {+ if (await confirmAction(t("Delete the model?"), t("Turning it on again downloads {size} again.", { size: fmtBytes(m.size) }), t("Delete"))) act("remove");+ };+ val.append(x);+ }+ val.append(segs([["off", t("Off")], ["on", t("On")]], m.on || m.downloading ? "on" : "off", (v) => act(v)));+ }+ r.replaceChildren(who, val);+ clearTimeout(pmTimer);+ // a download's progress, and where pf-serve runs once it has started+ const starting = m?.on && m.installed && !m.running && !m.failed && tries++ < 30;+ if (m?.downloading || starting) pmTimer = setTimeout(load, 1000);+ };+ const load = () => api("privacy-model").then((m) => { pmState = m; draw(m); }).catch(() => {});+ const act = (doing) => { tries = 0; api("privacy-model", { do: doing }).then((m) => { pmState = m; draw(m); }).catch((e) => { status(t(e.message), "err"); load(); }); };+ draw(pmState);+ load();+}+function pmSub(m) {+ const about = t("Names, addresses and passwords no rule can find, found by a model that runs on this computer");+ if (!m) return about;+ if (!m.supported && !m.installed) return t("Not available on this system yet");+ if (m.downloading) return t("Downloading the model: {done} of {total}", { done: fmtBytes(m.done), total: fmtBytes(m.total) });+ if (m.error) return t("The download stopped: {error}", { error: m.error });+ if (m.on && m.failed) return t("The model didn't answer, so requests are held back: {error}", { error: m.failed });+ if (m.on && m.running) {+ if (m.gpu) return t("On, on the GPU ({device})", { device: m.device });+ return m.gpuError ? t("On, on the CPU: the GPU failed ({error})", { error: m.gpuError }) : t("On, on the CPU");+ }+ if (m.on) return t("On: the model starts with the next request");+ if (m.installed) return t("Off. The model is downloaded ({size})", { size: fmtBytes(m.size) });+ return t("Names, addresses and passwords no rule can find, found by a model that runs on this computer. Turning it on downloads {size} once", { size: fmtBytes(m.size) });+}+function renderOTel(s, keep) {const page = $("#otelList");page.replaceChildren();diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 7d11c7fee..f9ecf36de 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1152,6 +1152,21 @@ const I18N = {"The bucket in s3://, gs://, oss://, cos:// and storage URLs; the path in it stays": "s3://、gs://、oss://、cos:// 和存储链接里的桶名;桶内路径不动","Email addresses and account names on Usage and Routing are blurred, for a screenshot to share": "用量和路由页上的邮箱和账号名会被模糊处理,方便截图分享","Masked words": "脱敏词",+ "Find with a local model": "用本地模型查找",+ "Delete model": "删除模型",+ "Delete the model?": "删除模型?",+ "Turning it on again downloads {size} again.": "再次打开时会重新下载 {size}。",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer": "规则找不到的姓名、地址和密码,由在这台电脑上运行的模型找出",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer. Turning it on downloads {size} once": "规则找不到的姓名、地址和密码,由在这台电脑上运行的模型找出。开启后会下载一次 {size}",+ "Not available on this system yet": "此系统暂不支持",+ "Downloading the model: {done} of {total}": "正在下载模型:{done} / {total}",+ "The download stopped: {error}": "下载已停止:{error}",+ "The model didn't answer, so requests are held back: {error}": "模型没有响应,请求已暂缓发送:{error}",+ "On, on the GPU ({device})": "已开启,运行在 GPU({device})",+ "On, on the CPU: the GPU failed ({error})": "已开启,运行在 CPU:GPU 出错({error})",+ "On, on the CPU": "已开启,运行在 CPU",+ "On: the model starts with the next request": "已开启:模型会在下一个请求时启动",+ "Off. The model is downloaded ({size})": "已关闭。模型已下载({size})","Your own words to keep from vendors, separated by commas": "不想让模型厂商看到的词,用逗号分隔","names, codenames, hosts": "人名、代号、主机名","Masking rules": "自定义脱敏规则",@@ -4868,6 +4883,21 @@ const I18N = {"The bucket in s3://, gs://, oss://, cos:// and storage URLs; the path in it stays": "s3://、gs://、oss://、cos:// 和儲存連結裡的桶名;桶內路徑不動","Email addresses and account names on Usage and Routing are blurred, for a screenshot to share": "用量和路由頁上的郵箱和帳號名會被模糊處理,方便截圖分享","Masked words": "脫敏詞",+ "Find with a local model": "用本機模型查找",+ "Delete model": "刪除模型",+ "Delete the model?": "刪除模型?",+ "Turning it on again downloads {size} again.": "再次開啟時會重新下載 {size}。",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer": "規則找不到的姓名、地址和密碼,由在這台電腦上執行的模型找出",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer. Turning it on downloads {size} once": "規則找不到的姓名、地址和密碼,由在這台電腦上執行的模型找出。開啟後會下載一次 {size}",+ "Not available on this system yet": "此系統暫不支援",+ "Downloading the model: {done} of {total}": "正在下載模型:{done} / {total}",+ "The download stopped: {error}": "下載已停止:{error}",+ "The model didn't answer, so requests are held back: {error}": "模型沒有回應,請求已暫緩送出:{error}",+ "On, on the GPU ({device})": "已開啟,執行於 GPU({device})",+ "On, on the CPU: the GPU failed ({error})": "已開啟,執行於 CPU:GPU 出錯({error})",+ "On, on the CPU": "已開啟,執行於 CPU",+ "On: the model starts with the next request": "已開啟:模型會在下一個請求時啟動",+ "Off. The model is downloaded ({size})": "已關閉。模型已下載({size})","Your own words to keep from vendors, separated by commas": "不想讓模型廠商看到的詞,用逗號分隔","names, codenames, hosts": "人名、代號、主機名","Masking rules": "自定義脫敏規則",@@ -8554,6 +8584,21 @@ const I18N = {"The bucket in s3://, gs://, oss://, cos:// and storage URLs; the path in it stays": "s3://、gs://、oss://、cos:// やストレージ URL のバケット名。中のパスはそのまま","Email addresses and account names on Usage and Routing are blurred, for a screenshot to share": "使用量とルーティングのページのメールアドレスとアカウント名をぼかします(スクリーンショットの共有用)","Masked words": "マスクする語",+ "Find with a local model": "ローカルモデルで検出",+ "Delete model": "モデルを削除",+ "Delete the model?": "モデルを削除しますか?",+ "Turning it on again downloads {size} again.": "もう一度オンにすると {size} を再びダウンロードします。",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer": "ルールでは見つからない名前・住所・パスワードを、このコンピュータで動くモデルが見つけます",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer. Turning it on downloads {size} once": "ルールでは見つからない名前・住所・パスワードを、このコンピュータで動くモデルが見つけます。オンにすると {size} を一度ダウンロードします",+ "Not available on this system yet": "このシステムではまだ使えません",+ "Downloading the model: {done} of {total}": "モデルをダウンロード中:{done} / {total}",+ "The download stopped: {error}": "ダウンロードが止まりました:{error}",+ "The model didn't answer, so requests are held back: {error}": "モデルが応答しないため、リクエストを保留しています:{error}",+ "On, on the GPU ({device})": "オン、GPU で実行中({device})",+ "On, on the CPU: the GPU failed ({error})": "オン、CPU で実行中:GPU が失敗しました({error})",+ "On, on the CPU": "オン、CPU で実行中",+ "On: the model starts with the next request": "オン:次のリクエストでモデルが起動します",+ "Off. The model is downloaded ({size})": "オフ。モデルはダウンロード済み({size})","Your own words to keep from vendors, separated by commas": "ベンダーに見せたくない語(カンマ区切り)","names, codenames, hosts": "人名、コードネーム、ホスト名","Masking rules": "マスクルール",@@ -12270,6 +12315,21 @@ const I18N = {"The bucket in s3://, gs://, oss://, cos:// and storage URLs; the path in it stays": "Der Bucket in s3://, gs://, oss://, cos:// und Speicher-URLs; der Pfad darin bleibt","Email addresses and account names on Usage and Routing are blurred, for a screenshot to share": "E-Mail-Adressen und Kontonamen auf „Nutzung“ und „Routing“ werden unscharf dargestellt, für einen Screenshot zum Teilen","Masked words": "Maskierte Wörter",+ "Find with a local model": "Mit lokalem Modell finden",+ "Delete model": "Modell löschen",+ "Delete the model?": "Modell löschen?",+ "Turning it on again downloads {size} again.": "Wieder eingeschaltet, werden erneut {size} geladen.",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer": "Namen, Adressen und Passwörter, die keine Regel findet, gefunden von einem Modell auf diesem Computer",+ "Names, addresses and passwords no rule can find, found by a model that runs on this computer. Turning it on downloads {size} once": "Namen, Adressen und Passwörter, die keine Regel findet, gefunden von einem Modell auf diesem Computer. Einschalten lädt einmalig {size}",+ "Not available on this system yet": "Auf diesem System noch nicht verfügbar",+ "Downloading the model: {done} of {total}": "Modell wird geladen: {done} von {total}",+ "The download stopped: {error}": "Download angehalten: {error}",+ "The model didn't answer, so requests are held back: {error}": "Das Modell antwortet nicht, Anfragen werden zurückgehalten: {error}",+ "On, on the GPU ({device})": "An, auf der GPU ({device})",+ "On, on the CPU: the GPU failed ({error})": "An, auf der CPU: die GPU ist ausgefallen ({error})",+ "On, on the CPU": "An, auf der CPU",+ "On: the model starts with the next request": "An: das Modell startet mit der nächsten Anfrage",+ "Off. The model is downloaded ({size})": "Aus. Das Modell ist geladen ({size})","Your own words to keep from vendors, separated by commas": "Eigene Wörter, die Anbieter nicht sehen sollen, durch Kommas getrennt","names, codenames, hosts": "Namen, Codenamen, Hosts","Masking rules": "Maskierungsregeln",diff --git a/internal/gui/privacymodel.go b/internal/gui/privacymodel.gonew file mode 100644index 000000000..538adc4ac--- /dev/null+++ b/internal/gui/privacymodel.go@@ -0,0 +1,76 @@+package gui++import (+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/yetone/magpie/internal/pii"+ "github.com/yetone/magpie/internal/settings"+)++// privacyModelJSON is Settings → Privacy's local masking model: whether it+// is on, and the model's own status (downloaded, downloading, where it+// runs).+type privacyModelJSON struct {+ On bool `json:"on"`+ pii.Status+}++func privacyModelState() privacyModelJSON {+ return privacyModelJSON{On: settings.Load().RedactModel, Status: pii.Now()}+}++// privacyModelRoutes: GET /api/privacy-model is its state; POST with+// {"do": "on" | "off" | "cancel" | "remove"} turns it on (downloading the+// model first, and saving it on once that is done), off (a download is+// stopped, pf-serve ended, the model kept), stops a download, or turns it off and deletes+// the model.+func privacyModelRoutes(mux *http.ServeMux) {+ mux.HandleFunc("GET /api/privacy-model", func(rw http.ResponseWriter, r *http.Request) {+ writeJSON(rw, privacyModelState())+ })+ mux.HandleFunc("POST /api/privacy-model", func(rw http.ResponseWriter, r *http.Request) {+ var in struct {+ Do string `json:"do"`+ }+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil {+ fail(rw, err)+ return+ }+ var err error+ switch in.Do {+ case "on":+ if pii.Installed() {+ if err = settings.SetRedactModel(true); err == nil {+ pii.Warm()+ }+ break+ }+ // on only once the model is on disk: a request in between is+ // masked by the rules, as before, and not held back+ err = pii.Download(func() {+ if settings.SetRedactModel(true) == nil {+ pii.Warm()+ }+ })+ case "off":+ pii.Cancel()+ err = settings.SetRedactModel(false)+ pii.Stop()+ case "cancel":+ pii.Cancel()+ case "remove":+ if err = settings.SetRedactModel(false); err == nil {+ err = pii.Remove()+ }+ default:+ err = fmt.Errorf("do is on, off, cancel or remove, not %q", in.Do)+ }+ if err != nil {+ fail(rw, err)+ return+ }+ writeJSON(rw, privacyModelState())+ })+}diff --git a/internal/gui/privacymodel_test.go b/internal/gui/privacymodel_test.gonew file mode 100644index 000000000..05575602e--- /dev/null+++ b/internal/gui/privacymodel_test.go@@ -0,0 +1,69 @@+package gui++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/pii"+ "github.com/yetone/magpie/internal/settings"+)++// The local masking model is on only once it is on disk: turned on where+// it can't be downloaded, nothing is saved; the Settings page's own save+// never turns it on or off; and off is saved at once.+func TestPrivacyModelOnlyOnOnceDownloaded(t *testing.T) {+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("USERPROFILE", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))+ srv := Handler(webHost{func() {}}, nil)+ do := func(method, path, body string) *httptest.ResponseRecorder {+ rec := httptest.NewRecorder()+ srv.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))+ return rec+ }+ var st privacyModelJSON+ if rec := do("GET", "/api/privacy-model", ""); rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil {+ t.Fatalf("state: %d %s", rec.Code, rec.Body)+ }+ if st.On || st.Installed || st.Size == 0 {+ t.Fatalf("state %+v", st)+ }+ if !pii.Supported() {+ if rec := do("POST", "/api/privacy-model", `{"do":"on"}`); rec.Code == http.StatusOK {+ t.Fatalf("on where it can't run: %d %s", rec.Code, rec.Body)+ }+ if settings.Load().RedactModel {+ t.Fatal("saved on with no model")+ }+ }+ if rec := do("POST", "/api/privacy-model", `{"do":"on!"}`); rec.Code == http.StatusOK {+ t.Fatalf("a bad do: %d", rec.Code)+ }+ if rec := do("POST", "/api/settings", `{"theme":"dark","lang":"en","redactModel":true}`); rec.Code != http.StatusOK {+ t.Fatalf("settings save: %d %s", rec.Code, rec.Body)+ }+ if settings.Load().RedactModel {+ t.Fatal("the Settings page's save turned it on")+ }+ if err := settings.SetRedactModel(true); err != nil {+ t.Fatal(err)+ }+ if rec := do("POST", "/api/settings", `{"theme":"dark","lang":"en"}`); rec.Code != http.StatusOK {+ t.Fatalf("settings save: %d %s", rec.Code, rec.Body)+ }+ if !settings.Load().RedactModel {+ t.Fatal("the Settings page's save turned it off")+ }+ if rec := do("POST", "/api/privacy-model", `{"do":"off"}`); rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil || st.On {+ t.Fatalf("off: %d %s", rec.Code, rec.Body)+ }+ if settings.Load().RedactModel {+ t.Fatal("off not saved")+ }+}diff --git a/internal/gui/tests/privacy-model.test.cjs b/internal/gui/tests/privacy-model.test.cjsnew file mode 100644index 000000000..389e56547--- /dev/null+++ b/internal/gui/tests/privacy-model.test.cjs@@ -0,0 +1,165 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// Settings → Privacy's local masking model (#1977): a row under the masking+// switches, there while either is on. On downloads the model, its progress+// shown and a Cancel beside it; once it is on, the row says where it runs.+// Off, a downloaded model can be deleted, after asking. Its words are shown+// in full, in every language, in a wide window and a narrow one, and a+// click moves nothing.+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 } = require("./reader.cjs");++const assets = path.resolve(__dirname, "../assets");+const size = 1637572192;+const words = {+ en: { name: "Find with a local model", on: "On", gpu: "On, on the GPU (MTL0)" },+ zh: { name: "用本地模型查找", on: "开启", gpu: "已开启,运行在 GPU(MTL0)" },+ "zh-TW": { name: "用本機模型查找", on: "開啟", gpu: "已開啟,執行於 GPU(MTL0)" },+ ja: { name: "ローカルモデルで検出", on: "オン", gpu: "オン、GPU で実行中(MTL0)" },+ de: { name: "Mit lokalem Modell finden", on: "An", gpu: "An, auf der GPU (MTL0)" },+};++// model is the page's /api/privacy-model: a POST is recorded and moves it+// along, as magpie would (downloading, then on and running on the GPU)+function serve(lang, masking, model, posts) {+ const settings = () => ({ lang, theme: "light", redact: masking, redactPersonal: false });+ const state = { agents: [], profiles: [], settings: settings() };+ return async (r) => {+ const url = new URL(r.request().url());+ const json = (data) => r.fulfill({ json: data });+ if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json(state);+ if (url.pathname === "/api/settings") return json(settings());+ if (url.pathname === "/api/privacy-model") {+ if (r.request().method() === "POST") {+ const { do: doing } = JSON.parse(r.request().postData());+ posts.push(doing);+ if (doing === "on") Object.assign(model, { downloading: true, done: 0, total: size, ticks: 0 });+ if (doing === "cancel") Object.assign(model, { downloading: false, done: 0 });+ if (doing === "remove") Object.assign(model, { installed: false, on: false });+ } else if (model.downloading && ++model.ticks >= 2) {+ Object.assign(model, { downloading: false, installed: true, on: true, running: true, gpu: true, device: "MTL0" });+ } else if (model.downloading) {+ model.done = Math.round(size * 0.4);+ }+ const { ticks, ...out } = model;+ return json(out);+ }+ if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });+ 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 r.fulfill({ body: await fs.readFile(file), contentType });+ };+}++async function open(engine, lang, width, masking, model, posts) {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage();+ page.setDefaultTimeout(8000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang, masking, model, posts));+ await watchSettingsReads(page);+ await page.goto("http://magpie.test/?view=settings&tab=privacy");+ await page.locator("#redactList .row").first().waitFor();+ await settingsDrawn(page);+ return { browser, page, errors };+}++// what the row shows: its words, whether they are cut, and that it is+// inside the list+const look = (page) => page.evaluate(() => {+ const r = document.querySelector("#privacyModelRow"), list = document.querySelector("#redactList").getBoundingClientRect();+ const sub = r.querySelector(".sub"), b = r.getBoundingClientRect(), v = r.querySelector(".val").getBoundingClientRect();+ return {+ name: r.querySelector(".name").textContent, sub: sub.textContent,+ on: r.querySelector(".segs .opt.on")?.textContent, buttons: [...r.querySelectorAll("button.text")].map((x) => x.textContent),+ cut: sub.scrollWidth > sub.clientWidth + 1 || sub.scrollHeight > sub.clientHeight + 1,+ inside: b.left >= list.left - 1 && b.right <= list.right + 1 && v.right <= b.right + 1,+ wide: document.documentElement.scrollWidth > document.documentElement.clientWidth,+ };+});++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of Object.keys(words)) {+ for (const width of [1100, 640]) {+ const w = words[lang];+ test(`${engine} ${lang} ${width}px: turned on, the model downloads and says where it runs`, async (t) => {+ const posts = [], model = { supported: true, installed: false, size };+ const { browser, page, errors } = await open(engine, lang, width, true, model, posts);+ t.after(() => browser.close());+ const row = page.locator("#privacyModelRow");+ await row.locator(".segs").waitFor();+ let m = await look(page);+ assert.equal(m.name, w.name);+ assert(m.sub.includes("1.6 GB"), `says what it downloads: ${m.sub}`);+ if (lang !== "en") assert(!/no rule can find|Turning it on/.test(m.sub), `translated: ${m.sub}`);+ assert(!m.cut && m.inside && !m.wide, `shown in full and inside: ${JSON.stringify(m)}`);++ await page.mouse.move(width / 2, 300);+ for (let i = 0; i < 20 && (await row.boundingBox()).y > 900; i++) {+ await page.mouse.wheel(0, 200);+ await page.waitForTimeout(80);+ }+ await page.waitForTimeout(300);+ const before = await page.evaluate(() => [scrollX, scrollY, document.querySelector("#view-settings").scrollTop]);+ const b = await row.locator(".segs .opt", { hasText: w.on }).boundingBox();+ await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);+ // downloading: its progress, and a Cancel+ await page.waitForFunction(() => /655 MB/.test(document.querySelector("#privacyModelRow .sub").textContent));+ m = await look(page);+ assert.equal(m.buttons.length, 1, "a Cancel while it downloads");+ assert.equal(m.on, w.on);+ assert(!m.cut && m.inside && !m.wide, `shown in full and inside: ${JSON.stringify(m)}`);+ // then on, on the GPU+ await page.waitForFunction((want) => document.querySelector("#privacyModelRow .sub").textContent === want, w.gpu);+ m = await look(page);+ assert.deepEqual(m.buttons, [], "nothing to cancel or delete while it is on");+ assert(!m.cut && m.inside && !m.wide, `shown in full and inside: ${JSON.stringify(m)}`);+ assert.deepEqual(posts, ["on"]);+ assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.querySelector("#view-settings").scrollTop]), before, "the click moved nothing");+ assert.deepEqual(errors, []);+ });+ }+ }++ test(`${engine}: a download is cancelled, and a downloaded model deleted after asking`, async (t) => {+ const posts = [], model = { supported: true, installed: false, size };+ const { browser, page, errors } = await open(engine, "en", 1100, true, model, posts);+ t.after(() => browser.close());+ const row = page.locator("#privacyModelRow");+ await row.locator(".segs .opt", { hasText: "On" }).click();+ await row.locator("button.text", { hasText: "Cancel" }).click();+ await page.waitForFunction(() => document.querySelector("#privacyModelRow .segs .opt.on")?.textContent === "Off");+ assert.deepEqual(posts, ["on", "cancel"]);++ Object.assign(model, { installed: true, on: false });+ await page.reload();+ await row.locator("button.text", { hasText: "Delete model" }).click();+ await page.locator("dialog.action-confirm button", { hasText: /^Delete$/ }).click();+ await page.waitForFunction(() => !document.querySelector("#privacyModelRow button.text"));+ assert.deepEqual(posts, ["on", "cancel", "remove"]);+ assert.match((await look(page)).sub, /downloads 1\.6 GB once/);+ assert.deepEqual(errors, []);+ });++ test(`${engine}: no model row while nothing is masked, and none to turn on where it can't run`, async (t) => {+ const { browser, page, errors } = await open(engine, "en", 1100, false, { supported: true, size }, []);+ t.after(() => browser.close());+ await page.locator("#redactList .row", { hasText: "Mask personal data" }).waitFor();+ assert.equal(await page.locator("#privacyModelRow").count(), 0);+ await browser.close();++ const two = await open(engine, "en", 1100, true, { supported: false, size }, []);+ t.after(() => two.browser.close());+ await two.page.waitForFunction(() => document.querySelector("#privacyModelRow .sub")?.textContent === "Not available on this system yet");+ assert.equal(await two.page.locator("#privacyModelRow .segs").count(), 0);+ assert.deepEqual([...errors, ...two.errors], []);+ });+}diff --git a/internal/pii/pii.go b/internal/pii/pii.goindex b5a66d4ca..f04be7a95 100644--- a/internal/pii/pii.go+++ b/internal/pii/pii.go@@ -40,7 +40,13 @@ var (var (serveTag = "pf-v1"serveBase = "https://github.com/yetone/magpie/releases/download/"- serveSHA = map[string]string{}+ serveSHA = map[string]string{+ "darwin-amd64": "7d5512ed24ff865bb0e84009b0adecd3addf0444891990cbc78634d78390c607",+ "darwin-arm64": "07eb79dd1d74a6dc8e2e59eefed1094a4c1dafa27051343fac65d6c2172617f0",+ "linux-amd64": "b172f39b2b5446cb92ef14f996b65157f5e1c0e4e673ee9c61a0214cc67c78af",+ "linux-arm64": "7a344515e35676d0da21b448c6c4bc49de7cf34f8f28604c6889c092ae963961",+ "windows-amd64": "dd06aa4e656cbebff348ad3fdfd66eca5f899b244dff65235d47a2c878b49c6c",+ })// target is this system's name in serveSHA.