gui: Settings' search finds what the words are about (canlee886 on X)
canlee886 (X, 2123329450502938656) searched Settings for "可访问性",
"监控" and "自动选择模型" and each said no setting matched: "缺少搜索时
的智能联想". The search only found settings whose text had every word.
What it does now, all in finder.js, in the page, nothing sent anywhere:
- A table of ~30 concepts, each with the words a reader may type in
en, zh, zh-TW, ja and de (accessibility, monitoring, picking a model
by itself, theme, proxy, notifications, startup, privacy, LAN, cost,
quota, hotkey, ...), leading to the English names of the settings it
covers (a setting's English is its data-en in every language). Those
settings are listed with the ones that have the words themselves,
for rows, built-ins and other pages' places alike.
- When nothing has the words: a long run of Chinese or Japanese is read
by its two-character words ("文字大小调整" finds Text size), and a
Latin word over 3 letters may be one edit off ("currancy").
- When no setting has the words themselves but some are related, the
line over the parts says "Settings related to “…”" (start-aligned,
in every language) instead of "No setting matches".
- The finders count first (setFeatsFind/elseFind take a dry flag), so
a search renders once and the view's MutationObserver doesn't loop.
Not done, on purpose: pinyin (a large table, and readers type Chinese
through an IME), a recent-searches list and "did you mean" chips (a
layout that jumps on focus; the owner has said no to UI churn).
Run (WSL magpie-desktop: mote's load was 26 to 34 on 18 cores, mica's
disk is full):
- settings-search-related.test.cjs (new), Chromium and WebKit, en, zh,
zh-TW, ja, de at 560x420, plus magpie web at 390x760: 16 of 16.
Against origin/main 9bf5848c1's assets (SEARCH_ASSETS): 0 of 16, "無
障礙"/"accessibility"/"barrierefreiheit" show no Text size.
- 37 nearby GUI files (settings-*, search-*, find-*, i18n*, menu-scroll,
click-scroll, builtins): 636 pass, 34 fail. The six files with reds,
run again at origin/main 9bf5848c1 and at the change: builtins,
click-scroll, menu-scroll and settings-update-source are red the same
at both (#4120, #4471, #1550); search-key-list/search-keys time out
on one subtest a run, a different one each time, at the change only,
and touch no Settings search: filed as #7194.
- At the rebased head (239da9991): settings-search-related,
settings-search, settings-search-reach, find-anywhere and i18n-keys,
64 of 64; go test ./internal/gui (TestCoreScriptBudget and the rest)
on Windows (xiaomi-gpu), since WSL has no gtk4: TestCoreScriptBudget and
the i18n checks pass; 10 Windows reds, none in assets, all filed
(#6068: TestLodyImportHandoff's %AppData%, TestUpdateThatWontStart,
TestGatewayHeldByAContainer, ...; #7112 TestSetPortServes...).
- Broken by hand: the base-assets run above.
Not tried: the whole GUI suite (WSL and mote were busy with other
sessions' suites; mica has no disk), the real app (only Playwright's
engines, not WebKitGTK or WKWebView; no motion was added).
This commit is contained in:
@@ -4255,6 +4255,8 @@ body:not(.side-nav) #view-settings .set-head.stuck::before { opacity: 1; box-sha
|
||||
.set-searching .set-miss { display: none !important; }
|
||||
.set-searching .set-page::before { content: attr(data-part); display: block; margin: 4px 2px 6px; font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); }
|
||||
.set-none { margin: 18px 2px; font-size: 13px; color: var(--muted); text-align: center; }
|
||||
/* what the words are about, found when nothing has them (finder.js): a line over the parts */
|
||||
.set-none.set-near { margin: 2px 2px 10px; text-align: start; }
|
||||
.set-page > .list:not(:last-child) { margin-bottom: 8px; }
|
||||
/* what the search finds on the other pages (finder.js): a part per page
|
||||
after Settings' own, named by it; the place Open goes to is lit there */
|
||||
|
||||
+151
-29
@@ -7,35 +7,158 @@
|
||||
// search up from any page (app.js findAnywhere). app.js imports this the
|
||||
// first time a search runs, so it weighs nothing on the core.
|
||||
|
||||
// What a search is about (canlee886 on X: "可访问性", "监控" and
|
||||
// "自动选择模型" found nothing, "缺少搜索时的智能联想"). A concept's words
|
||||
// in each language lead to the English names of the settings it covers (a
|
||||
// setting's English is in its data-en in every language), listed with the
|
||||
// settings that have the words themselves. When nothing has them, a long
|
||||
// run of Chinese or Japanese is read by its two-character words and a
|
||||
// Latin word may have a typo, and with no setting that has the words, the
|
||||
// line over the parts says "Settings related to “…”". All of it is here,
|
||||
// in the page: nothing is sent anywhere.
|
||||
// Each line: the words a reader may type (_ joins a phrase's words) | the
|
||||
// names they lead to.
|
||||
const CONCEPTS = [
|
||||
"accessibility a11y 可访问性 无障碍 辅助功能 可訪問性 無障礙 輔助使用 協助工具 アクセシビリティ 見やすさ barrierefrei bedienungshilfe | text size|reduce motion|colorblind|appearance|interface font|code font",
|
||||
"theme dark_mode light_mode darkmode 深色 暗色 夜间 浅色 主题 外观 皮肤 主題 外觀 深色模式 ダーク ライト テーマ 外観 dunkel hell erscheinungsbild | appearance|accent color|background image",
|
||||
"zoom font_size bigger smaller 字体 字號 字号 放大 缩小 缩放 字體 縮放 フォント 拡大 縮小 schrift vergrößern | text size|interface font|code font",
|
||||
"animation 动画 动效 動畫 アニメーション animation | reduce motion|loading bird",
|
||||
"monitor metrics telemetry tracing trace logging grafana prometheus jaeger 监控 监测 遥测 指标 追踪 链路 日志 監控 監測 遙測 追蹤 監視 モニタ テレメトリ トレース überwach metrik | observability|opentelemetry|otel|requests",
|
||||
"auto_model autoselect auto_select auto_switch model_routing smart_routing 自动选择 自动选模型 自动切换 自动路由 智能路由 模型路由 智能选择 自動選擇 自動切換 智慧路由 自動選択 自動切替 モデル選択 modellwahl modellauswahl automatische_auswahl | routing|smart|system one|busy models last",
|
||||
"notify notification alert remind 通知 提醒 告警 预警 提示 警報 預警 アラート リマインド benachrichtig erinner | alert|reminder|bark",
|
||||
"startup launch_at autostart boot 开机 自启 启动 開機 自啟 啟動 起動 自動起動 systemstart | open at login",
|
||||
"vpn socks 代理 翻墙 梯子 科学上网 プロキシ | proxy|proxies",
|
||||
"sleep awake caffeinate 休眠 睡眠 待机 待機 スリープ ruhezustand | prevent sleep",
|
||||
"language locale 语言 中文 英文 語言 言語 sprache | language",
|
||||
"upgrade version 升级 版本 升級 バージョン aktualisier | app updates|about",
|
||||
"backup export import restore 备份 导出 导入 恢复 備份 匯出 匯入 還原 バックアップ 復元 sicherung | sync and backup|backup",
|
||||
"redact desensitiz sensitive secret password pii 脱敏 隐私 敏感 密码 掩码 去敏 隱私 遮罩 密碼 マスク 秘密 パスワード maskier datenschutz | privacy|what to mask|masking",
|
||||
"lan remote phone mobile tailscale 局域网 远程 共享 手机 内网 區域網 遠端 共用 手機 リモート 共有 スマホ fernzugriff | sharing|local network|browser access|another magpie|network and sharing",
|
||||
"cost money price spend billing 费用 花费 价格 账单 金额 花了多少 費用 價格 帳單 料金 価格 kosten preis | currency|menu bar cost|price rate|totals in|low balance alert",
|
||||
"quota rate_limit 额度 配额 限额 余量 限流 額度 配額 クォータ 上限 kontingent | allowance|requests per minute|rate limited|concurrency",
|
||||
"tray menubar menu_bar status_bar 托盘 菜单栏 状态栏 系統匣 選單列 狀態列 メニューバー トレイ menüleiste | menu bar|tray|bar icon",
|
||||
"hotkey shortcut keybind keyboard 快捷键 热键 快捷鍵 熱鍵 ショートカット tastenkürzel | quick panel shortcut",
|
||||
"api_key apikey token 密钥 秘钥 令牌 金鑰 キー schlüssel | api key|gateway keys|accounts",
|
||||
"web_search 联网 搜索引擎 網路搜尋 ウェブ検索 websuche | web search",
|
||||
"image_generat picture 生图 画图 图片 图像 繪圖 圖片 画像 bild | images|background image",
|
||||
"context_length long_context 上下文 压缩 長度 コンテキスト kontext | longest context|context window|compact at|context",
|
||||
"timeout latency 超时 延迟 逾時 延遲 タイムアウト zeitüberschreitung | slow to start|speed first",
|
||||
"disable_model hide_model 禁用模型 隐藏模型 停用模型 屏蔽模型 隱藏模型 モデル無効 | disabled models",
|
||||
"checkin check-in 签到 簽到 チェックイン | check in|check-in",
|
||||
"warmup warm-up 预热 重置 預熱 ウォームアップ | warm up|resets|reset reminder",
|
||||
"memory ram usage performance battery 内存 性能 省电 耗电 卡顿 記憶體 效能 メモリ 省電力 speicher akku | lightweight mode",
|
||||
"sidebar navigation 侧边栏 侧栏 导航 側邊欄 導覽 サイドバー seitenleiste | sidebar pages",
|
||||
"history chat_log 历史 记录 聊天记录 歷史 紀錄 履歴 verlauf | session history|sessions",
|
||||
"terminal iterm ghostty 终端 終端 ターミナル | session terminal",
|
||||
].map((l) => {
|
||||
const [say, to] = l.split(" | ");
|
||||
return { say: say.split(" ").map((w) => w.replace(/_/g, " ")), to: to.split("|") };
|
||||
});
|
||||
const CJK = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff]/;
|
||||
// a concept's word in what was typed: Chinese or Japanese anywhere in it, a
|
||||
// Latin word at a word's start (monitor finds monitoring; "ram" is not in
|
||||
// "program"), a short one whole ("lan" is not "language"), and a word
|
||||
// still being typed as its start ("accessib")
|
||||
function conceptsOf(q) {
|
||||
const at = " " + q.replace(/[^\p{L}\p{N}]+/gu, " ") + " ";
|
||||
const last = q.split(/\s+/).pop();
|
||||
return CONCEPTS.filter((c) => c.say.some((w) => CJK.test(w) ? q.includes(w) || (last.length > 1 && w.startsWith(last))
|
||||
: at.includes(" " + w + (w.length > 3 ? "" : " ")) || (last.length > 3 && w.startsWith(last))));
|
||||
}
|
||||
// one typo: a letter more, less or other
|
||||
function near1(a, b) {
|
||||
if (Math.abs(a.length - b.length) > 1) return false;
|
||||
let i = 0, j = 0, e = 0;
|
||||
while (i < a.length && j < b.length) {
|
||||
if (a[i] === b[j]) { i++; j++; continue; }
|
||||
if (++e > 1) return false;
|
||||
if (a.length > b.length) i++;
|
||||
else if (b.length > a.length) j++;
|
||||
else { i++; j++; }
|
||||
}
|
||||
return e + (a.length - i) + (b.length - j) <= 1;
|
||||
}
|
||||
// a word's pieces: a run of Chinese or Japanese longer than two by its
|
||||
// two-character words, anything else whole
|
||||
const pieces = (w) => !CJK.test(w) || w.length <= 2 ? [w] : [...w].slice(0, -1).map((c, i) => c + w[i + 1]);
|
||||
const piecesIn = (ps, text) => {
|
||||
let toks = null;
|
||||
return ps.filter((p) => text.includes(p) || (p.length > 3 && !CJK.test(p) && (toks ||= text.split(/[^\p{L}\p{N}]+/u)).some((x) => near1(p, x)))).length;
|
||||
};
|
||||
// findQuery: what a place must say for the words. By default the words
|
||||
// themselves (every one in a place's text) or, by its name, a setting a
|
||||
// concept in them is about; "words" the words alone; "near" a concept's
|
||||
// settings or most of the words' pieces, by name. test(text, name) is
|
||||
// whether a place matches; any(text) whether some of what is asked is there
|
||||
function findQuery(q, mode = "") {
|
||||
const words = q.split(/\s+/).filter(Boolean);
|
||||
const to = mode === "words" ? [] : conceptsOf(q).flatMap((c) => c.to);
|
||||
const about = (name) => to.some((x) => name.includes(x));
|
||||
if (mode !== "near") return { key: mode + q, test: (text, name = text) => words.every((w) => text.includes(w)) || about(name), any: (text) => words.some((w) => text.includes(w)) || about(text) };
|
||||
const ps = words.flatMap(pieces);
|
||||
const loose = (name) => {
|
||||
const n = piecesIn(ps, name);
|
||||
return n > 0 && n * 2 >= ps.length;
|
||||
};
|
||||
return { key: "~" + q, near: true, test: (text, name = text) => about(name) || loose(name), any: (text) => about(text) || piecesIn(ps, text) > 0 };
|
||||
}
|
||||
window.findQuery = findQuery;
|
||||
|
||||
// Settings' own rows matching the words, shown or English, by their text,
|
||||
// section heading or part name (sgfvdsg86265 on X); Escape restores
|
||||
const setText = (n) => [n.textContent, ...[...n.querySelectorAll("[data-en]")].map((e) => e.dataset.en)].join(" ").toLowerCase();
|
||||
window.setFind = function () {
|
||||
if (!provLinksDrawn && setQuery) provLinksDraw();
|
||||
const v = $("#view-settings");
|
||||
v.classList.add("set-searching");
|
||||
const words = setQuery.split(/\s+/);
|
||||
let any = false;
|
||||
// a row's name, shown and in English (the name's own data-en)
|
||||
const nameText = (n) => {
|
||||
const e = n.querySelector(".name") || n.querySelector(".who") || n;
|
||||
return setText(e) + " " + (e.dataset.en || "").toLowerCase();
|
||||
};
|
||||
// a row found: shown where it is, not under a hidden part of the page, a
|
||||
// built-in switched off or a provider not there
|
||||
function rowShows(n, page) {
|
||||
for (let a = n; a && a !== page; a = a.parentElement) if (a.hidden) return false;
|
||||
if (featureHides(n)) return false;
|
||||
const ps = n.agents && (providers || providersEarly?.got)?.providers;
|
||||
return !(ps && !ps.some((x) => n.agents.includes(x.account?.agent)));
|
||||
}
|
||||
// each part's rows the query finds, and whether each matched at all
|
||||
function setRows(fq) {
|
||||
const out = [];
|
||||
for (const id of SET_TABS) {
|
||||
const page = $("#setPage-" + id), tab = $("#setTab-" + id);
|
||||
const part = setText(tab) + (id === "otel" ? " otel" : ""); // not "usage" for Allowances
|
||||
let hits = 0, head = "";
|
||||
const lit = new Set();
|
||||
let head = "";
|
||||
const rows = [];
|
||||
for (const n of page.querySelectorAll(".row-head, .row")) {
|
||||
if (n.matches(".row-head")) {
|
||||
head = setText(n);
|
||||
continue;
|
||||
}
|
||||
if (n.parentElement.closest(".row")) continue; // a row in a row goes with it
|
||||
const says = part + " " + head + " " + setText(n);
|
||||
const hit = words.every((w) => says.includes(w));
|
||||
n.classList.toggle("set-miss", !hit);
|
||||
let shows = hit;
|
||||
for (let a = n; shows && a && a !== page; a = a.parentElement) if (a.hidden) shows = false;
|
||||
if (shows && featureHides(n)) shows = false; // a built-in plugin switched off
|
||||
// a provider's link with no such provider to open
|
||||
const ps = n.agents && (providers || providersEarly?.got)?.providers;
|
||||
if (shows && ps && !ps.some((x) => n.agents.includes(x.account?.agent))) n.classList.add("set-miss"), shows = false;
|
||||
const hit = fq.test(part + " " + head + " " + setText(n), part + " " + head + " " + nameText(n));
|
||||
rows.push([n, hit, hit && rowShows(n, page)]);
|
||||
}
|
||||
out.push([id, page, tab, rows]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const setCount = (fq) => setRows(fq).reduce((s, [, , , rows]) => s + rows.filter((r) => r[2]).length, 0)
|
||||
+ (window.setFeatsFind?.(fq, true) || 0) + elseFind(fq, true);
|
||||
window.setFind = function () {
|
||||
if (!provLinksDrawn && setQuery) provLinksDraw();
|
||||
const v = $("#view-settings");
|
||||
v.classList.add("set-searching");
|
||||
// the words themselves, and the settings a concept in them is about;
|
||||
// their pieces, or a typo's word, when nothing has them. The line says
|
||||
// so when no setting has the words themselves.
|
||||
let fq = findQuery(setQuery), near = false;
|
||||
if (!setCount(fq)) fq = findQuery(setQuery, "near");
|
||||
if (!setCount(findQuery(setQuery, "words"))) near = setCount(fq) > 0;
|
||||
let any = false;
|
||||
for (const [, page, tab, rows] of setRows(fq)) {
|
||||
let hits = 0;
|
||||
const lit = new Set();
|
||||
for (const [n, hit, shows] of rows) {
|
||||
n.classList.toggle("set-miss", !shows);
|
||||
if (!shows) continue;
|
||||
hits++;
|
||||
lit.add(n.closest(".list") || n.parentElement);
|
||||
@@ -55,12 +178,13 @@ window.setFind = function () {
|
||||
}
|
||||
window.setFolds?.(v); // a hit under a folded Advanced (provlinks.js)
|
||||
// the built-ins that match (setfeats.js)
|
||||
if (window.setFeatsFind) any = setFeatsFind(words) > 0 || any;
|
||||
if (window.setFeatsFind) any = setFeatsFind(fq) > 0 || any;
|
||||
else import("./setfeats.js").then(() => setQuery && setFind(), () => {});
|
||||
any = elseFind(words) > 0 || any;
|
||||
const none = $("#setNone");
|
||||
none.hidden = any;
|
||||
none.textContent = t("No setting matches “{q}”", { q: $("#setQ").value.trim() });
|
||||
any = elseFind(fq) > 0 || any;
|
||||
const none = $("#setNone"), typed = $("#setQ").value.trim();
|
||||
none.hidden = any && !near;
|
||||
none.classList.toggle("set-near", near);
|
||||
none.textContent = near ? t("Settings related to “{q}”", { q: typed }) : t("No setting matches “{q}”", { q: typed });
|
||||
};
|
||||
|
||||
// a place's words: its English and the reader's language, lower case
|
||||
@@ -179,19 +303,17 @@ function places() {
|
||||
// the rows a page shows before Show more
|
||||
const FIRST = 8;
|
||||
let elseMore = new Set(), elseWords = "";
|
||||
function elseFind(words) {
|
||||
function elseFind(fq, dry) {
|
||||
const q = fq?.key || "";
|
||||
const found = !q ? [] : places().filter((x) => fq.test(x.own + " " + (x.of || ""), x.own + " " + (x.of || "")) && (!x.of || fq.any(x.own)));
|
||||
if (dry) return found.length;
|
||||
let box = document.getElementById("setElse");
|
||||
if (!box) {
|
||||
box = el("div", "set-else");
|
||||
box.id = "setElse";
|
||||
$("#view-settings").append(box);
|
||||
}
|
||||
const q = words.join(" ");
|
||||
if (q !== elseWords) elseMore = new Set(), elseWords = q;
|
||||
const found = !words.length ? [] : places().filter((x) => {
|
||||
const all = x.own + " " + (x.of || "");
|
||||
return words.every((w) => all.includes(w)) && (!x.of || words.some((w) => x.own.includes(w)));
|
||||
});
|
||||
// a page's places, its own name first, then what a name says before a field
|
||||
const by = new Map();
|
||||
for (const x of found) {
|
||||
@@ -224,7 +346,7 @@ function elseFind(words) {
|
||||
if (!all && list.length > FIRST) {
|
||||
const more = el("button", "text find-more", t("Show {n} more", { n: list.length - FIRST }));
|
||||
more.type = "button";
|
||||
more.onclick = () => { elseMore.add(v); elseFind(words); };
|
||||
more.onclick = () => { elseMore.add(v); elseFind(fq); };
|
||||
sec.append(rows, more);
|
||||
} else sec.append(rows);
|
||||
secs.push(sec);
|
||||
|
||||
@@ -3907,6 +3907,7 @@ const I18N = {
|
||||
"Search sessions": "搜索会话",
|
||||
"Find a setting": "查找设置",
|
||||
"No setting matches “{q}”": "没有和“{q}”匹配的设置",
|
||||
"Settings related to “{q}”": "与“{q}”相关的设置",
|
||||
"Find a provider": "查找供应商",
|
||||
"No provider matches “{q}”": "没有和“{q}”匹配的供应商",
|
||||
"Serves {models}": "提供 {models}",
|
||||
@@ -9387,6 +9388,7 @@ const I18N = {
|
||||
"Search sessions": "搜尋會話",
|
||||
"Find a setting": "尋找設定",
|
||||
"No setting matches “{q}”": "沒有和「{q}」匹配的設定",
|
||||
"Settings related to “{q}”": "與「{q}」相關的設定",
|
||||
"Find a provider": "尋找供應商",
|
||||
"No provider matches “{q}”": "沒有和「{q}」匹配的供應商",
|
||||
"Serves {models}": "提供 {models}",
|
||||
@@ -14868,6 +14870,7 @@ const I18N = {
|
||||
"Search sessions": "セッションを検索",
|
||||
"Find a setting": "設定を検索",
|
||||
"No setting matches “{q}”": "「{q}」に一致する設定はありません",
|
||||
"Settings related to “{q}”": "「{q}」に関連する設定",
|
||||
"Find a provider": "プロバイダを検索",
|
||||
"No provider matches “{q}”": "「{q}」に一致するプロバイダはありません",
|
||||
"Serves {models}": "{models} を提供",
|
||||
@@ -20370,6 +20373,7 @@ const I18N = {
|
||||
"Search sessions": "Sitzungen durchsuchen",
|
||||
"Find a setting": "Einstellung suchen",
|
||||
"No setting matches “{q}”": "Keine Einstellung passt zu „{q}“",
|
||||
"Settings related to “{q}”": "Einstellungen zu „{q}“",
|
||||
"Find a provider": "Anbieter suchen",
|
||||
"No provider matches “{q}”": "Kein Anbieter passt zu „{q}“",
|
||||
"Serves {models}": "Bietet {models}",
|
||||
|
||||
@@ -22,7 +22,15 @@ let featAt = null, featAtEnd = 0;
|
||||
row.classList.add("flash");
|
||||
};
|
||||
}
|
||||
window.setFeatsFind = function (words) {
|
||||
// fq is finder.js's findQuery; dry counts them and draws nothing
|
||||
window.setFeatsFind = function (fq, dry) {
|
||||
const say = (s) => (s ? s + " " + t(s) : "");
|
||||
const found = ((fq?.key && prefs?.builtins) || []).filter((f) => {
|
||||
const props = Object.values(f.schema?.properties || {});
|
||||
const text = [say(f.name), say(f.sub), ...props.map((p) => say(p.title) + " " + say(p.description))].join(" ").toLowerCase();
|
||||
return fq.test(text, [say(f.name), ...props.map((p) => say(p.title))].join(" ").toLowerCase());
|
||||
});
|
||||
if (dry) return found.length;
|
||||
let box = document.getElementById("setFeats");
|
||||
if (!box) {
|
||||
box = el("section", "set-page set-feats");
|
||||
@@ -31,12 +39,6 @@ window.setFeatsFind = function (words) {
|
||||
$("#view-settings").append(box);
|
||||
}
|
||||
const list = box.firstChild;
|
||||
const say = (s) => (s ? s + " " + t(s) : "");
|
||||
const found = ((words.length && prefs?.builtins) || []).filter((f) => {
|
||||
const props = Object.values(f.schema?.properties || {});
|
||||
const text = [say(f.name), say(f.sub), ...props.map((p) => say(p.title) + " " + say(p.description))].join(" ").toLowerCase();
|
||||
return words.every((w) => text.includes(w));
|
||||
});
|
||||
// drawn again only when it changes: a draw is a change Settings'
|
||||
// observer runs the search again on
|
||||
const key = document.documentElement.lang + " " + found.map((f) => f.id + (f.on ? "+" : "-")).join(" ");
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings' search finds what the words are about (canlee886 on X:
|
||||
// "可访问性", "监控" and "自动选择模型" each said no setting matched, "缺少
|
||||
// 搜索时的智能联想"). When no setting has the words themselves, the
|
||||
// settings they are about are shown under "Settings related to “…”": a
|
||||
// concept's words in each language (accessibility, monitoring, picking a
|
||||
// model by itself) lead to the settings it covers, a long run of Chinese is
|
||||
// read by its two-character words, and a Latin word may have a typo. Words
|
||||
// a setting has are still found as before, with no such line, and words
|
||||
// nothing is about still say no setting matches. Nothing is posted, the
|
||||
// page doesn't scroll, and nothing runs off to the side at 560 x 420 or on
|
||||
// a phone. Every language, Chromium and WebKit; the API is faked here.
|
||||
// SEARCH_ASSETS points it at an older assets folder (the base, where it
|
||||
// fails); ARTIFACT_DIR gets a screenshot of each.
|
||||
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 { provPrefsProviders } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(process.env.SEARCH_ASSETS || path.join(__dirname, "../assets"));
|
||||
|
||||
const row = (id, name, sub, on, more) => ({ id, name, sub, on, chosen: on, source: "preset", state: on ? "active" : "off", inUse: 0, ...more });
|
||||
const builtins = [
|
||||
row("otel", "Observability", "Send each request's trace to an OpenTelemetry collector", false, { setAt: "otel #otelList" }),
|
||||
];
|
||||
|
||||
function server(lang, posts, web) {
|
||||
const cur = {
|
||||
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", textSize: 100,
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, builtins,
|
||||
};
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (req.method() !== "GET" && url.pathname !== "/api/update/using" && url.pathname !== "/api/page-away") posts.push(url.pathname);
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web},textSize:100,featuresOff:["otel"]};` });
|
||||
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", textSize: 100 }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings") return json(cur);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/plugins/builtin") return json(builtins);
|
||||
if (url.pathname === "/api/providers") return json(provPrefsProviders(["codex"], { codex: "ChatGPT" }));
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
// the line over the parts, and whether it is the related one (only when no
|
||||
// setting has the words themselves)
|
||||
const line = (page) => page.evaluate(() => {
|
||||
const n = document.querySelector("#setNone");
|
||||
return n.getClientRects().length ? (n.classList.contains("set-near") ? "near: " : "none: ") + n.textContent : "";
|
||||
});
|
||||
const seen = (page, sel) => page.locator(sel).first().evaluate((e) => !!e.getClientRects().length && getComputedStyle(e).visibility !== "hidden").catch(() => false);
|
||||
const overflow = (page) => page.evaluate(() => {
|
||||
const out = [];
|
||||
const de = document.documentElement, v = document.querySelector("#view-settings");
|
||||
if (de.scrollWidth > de.clientWidth) out.push("page " + de.scrollWidth + ">" + de.clientWidth);
|
||||
if (v.scrollWidth > v.clientWidth) out.push("view " + v.scrollWidth + ">" + v.clientWidth);
|
||||
const n = document.querySelector("#setNone").getBoundingClientRect(), r = v.getBoundingClientRect();
|
||||
if (n.width && (n.left < r.left - 0.5 || n.right > r.right + 0.5)) out.push("line " + n.left + "-" + n.right);
|
||||
return out;
|
||||
});
|
||||
|
||||
// what a reader in each language types for the three asks
|
||||
const ASKS = {
|
||||
en: ["accessibility", "monitoring", "auto select model"],
|
||||
zh: ["可访问性", "监控", "自动选择模型"],
|
||||
"zh-TW": ["無障礙", "監控", "自動選擇模型"],
|
||||
ja: ["アクセシビリティ", "監視", "モデル自動選択"],
|
||||
de: ["barrierefreiheit", "überwachung", "automatische modellwahl"],
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": Settings' search finds what the words are about", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const shots = [];
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
for (const [name, buf] of shots) await fs.writeFile(path.join(process.env.ARTIFACT_DIR, `${engine}-settings-related-${name}.png`), buf);
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
const open = async (lang, posts, { width = 560, height = 420, web = false } = {}) => {
|
||||
const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.errors = [];
|
||||
page.on("pageerror", (e) => { if (engine === "webkit" && /due to access control checks/.test(e.message)) return; page.errors.push(e.message); });
|
||||
await page.route("**/*", server(lang, posts, web));
|
||||
await page.goto("http://magpie.test/?view=settings&tab=general");
|
||||
await page.locator("#themeSegs .opt").first().waitFor();
|
||||
return page;
|
||||
};
|
||||
// typed, then the search settled: the lazy finder and built-ins in
|
||||
const type = async (page, s) => {
|
||||
await page.locator("#setQ").fill(s);
|
||||
await page.waitForFunction(() => window.setFind && window.setFeatsFind && document.querySelector("#view-settings").classList.contains("set-searching") === !!document.querySelector("#setQ").value.trim());
|
||||
await page.waitForTimeout(150);
|
||||
};
|
||||
|
||||
for (const lang of Object.keys(ASKS)) {
|
||||
await t.test(lang, async () => {
|
||||
const posts = [];
|
||||
const page = await open(lang, posts);
|
||||
const tr = (s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]);
|
||||
const [a11y, monitor, autoModel] = ASKS[lang];
|
||||
|
||||
// accessibility: the settings that make it easier to see and use
|
||||
await type(page, a11y);
|
||||
for (const sel of ["#textSizeSegs", "#themeSegs"]) assert(await seen(page, sel), `"${a11y}" shows ${sel}`);
|
||||
assert(await seen(page, "#view-settings .row:has(> .who > .name[data-en='Reduce motion'])"), `"${a11y}" shows Reduce motion`);
|
||||
assert.equal(await seen(page, "#currencySegs"), false, "not Currency");
|
||||
assert.equal(await line(page), "near: " + await tr("Settings related to “{q}”", { q: a11y }));
|
||||
assert.deepEqual(await overflow(page), []);
|
||||
shots.push([lang + "-a11y", await page.screenshot()]);
|
||||
|
||||
// monitoring: Observability, a built-in switched off here
|
||||
await type(page, monitor);
|
||||
const feats = await page.locator("#setFeats .feat-find:visible .name").allTextContents();
|
||||
assert(feats.includes(await tr("Observability")), `"${monitor}" finds Observability: ${feats}`);
|
||||
assert.match(await line(page), /^near: /);
|
||||
assert.deepEqual(await overflow(page), []);
|
||||
shots.push([lang + "-monitor", await page.screenshot()]);
|
||||
|
||||
// a model picked by itself: Models' Routing settings
|
||||
await type(page, autoModel);
|
||||
assert(await seen(page, "#busyLoadRow"), `"${autoModel}" shows Busy models last`);
|
||||
assert(await seen(page, "#contextCapRow"), `"${autoModel}" shows Longest context, under the same Routing`);
|
||||
assert.equal(await seen(page, "#themeSegs"), false, "not Appearance");
|
||||
// with a setting that has the words themselves (English's web
|
||||
// search row says "auto", "select" and "model"), no line
|
||||
assert.match(await line(page), lang === "en" ? /^$/ : /^near: /);
|
||||
assert.deepEqual(await overflow(page), []);
|
||||
shots.push([lang + "-auto-model", await page.screenshot()]);
|
||||
|
||||
// a word a setting has is found as before, with no line
|
||||
await type(page, "currency");
|
||||
assert(await seen(page, "#currencySegs"));
|
||||
assert.equal(await line(page), "");
|
||||
// and a concept's settings come with the words' own: "proxy" has
|
||||
// its own rows, and "vpn" (in no setting's words) leads to them
|
||||
await type(page, "vpn");
|
||||
assert(await seen(page, "#view-settings .row:has(> .who > .name[data-en='Proxy'])"), "vpn finds Proxy");
|
||||
// a typo is forgiven
|
||||
await type(page, "currancy");
|
||||
assert(await seen(page, "#currencySegs"), "currancy finds Currency");
|
||||
assert.equal(await line(page), "near: " + await tr("Settings related to “{q}”", { q: "currancy" }));
|
||||
// and words nothing is about still say so
|
||||
await type(page, "zzqqxx");
|
||||
assert.equal(await line(page), "none: " + await tr("No setting matches “{q}”", { q: "zzqqxx" }));
|
||||
// Escape puts it all away
|
||||
await page.locator("#setQ").focus();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await line(page), "");
|
||||
assert(await seen(page, "#setTabs"), "the tabs back");
|
||||
|
||||
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), 0, "searching scrolls nothing");
|
||||
assert.deepEqual(posts, [], "searching posts nothing");
|
||||
assert.deepEqual(page.errors, []);
|
||||
await page.context().close();
|
||||
});
|
||||
}
|
||||
|
||||
// a long run of Chinese is read by its two-character words, and a
|
||||
// Latin word with a typo by the word it is near
|
||||
await t.test("pieces and typos", async () => {
|
||||
for (const [lang, q] of [["zh", "文字大小调整"], ["en", "text sise"], ["zh-TW", "文字大小調整"]]) {
|
||||
const page = await open(lang, []);
|
||||
await type(page, q);
|
||||
assert(await seen(page, "#textSizeSegs"), `${lang} "${q}" finds Text size`);
|
||||
assert.match(await line(page), /^near: /, q);
|
||||
assert.deepEqual(page.errors, []);
|
||||
await page.context().close();
|
||||
}
|
||||
});
|
||||
|
||||
await t.test("magpie web on a phone", async () => {
|
||||
const page = await open("zh", [], { width: 390, height: 760, web: true });
|
||||
await type(page, "可访问性");
|
||||
assert.equal(await line(page), "near: 与“可访问性”相关的设置");
|
||||
assert.deepEqual(await overflow(page), []);
|
||||
shots.push(["web-phone", await page.screenshot()]);
|
||||
assert.deepEqual(page.errors, []);
|
||||
await page.context().close();
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user