diff --git a/internal/gui/assets/plugins/redact/i18n.js b/internal/gui/assets/plugins/redact/i18n.js index 40251f147..7b9e7c6d2 100644 --- a/internal/gui/assets/plugins/redact/i18n.js +++ b/internal/gui/assets/plugins/redact/i18n.js @@ -98,6 +98,15 @@ magpie.strings({ "Your own words to keep from vendors, one on each row": "不想让模型厂商看到的词,每行一个", "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "总是按原样发送的值,整段匹配、不分大小写,每行一个:比如团队邮箱、测试密钥", "Remove {word}": "移除 {word}", + "Paste words, one a line or separated by commas": "粘贴词,每行一个,或用逗号隔开", + "Words to import": "要导入的词", + "New words: {n}": "新词:{n}", + "No new words: each is in the list already": "没有新词:都已在列表里", + "Words added: {n}": "已添加 {n} 个词", + "Words added: {n} · already in the list: {m}": "已添加 {n} 个词 · {m} 个已在列表里", + "Add many words at once, pasted one a line or separated by commas": "一次添加多个词:粘贴进来,每行一个,或用逗号隔开", + "Copy the list, one word a line": "复制整个列表,每行一个词", + "Words copied: {n}": "已复制 {n} 个词", }, "zh-TW": { "Turn on masking": "開啟脫敏", @@ -196,6 +205,15 @@ magpie.strings({ "Your own words to keep from vendors, one on each row": "不想讓模型廠商看到的詞,每行一個", "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "一律照原樣送出的值,整段比對、不分大小寫,每行一個:例如團隊信箱、測試金鑰", "Remove {word}": "移除 {word}", + "Paste words, one a line or separated by commas": "貼上詞,每行一個,或用逗號隔開", + "Words to import": "要匯入的詞", + "New words: {n}": "新詞:{n}", + "No new words: each is in the list already": "沒有新詞:都已在清單裡", + "Words added: {n}": "已新增 {n} 個詞", + "Words added: {n} · already in the list: {m}": "已新增 {n} 個詞 · {m} 個已在清單裡", + "Add many words at once, pasted one a line or separated by commas": "一次新增多個詞:貼上進來,每行一個,或用逗號隔開", + "Copy the list, one word a line": "複製整個清單,每行一個詞", + "Words copied: {n}": "已複製 {n} 個詞", }, ja: { "Turn on masking": "マスクをオンにする", @@ -294,6 +312,15 @@ magpie.strings({ "Your own words to keep from vendors, one on each row": "ベンダーに見せたくない語(1 行に 1 つ)", "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "常にそのまま送る値。全体一致、大文字小文字を区別せず、1 行に 1 つ:チームのアドレス、テスト用キーなど", "Remove {word}": "{word} を削除", + "Paste words, one a line or separated by commas": "語を貼り付け(1 行に 1 つ、またはカンマ区切り)", + "Words to import": "インポートする語", + "New words: {n}": "新しい語:{n}", + "No new words: each is in the list already": "新しい語はありません:すべてリストにあります", + "Words added: {n}": "{n} 語を追加しました", + "Words added: {n} · already in the list: {m}": "{n} 語を追加しました · {m} 語は既にリストにあります", + "Add many words at once, pasted one a line or separated by commas": "複数の語をまとめて追加:1 行に 1 つ、またはカンマ区切りで貼り付け", + "Copy the list, one word a line": "リストをコピー(1 行に 1 語)", + "Words copied: {n}": "{n} 語をコピーしました", }, de: { "Turn on masking": "Maskierung einschalten", @@ -392,5 +419,14 @@ magpie.strings({ "Your own words to keep from vendors, one on each row": "Eigene Wörter, die Anbieter nicht sehen sollen, eines pro Zeile", "Values that always go as written, each whole and in any case, one on each row: a team address, a test key": "Werte, die immer unverändert gehen, jeweils ganz und ohne Groß-/Kleinschreibung, einer pro Zeile: eine Team-Adresse, ein Testschlüssel", "Remove {word}": "{word} entfernen", + "Paste words, one a line or separated by commas": "Wörter einfügen, eines pro Zeile oder durch Kommas getrennt", + "Words to import": "Zu importierende Wörter", + "New words: {n}": "Neue Wörter: {n}", + "No new words: each is in the list already": "Keine neuen Wörter: alle stehen schon in der Liste", + "Words added: {n}": "Wörter hinzugefügt: {n}", + "Words added: {n} · already in the list: {m}": "Wörter hinzugefügt: {n} · schon in der Liste: {m}", + "Add many words at once, pasted one a line or separated by commas": "Viele Wörter auf einmal hinzufügen, eingefügt eines pro Zeile oder durch Kommas getrennt", + "Copy the list, one word a line": "Die Liste kopieren, ein Wort pro Zeile", + "Words copied: {n}": "Wörter kopiert: {n}", }, }); diff --git a/internal/gui/assets/plugins/redact/redact.css b/internal/gui/assets/plugins/redact/redact.css index e5caf4deb..fba52a2e0 100644 --- a/internal/gui/assets/plugins/redact/redact.css +++ b/internal/gui/assets/plugins/redact/redact.css @@ -375,3 +375,11 @@ body.window .msk-onebar::before { inset: -6px calc(var(--bar, 0px) - 16px) -6px .word-line input.words { flex: 1 1 auto; width: auto; min-width: 0; } .word-line .word-x { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0; border-radius: 6px; font-size: 15px; color: var(--muted); } .word-line.word-new .text { flex: none; } +/* Import… under a word list: many words pasted at once, a word a line or + split at commas (wordList in settings.js) */ +.word-import { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.word-import textarea.word-import-in { width: 100%; box-sizing: border-box; resize: vertical; min-height: 84px; font: inherit; font-size: 12px; line-height: 1.5; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); color: var(--fg); } +#redactList textarea.word-import-in.words-hidden { -webkit-text-security: disc; } +.word-import-bar { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; min-width: 0; } +.word-import-bar .grow { flex: 1; } +.word-import-count { min-width: 0; } diff --git a/internal/gui/assets/plugins/redact/settings.js b/internal/gui/assets/plugins/redact/settings.js index d3367e55b..258f2db49 100644 --- a/internal/gui/assets/plugins/redact/settings.js +++ b/internal/gui/assets/plugins/redact/settings.js @@ -48,14 +48,20 @@ function redactRouteRow(s) { // it holds. let wordsRedrawing = false; const splitWords = (v) => v.split(/[,,\n]/).map((w) => w.trim()).filter(Boolean); -function wordList(key, list, ph, label, save) { +// Import… takes many words at once (acmilan_ on Discord: adding them one +// by one was slow), pasted a word a line or split at commas; a word the +// list has, or one pasted twice, is passed over, and the status says how +// many were added. The box open, and what it holds, outlive a redraw. +// Copy puts the list on the clipboard a word a line, as Import takes it. +let wordImport = null; +function wordList(key, list, ph, label, save, savedNow) { const box = el("div", "word-list"); box.dataset.list = key; let cur = list.map((w) => ({ w })); const put = (next) => { if (next.map((o) => o.w).join("\n") === cur.map((o) => o.w).join("\n")) return; cur = next; - save(next.map((o) => o.w)); + return save(next.map((o) => o.w)); }; const keys = (i, done, back) => { i.onkeydown = (e) => { @@ -103,6 +109,71 @@ function wordList(key, list, ph, label, save) { go.onclick = () => { take(); add.focus(NO_SCROLL); }; line.append(add, go); box.append(line); + + const imp = el("div", "word-import"); + imp.hidden = wordImport?.key !== key; + const area = el("textarea", "word-import-in"); + area.rows = 5; + area.spellcheck = false; + area.value = wordImport?.key === key ? wordImport.text : ""; + area.placeholder = t("Paste words, one a line or separated by commas"); + area.setAttribute("aria-label", t("Words to import")); + const count = el("span", "hint word-import-count"); + const bring = el("button", "text primary", t("Import")); + bring.type = "button"; + const fresh = () => { + const have = new Set(cur.map((o) => o.w)); + return [...new Set(splitWords(area.value))].filter((w) => !have.has(w)); + }; + const counted = () => { + const n = fresh().length; + count.textContent = area.value.trim() ? (n ? t("New words: {n}", { n }) : t("No new words: each is in the list already")) : ""; + bring.disabled = !n; + }; + const close = () => { wordImport = null; area.value = ""; imp.hidden = true; counted(); }; + area.oninput = () => { wordImport = { key, text: area.value }; counted(); }; + const bringIn = async () => { + const pasted = new Set(splitWords(area.value)), add = fresh(); + if (!add.length) return; + close(); + await put([...cur, ...add.map((w) => ({ w }))]); + // said only once the words are saved: a failed save has said why + const now = new Set(savedNow?.() || []); + if (!add.every((w) => now.has(w))) return; + const had = pasted.size - add.length; + status(had ? t("Words added: {n} · already in the list: {m}", { n: add.length, m: had }) : t("Words added: {n}", { n: add.length }), "ok"); + }; + area.onkeydown = (e) => { + e.stopPropagation(); + if (e.isComposing || e.keyCode === 229) return; + if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); bringIn(); } + else if (e.key === "Escape") close(); + }; + bring.onclick = bringIn; + const no = el("button", "text", t("Cancel")); + no.type = "button"; + no.onclick = close; + const bar = el("div", "word-import-bar"); + bar.append(count, el("span", "grow"), no, bring); + imp.append(area, bar); + counted(); + box.append(imp); + + const open = el("button", "text word-import-open", t("Import…")); + open.type = "button"; + open.title = t("Add many words at once, pasted one a line or separated by commas"); + open.onclick = () => { + if (!imp.hidden) return void close(); + wordImport = { key, text: "" }; + imp.hidden = false; + area.focus(NO_SCROLL); + }; + const out = el("button", "text word-copy", t("Copy")); + out.type = "button"; + out.title = t("Copy the list, one word a line"); + out.disabled = !cur.length; + out.onclick = () => copy(cur.map((o) => o.w).join("\n"), "", out, t("Words copied: {n}", { n: cur.length })); + box.tools = [open, out]; return box; } // wordRow: the row a wordList sits under, its words above and the list @@ -141,7 +212,8 @@ function redactWordsHidden(r) { const eye = el("button", "text redact-eye"); eye.type = "button"; const set = () => { - for (const i of r.querySelectorAll("input.words")) { + for (const i of r.querySelectorAll("input.words, textarea.word-import-in")) { + if (i.tagName === "TEXTAREA") { if (dots) i.classList.toggle("words-hidden", !redactWordsShown); continue; } if (dots) i.classList.toggle("words-hidden", !redactWordsShown); else i.type = redactWordsShown ? "text" : "password"; } @@ -158,16 +230,18 @@ function redactWordsHidden(r) { const f = wordFocusOf(); wordsRedrawing = true; try { draw(s, keep); } finally { wordsRedrawing = false; } - const words = wordRow(t("Masked words"), t("Your own words to keep from vendors, one on each row"), - wordList("words", s.redactWords || [], t("names, codenames, hosts"), t("Masked words"), (redactWords) => savePrefs({ ...keep, redactWords }))); + const wl = wordList("words", s.redactWords || [], t("names, codenames, hosts"), t("Masked words"), (redactWords) => savePrefs({ ...keep, redactWords }), () => prefs?.redactWords); + const words = wordRow(t("Masked words"), t("Your own words to keep from vendors, one on each row"), wl, ...wl.tools); const at = $("#redactWordsAnyCaseRow"); if (at) at.before(words); else $("#redactList").append(words); redactWordsHidden(words); const acts = $("#maskActList"); - if (acts) acts.append(wordRow(t("Never mask"), t("Values that always go as written, each whole and in any case, one on each row: a team address, a test key"), - wordList("allow", s.redactAllow || [], t("ops@company.com, build-01"), t("Never mask"), (allow) => writingPrefs(api("settings/redact-allow", { allow })) + if (acts) { + const al = wordList("allow", s.redactAllow || [], t("ops@company.com, build-01"), t("Never mask"), (allow) => writingPrefs(api("settings/redact-allow", { allow })) .then((ns) => { prefs = ns; renderSettings(); status(t("Saved"), "ok", 1500); }) - .catch(settingsErr)))); + .catch(settingsErr), () => prefs?.redactAllow); + acts.append(wordRow(t("Never mask"), t("Values that always go as written, each whole and in any case, one on each row: a team address, a test key"), al, ...al.tools)); + } wordFocusBack(f); if (s.redact || s.redactPersonal || (s.redactWords || []).length) redactRouteRow(s); }; diff --git a/internal/gui/tests/redact-words-import.test.cjs b/internal/gui/tests/redact-words-import.test.cjs new file mode 100644 index 000000000..036df96ef --- /dev/null +++ b/internal/gui/tests/redact-words-import.test.cjs @@ -0,0 +1,186 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Privacy's Masked words and Never mask take many words at once +// (acmilan_ on Discord: adding them one by one was slow). Import… opens a +// box under the list; what is pasted there, a word a line or split at +// commas, is added after the words the list has, a word already in it or +// pasted twice passed over, and the status says how many were added. A +// redraw keeps the box and what it holds; Escape and Cancel close it and +// save nothing; a save that fails says no count. Copy puts the list on the +// clipboard a word a line. Every language, Chromium and WebKit, narrow. +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 { reach, watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +function serve(lang, box) { + return async (r) => { + const req = r.request(), url = new URL(req.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({ agents: [], profiles: [], settings: box.settings }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { + if (box.fail) return r.fulfill({ status: 500, contentType: "text/plain", body: "disk full" }); + box.settings = JSON.parse(req.postData()); + box.saved.push(box.settings.redactWords); + } + return json(box.settings); + } + if (url.pathname === "/api/settings/redact-allow") { + const b = req.postDataJSON(); + box.allowed.push(b.allow); + box.settings = { ...box.settings, redactAllow: b.allow }; + return json(box.settings); + } + if (url.pathname === "/api/copy") { + box.copied.push(req.postDataJSON().text); + return json({}); + } + 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)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +const ROW = (key) => `.row:has(> .word-list[data-list="${key}"])`; +const LIST = (key) => `.word-list[data-list="${key}"]`; +const words = (page, key) => page.evaluate((sel) => [...document.querySelectorAll(`${sel} input[data-word]`)].map((i) => i.dataset.word), LIST(key)); +const drawn = (page, key, want) => page.waitForFunction(([sel, want]) => + JSON.stringify([...document.querySelectorAll(`${sel} input[data-word]`)].map((i) => i.dataset.word)) === want, [LIST(key), JSON.stringify(want)], { timeout: 5000 }); +const until = async (ok, what) => { + for (let n = 0; n < 100 && !ok(); n++) await new Promise((r) => setTimeout(r, 50)); + assert(ok(), what); +}; +// the window's own word for it +const said = (page, s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]); +// nothing in the list's row past its section's edge, and no sideways scroll +const fits = (page, key) => page.evaluate((sel) => { + const l = document.querySelector(sel).parentElement.getBoundingClientRect(); + const over = [...document.querySelectorAll(`${sel} input, ${sel} button, ${sel} textarea, ${sel} .hint`)] + .filter((n) => n.getClientRects().length).filter((n) => { const b = n.getBoundingClientRect(); return b.left < l.left - 1 || b.right > l.right + 1; }) + .map((n) => n.className); + return { over, page: document.documentElement.scrollWidth > document.documentElement.clientWidth }; +}, ROW(key)); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang} 400px: masked words and never-mask values are imported in bulk and copied out`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 400, height: 1400 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + const box = { saved: [], allowed: [], copied: [], fail: false, + settings: { lang, theme: "light", redact: true, redactPersonal: false, redactWords: ["Nightjar", "百度"], redactAllow: ["ops@company.com"] } }; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, box)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=privacy"); + await page.locator(LIST("words")).waitFor(); + await settingsDrawn(page); + + // closed until asked for, and nothing native + const area = page.locator(`${LIST("words")} textarea.word-import-in`); + assert.equal(await area.isVisible(), false, "the import box is closed at first"); + assert.equal(await page.locator(`${ROW("words")} select`).count(), 0); + const open = page.locator(`${ROW("words")} .word-import-open`); + assert.equal((await open.textContent()).trim(), await said(page, "Import…")); + await reach(page, open); + await open.click(); + await page.waitForFunction((sel) => document.activeElement?.matches(`${sel} textarea.word-import-in`), LIST("words")); + assert.deepEqual(await fits(page, "words"), { over: [], page: false }, "the open box fits a narrow window"); + + // pasted: lines, commas (either width), blanks, a word twice and two + // the list has; the count is of the new ones + await area.fill("Nightjar\nKestrel, Osprey,百度\n\n Kestrel \nops.example.com\n"); + const count = page.locator(`${LIST("words")} .word-import-count`); + assert.equal(await count.textContent(), await said(page, "New words: {n}", { n: 3 })); + if (lang === "en") assert.equal(await count.textContent(), "New words: 3"); + + // a redraw keeps the box open with what it holds + await page.evaluate(() => renderSettings()); + await page.locator(`${LIST("words")} textarea.word-import-in`).waitFor({ state: "visible" }); + assert.equal(await area.inputValue(), "Nightjar\nKestrel, Osprey,百度\n\n Kestrel \nops.example.com\n"); + assert.equal(box.saved.length, 0, "typing in the box saves nothing"); + + const go = page.locator(`${LIST("words")} .word-import-bar button.primary`); + await reach(page, go); + await go.click(); + const five = ["Nightjar", "百度", "Kestrel", "Osprey", "ops.example.com"]; + await until(() => JSON.stringify(box.saved.at(-1)) === JSON.stringify(five), `saved ${JSON.stringify(box.saved)}`); + assert.equal(box.saved.length, 1, "one save for the whole import"); + await drawn(page, "words", five); + const done = await said(page, "Words added: {n} · already in the list: {m}", { n: 3, m: 2 }); + await page.waitForFunction((want) => document.querySelector("#status").textContent === want, done); + if (lang === "en") assert.equal(done, "Words added: 3 · already in the list: 2"); + assert.equal(await area.isVisible(), false, "the box closes once imported"); + + // only words the list has: nothing to import; Escape closes, saves nothing + await open.click(); + await area.fill("kestrel\nKestrel"); + assert.equal(await count.textContent(), await said(page, "New words: {n}", { n: 1 }), "a word in another case is a word of its own"); + await area.fill("Kestrel, Osprey"); + assert.equal(await count.textContent(), await said(page, "No new words: each is in the list already")); + assert.equal(await go.isDisabled(), true); + await area.press("Escape"); + assert.equal(await area.isVisible(), false); + // and Cancel closes it too, emptied for next time + await open.click(); + await area.fill("Plover"); + await page.locator(`${LIST("words")} .word-import-bar button:not(.primary)`).click(); + assert.equal(await area.isVisible(), false); + await open.click(); + assert.equal(await area.inputValue(), ""); + await area.press("Escape"); + assert.equal(box.saved.length, 1, "closing saves nothing"); + + // a save that fails says no count + box.fail = true; + await open.click(); + await area.fill("Plover"); + await area.press(process.platform === "darwin" ? "Meta+Enter" : "Control+Enter"); + await page.waitForFunction(() => document.querySelector("#status").classList.contains("err")); + assert.notEqual(await page.locator("#status").textContent(), await said(page, "Words added: {n}", { n: 1 })); + box.fail = false; + await drawn(page, "words", five); + + // Copy: the list a word a line, as Import takes it + const copy = page.locator(`${ROW("words")} .word-copy`); + await reach(page, copy); + await copy.click(); + await until(() => box.copied.length === 1, "copied once"); + assert.equal(box.copied[0], five.join("\n")); + await page.waitForFunction((want) => document.querySelector("#status").textContent === want, await said(page, "Words copied: {n}", { n: 5 })); + + // Never mask takes an import the same way + const allowOpen = page.locator(`${ROW("allow")} .word-import-open`); + await reach(page, allowOpen); + await allowOpen.click(); + const allowArea = page.locator(`${LIST("allow")} textarea.word-import-in`); + await allowArea.fill("ops@company.com, build-01\nbuild-02"); + const allowGo = page.locator(`${LIST("allow")} .word-import-bar button.primary`); + await reach(page, allowGo); + await allowGo.click(); + await until(() => box.allowed.length === 1, "never-mask saved once"); + assert.deepEqual(box.allowed[0], ["ops@company.com", "build-01", "build-02"]); + await drawn(page, "allow", ["ops@company.com", "build-01", "build-02"]); + assert.deepEqual(await fits(page, "allow"), { over: [], page: false }); + + // what was saved is drawn again on the next load + await page.reload(); + await page.locator(LIST("words")).waitFor(); + await settingsDrawn(page); + assert.deepEqual(await words(page, "words"), five); + assert.deepEqual(errors, []); + }); + } +}