Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
test: run the built-in ad blocking on real pages before a runtime release
Tw93a59fdd9a4bc6
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex 0b40fb09..3bd2b3f2 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -42,3 +42,4 @@ paths:- The shared download HTTP client pools connections without a cookie jar. Redirects must re-read the calling window's cookies for each HTTP(S) target, progressively narrow Referer, and never restore it after an HTTPS downgrade. Accept page context only from the calling window's actual origin, strip URL credentials, and flush asynchronous file writes before reporting success. Wry (through 0.57.2) misses macOS literal-IP cookies; only that branch reads the window's full cookie store, with exact IP, Path, Secure and expiry filtering. Keep normal hostnames and other platforms on `cookies_for_url`. Validate the real WebView's User-Agent, Referer, HttpOnly session cookie and wrong-Path exclusion in `tests/integration/ipc-security.mjs`.- macOS menu navigation must keep working on blank error pages: Reload uses native `WebviewWindow::reload`, Go Home uses `navigate` + `resolve_home_url`, Back/Forward use the platform WKWebView history API rather than page `eval`. Copy URL reads `window.url()` so it does not depend on a live JS document.- The release profile is `panic = "unwind"` (2026-11-19), not `abort`: under abort an Objective-C exception that crosses a Rust frame ends the app, since Wry's `objc2::exception::catch` cannot hold, and WebKit raises one whenever an `ipc://` answer arrives for a request a closing or leaving page had out. Measured on macOS 26.7 with both mitigations off (no `deferWindowClose`, `CLOSE_GRACE` 0): the abort build died on the first sign-in popup with a crash report, the unwind build finished all three flows of `tests/integration/signin-popup-server.mjs` and stayed up. It costs about 1.9 MB per architecture on macOS (12.8 to 14.7 MB on arm64). Windows and Linux have no such exception and pay more (the Windows x64 binary went from 11.9 to 16.4 MB), so the CLI passes `CARGO_PROFILE_RELEASE_PANIC=abort` to their release builds (`getPanicStrategyEnvironment` in `bin/builders/env.ts`), as any other builder of those platforms should; the profile's default stays unwind so that a builder that forgets is only larger, never back to the crash. Do not switch the profile back for size; `tests/unit/popup-close.test.ts` holds it. The close delay and the grace stay: they let the popup's last calls finish, which unwinding does not.+- Built-in ad blocking (`content-blocking` feature, `src-tauri/src/app/content_blocking.rs`) embeds the lists of `filters/`, which `node scripts/update-filter-lists.mjs` downloads; they age within days, so update them before a runtime release. A change to the lists or to their conversion is then run on real pages with `node tests/blocking/run.mjs` (macOS, about 15 minutes for the 60 pages of `tests/blocking/sites.txt`), because unit tests on the conversion let I-23 ship: it loads each page in an offscreen WKWebView without blocking, with the two WebKit lists a Mac or Linux app compiles and with the hiding script a Windows app injects, and fails a page that loses its icons, most of its elements or most of a long text. It first proves it can fail, on a list that hides every `svg`. Pages change from one load to the next, so a difference is loaded three times before it counts, and a cookie notice that is half of a short page's text is the cookies list working. Measured in a Windows 11 VM on 2026-11-21: the 644 KB generic hiding style costs about 12 ms to add on a page and 2 to 8 ms more on a full style recalculation (stackoverflow.com, bilibili.com, theguardian.com), so it is not trimmed per site. Scriptlet rules (`+js(...)`) and procedural selectors are dropped on purpose: the scriptlets that block YouTube's ads change every few days, and lists embedded at build time would be stale and could stop playback instead; they need a way to update lists in installed apps first.diff --git a/src-tauri/src/app/content_blocking.rs b/src-tauri/src/app/content_blocking.rsindex a474d04d..e0c46857 100644--- a/src-tauri/src/app/content_blocking.rs+++ b/src-tauri/src/app/content_blocking.rs@@ -1294,9 +1294,6 @@ mod tests {#[test]fn the_windows_script_carries_the_exceptions() {let script = generic_script(&["ads"]);- if let Ok(path) = std::env::var("PAKE_DUMP_SCRIPT") {- std::fs::write(path, &script).expect("script written");- }assert!(script.contains("\"bing.com\""),"a site with generic hiding off"@@ -1312,6 +1309,22 @@ mod tests {assert!(!script.contains("(document.head||document.documentElement).appendChild"));}+ /// Writes what an app with every group on loads, for+ /// `tests/blocking/run.mjs` to try on real pages: the two WebKit lists of+ /// a Mac or Linux app and the hiding script of a Windows one.+ #[test]+ #[ignore = "writes files for tests/blocking/run.mjs"]+ fn dump_for_real_pages() {+ let dir = std::env::var("PAKE_DUMP_BLOCKING").expect("PAKE_DUMP_BLOCKING names a folder");+ let dir = std::path::Path::new(&dir);+ let all: Vec<&str> = GROUPS.iter().map(|(group, _)| *group).collect();+ for (unit, rule_types) in WEBKIT_UNITS {+ let json = serde_json::to_string(&webkit_rules(&all, rule_types)).expect("rules");+ std::fs::write(dir.join(format!("{unit}.json")), json).expect("list written");+ }+ std::fs::write(dir.join("windows.js"), generic_script(&all)).expect("script written");+ }+#[test]fn rules_serialize_to_webkit_json() {let rules = webkit_rules(&["ads"], RuleTypes::NetworkOnly);diff --git a/tests/blocking/probe.swift b/tests/blocking/probe.swiftnew file mode 100644index 00000000..026e9c28--- /dev/null+++ b/tests/blocking/probe.swift@@ -0,0 +1,124 @@+import AppKit+import WebKit++// Loads one page in an offscreen WKWebView and prints one line of JSON saying+// what the page shows. Run by tests/blocking/run.mjs.+// probe <url> [--list rules.json]... [--script start.js]+// --list compiles a WebKit content rule list, as a Mac or Linux app does.+// --script runs at document start in every frame, as the Windows runtime's+// hiding script does.+var args = Array(CommandLine.arguments.dropFirst())+guard let first = args.first, let url = URL(string: first) else {+ print("{\"error\":\"usage\"}")+ exit(64)+}+args.removeFirst()+var lists: [String] = []+var scripts: [String] = []+while args.count >= 2 {+ if args[0] == "--list" { lists.append(args[1]) }+ if args[0] == "--script" { scripts.append(args[1]) }+ args.removeFirst(2)+}+let settle = Double(ProcessInfo.processInfo.environment["PROBE_SETTLE"] ?? "5") ?? 5+let limit = Double(ProcessInfo.processInfo.environment["PROBE_LIMIT"] ?? "75") ?? 75++func finish(_ line: String, _ code: Int32) -> Never {+ print(line)+ exit(code)+}++final class Navigation: NSObject, WKNavigationDelegate {+ var loaded: (() -> Void)?+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loaded?() }+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {+ loaded?()+ }+ func webView(+ _ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,+ withError error: Error+ ) {+ finish("{\"error\":\"load\"}", 3)+ }+}++let report = """+ (() => {+ const shown = (e) => getComputedStyle(e).display !== 'none';+ const all = [...document.querySelectorAll('body *')];+ const svg = [...document.querySelectorAll('svg')];+ const img = [...document.images];+ return JSON.stringify({+ href: location.href,+ elements: all.length,+ visible: all.filter((e) => e.offsetParent !== null || getComputedStyle(e).position === 'fixed').length,+ text: (document.body.innerText || '').length,+ svg: svg.length,+ svgHidden: svg.filter((e) => !shown(e)).length,+ img: img.length,+ imgHidden: img.filter((e) => !shown(e)).length,+ styles: document.querySelectorAll('style[data-pake-blocking]').length,+ });+ })()+ """++let app = NSApplication.shared+app.setActivationPolicy(.prohibited)+let config = WKWebViewConfiguration()+config.websiteDataStore = .nonPersistent()+let navigation = Navigation()+var web: WKWebView!++func start() {+ for path in scripts {+ guard let source = try? String(contentsOfFile: path, encoding: .utf8) else {+ finish("{\"error\":\"script\"}", 65)+ }+ config.userContentController.addUserScript(+ WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false))+ }+ web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1200, height: 800), configuration: config)+ web.customUserAgent =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15"+ web.navigationDelegate = navigation+ navigation.loaded = {+ navigation.loaded = nil+ DispatchQueue.main.asyncAfter(deadline: .now() + settle) {+ web.evaluateJavaScript(report) { value, _ in+ guard let line = value as? String else { finish("{\"error\":\"script\"}", 4) }+ finish(line, 0)+ }+ }+ }+ web.load(URLRequest(url: url))+}++// One store per run, so a list compiled for the first page serves the rest+// and the folder goes away with the run.+let storeDir = ProcessInfo.processInfo.environment["PROBE_STORE"] ?? NSTemporaryDirectory()+guard let store = WKContentRuleListStore(url: URL(fileURLWithPath: storeDir, isDirectory: true))+else { finish("{\"error\":\"store\"}", 65) }++var pending = lists.count+func added(_ list: WKContentRuleList) {+ config.userContentController.add(list)+ pending -= 1+ if pending == 0 { start() }+}+if pending == 0 { start() }+for path in lists {+ let identifier = "pake-probe-" + URL(fileURLWithPath: path).lastPathComponent+ store.lookUpContentRuleList(forIdentifier: identifier) { found, _ in+ if let found { return added(found) }+ guard let json = try? String(contentsOfFile: path, encoding: .utf8) else {+ finish("{\"error\":\"list\"}", 65)+ }+ store.compileContentRuleList(forIdentifier: identifier, encodedContentRuleList: json) {+ list, _ in+ guard let list else { finish("{\"error\":\"compile\"}", 5) }+ added(list)+ }+ }+}+DispatchQueue.main.asyncAfter(deadline: .now() + limit) { finish("{\"error\":\"timeout\"}", 2) }+app.run()diff --git a/tests/blocking/run.mjs b/tests/blocking/run.mjsnew file mode 100644index 00000000..dcbaba57--- /dev/null+++ b/tests/blocking/run.mjs@@ -0,0 +1,195 @@+#!/usr/bin/env node+// Runs the built-in ad blocking on real pages before a runtime release that+// changes the filter lists or their conversion (docs/incidents.md I-23, I-24).+// Each page of sites.txt is loaded in an offscreen WKWebView three times: with+// no blocking, with the two WebKit lists a Mac or Linux app compiles, and with+// the hiding script a Windows app injects. A page that loses its icons, most of+// its elements or most of its text under either fails the run.+//+// node tests/blocking/run.mjs every page of sites.txt+// node tests/blocking/run.mjs <url>... only these pages+//+// macOS only, and it needs the network. A page that does not load without+// blocking either is listed as not covered and does not fail the run.+import { execFile, execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const root = join(here, "../..");+const PARALLEL = 4;+const ROUNDS = 3;++// What counts as a page that lost its content. Pages change between two loads,+// so each limit sits far from what an ad or a banner removes.+export function verdict(off, on) {+ if (on.error) return `did not load (${on.error})`;+ const hidden = (page) => (page.svg ? page.svgHidden / page.svg : 0);+ if (on.svg >= 3 && hidden(on) > 0.5 && hidden(off) < 0.2) {+ return `${on.svgHidden} of ${on.svg} svg hidden, ${off.svgHidden} of ${off.svg} without blocking`;+ }+ if (off.visible > 50 && on.visible < off.visible * 0.5) {+ return `${on.visible} visible elements, ${off.visible} without blocking`;+ }+ // A cookie notice is half the text of a short landing page (grok.com,+ // perplexity.ai), so only a page with a body of text is held to this.+ if (off.text > 1500 && on.text < off.text * 0.4) {+ return `${on.text} characters of text, ${off.text} without blocking`;+ }+ return "";+}++function probe(bin, env, url, extra) {+ return new Promise((resolve) => {+ execFile(+ bin,+ [url, ...extra],+ { env: { ...process.env, ...env }, timeout: 120_000 },+ (_error, stdout) => {+ const line = stdout.trim().split("\n").pop() || "";+ try {+ resolve(JSON.parse(line));+ } catch {+ resolve({ error: "no report" });+ }+ },+ );+ });+}++async function main() {+ if (process.platform !== "darwin") {+ console.error("tests/blocking/run.mjs runs on macOS only");+ process.exit(2);+ }+ const { fetched } = JSON.parse(+ readFileSync(join(root, "filters/sources.json"), "utf8"),+ );+ const age = Math.floor((Date.now() - Date.parse(fetched)) / 86_400_000);+ console.log(+ `filter lists fetched ${fetched}, ${age} days ago` ++ (age > 14 ? "; run scripts/update-filter-lists.mjs first" : ""),+ );+ const work = mkdtempSync(join(tmpdir(), "pake-blocking-"));+ try {+ const bin = join(work, "probe");+ execFileSync("swiftc", ["-O", join(here, "probe.swift"), "-o", bin], {+ stdio: "inherit",+ });+ execFileSync(+ "cargo",+ [+ "test",+ "--lib",+ "--features",+ "content-blocking",+ "dump_for_real_pages",+ "--",+ "--ignored",+ ],+ {+ cwd: join(root, "src-tauri"),+ env: { ...process.env, PAKE_DUMP_BLOCKING: work },+ stdio: ["ignore", "ignore", "inherit"],+ },+ );+ const env = { PROBE_STORE: join(work, "store") };+ const modes = {+ webkit: [+ "--list",+ join(work, "network.json"),+ "--list",+ join(work, "cosmetic.json"),+ ],+ windows: ["--script", join(work, "windows.js")],+ };++ // The run first shows it can see a broken conversion: a list that hides+ // every svg, which is what I-23 shipped, has to fail on a page with icons.+ const broken = join(work, "broken.json");+ writeFileSync(+ broken,+ JSON.stringify([+ {+ trigger: { "url-filter": ".*" },+ action: { type: "css-display-none", selector: "svg" },+ },+ ]),+ );+ const control = "https://github.com/";+ const controlOff = await probe(bin, env, control, []);+ const controlOn = await probe(bin, env, control, ["--list", broken]);+ if (controlOff.error || !verdict(controlOff, controlOn)) {+ console.error(+ `the control did not fail: ${JSON.stringify(controlOff)} ${JSON.stringify(controlOn)}`,+ );+ process.exit(2);+ }+ // Compiles the two real lists once, before pages run side by side.+ const warm = await probe(bin, env, "https://example.com/", modes.webkit);+ if (warm.error) {+ console.error(`the lists did not compile or load: ${warm.error}`);+ process.exit(2);+ }+ const script = await probe(bin, env, "https://example.com/", modes.windows);+ if (!script.styles) {+ console.error("the Windows script attached no style to a plain page");+ process.exit(1);+ }++ const sites = process.argv.slice(2).length+ ? process.argv.slice(2)+ : readFileSync(join(here, "sites.txt"), "utf8")+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith("#"));+ const failed = [];+ const uncovered = [];+ const queue = [...sites];+ const worker = async () => {+ for (let url = queue.shift(); url; url = queue.shift()) {+ // Some pages come in two shapes from one load to the next (notion.so,+ // a Bing search), so a page that differs is loaded again, without and+ // with blocking, and fails only when it differs every time.+ let bad = "";+ let covered = false;+ for (let round = 0; round < ROUNDS; round++) {+ const off = await probe(bin, env, url, []);+ if (off.error) {+ bad = off.error;+ continue;+ }+ covered = true;+ bad = "";+ for (const [mode, extra] of Object.entries(modes)) {+ const why = verdict(off, await probe(bin, env, url, extra));+ if (why) bad += `${bad ? "; " : ""}${mode}: ${why}`;+ }+ if (!bad) break;+ }+ if (!covered) {+ uncovered.push(`${url} (${bad})`);+ console.log(`not covered ${url}`);+ continue;+ }+ if (bad) failed.push(`${url} ${bad}`);+ console.log(`${bad ? "FAILED " : "ok "} ${url} ${bad}`);+ }+ };+ await Promise.all(Array.from({ length: PARALLEL }, worker));++ const covered = sites.length - uncovered.length;+ console.log(+ `\n${covered} of ${sites.length} pages covered, ${failed.length} failed`,+ );+ for (const line of uncovered) console.log(`not covered: ${line}`);+ for (const line of failed) console.log(`failed: ${line}`);+ if (failed.length || covered < sites.length * 0.8) process.exit(1);+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+}++if (process.argv[1] === fileURLToPath(import.meta.url)) await main();diff --git a/tests/blocking/sites.txt b/tests/blocking/sites.txtnew file mode 100644index 00000000..d5d4fa7e--- /dev/null+++ b/tests/blocking/sites.txt@@ -0,0 +1,60 @@+https://chatgpt.com/+https://claude.ai/+https://chat.deepseek.com/+https://devdocs.io/+https://discord.com/app+https://excalidraw.com/+https://www.figma.com/+https://v.flomoapp.com/mine+https://gemini.google.com/+https://notebook.google.com/+https://github.com/+https://mail.google.com/+https://calendar.google.com/+https://grok.com/+https://www.instagram.com/+https://read.amazon.com/+https://linear.app/+https://musicforprogramming.net/+https://app.notion.com/+https://outlook.live.com/+https://www.perplexity.ai/+https://qwerty.kaiyi.cool/+https://read.readwise.io/+https://web.telegram.org/a/+https://wx.qq.com/+https://weread.qq.com/+https://x.com/+https://www.xiaohongshu.com/explore+https://www.youtube.com/+https://music.youtube.com/+https://www.google.com/search?q=pake+desktop+app+https://www.bing.com/search?q=pake+desktop+app+https://duckduckgo.com/?q=pake+desktop+app+https://www.bilibili.com/+https://www.zhihu.com/explore+https://weibo.com/+https://www.douyin.com/+https://www.reddit.com/+https://en.wikipedia.org/wiki/Web_browser+https://www.nytimes.com/+https://www.amazon.com/+https://www.taobao.com/+https://www.baidu.com/s?wd=pake+https://www.v2ex.com/+https://www.twitch.tv/+https://www.linkedin.com/+https://open.spotify.com/+https://www.tiktok.com/+https://news.ycombinator.com/+https://stackoverflow.com/questions+https://www.notion.so/+https://translate.google.com/+https://maps.google.com/+https://www.facebook.com/+https://slack.com/+https://www.jd.com/+https://www.163.com/+https://www.qq.com/+https://www.threads.net/+https://medium.com/diff --git a/tests/unit/blocking-verdict.test.ts b/tests/unit/blocking-verdict.test.tsnew file mode 100644index 00000000..08712740--- /dev/null+++ b/tests/unit/blocking-verdict.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+// @ts-expect-error a plain script without types+import { verdict } from '../blocking/run.mjs';++const page = (over: Record<string, number>) => ({+ elements: 2000,+ visible: 1500,+ text: 4000,+ svg: 20,+ svgHidden: 0,+ ...over,+});++describe('the real-page verdict of tests/blocking/run.mjs', () => {+ it('fails a page whose icons are all hidden, as I-23 shipped', () => {+ expect(verdict(page({}), page({ svgHidden: 20 }))).toMatch(+ /20 of 20 svg hidden/,+ );+ });++ it('fails a page that lost most of what it shows or says', () => {+ expect(verdict(page({}), page({ visible: 400 }))).toMatch(/visible/);+ expect(verdict(page({}), page({ text: 900 }))).toMatch(/characters/);+ });++ it('fails a page that loads only without blocking', () => {+ expect(verdict(page({}), { error: 'timeout' })).toMatch(/did not load/);+ });++ it('passes a page that lost an ad, a tracker pixel or a cookie notice', () => {+ expect(+ verdict(page({}), page({ visible: 1400, text: 3400, svgHidden: 2 })),+ ).toBe('');+ // grok.com: the cookie notice is more than half of a short page's text.+ expect(verdict(page({ text: 806 }), page({ text: 302 }))).toBe('');+ });++ it('passes a page that hides its own icons without blocking too', () => {+ expect(verdict(page({ svgHidden: 14 }), page({ svgHidden: 15 }))).toBe('');+ });+});