Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: harden download/menu multi-window UX and add /bugs skill

Tw937bc5b1013297
diff --git a/.agents/skills/bugs/SKILL.md b/.agents/skills/bugs/SKILL.md
new file mode 100644
index 00000000..a6ed99fb
--- /dev/null
+++ b/.agents/skills/bugs/SKILL.md
@@ -0,0 +1,129 @@
+---
+name: bugs
+version: 1.0.0
+description: Proactively sweep a Pake area for latent UX and runtime defects before users report them, using this repo's own fix history and boundary archetypes, and confirm every finding with a probe run this turn. Use for 找找有没有bug, 主动找bug, 有没有隐患, 排查隐患, 举一反三, 上线前扫一遍, 这块可靠吗, latent bug scan, sibling sweep after a fix. Not for an already-reported symptom (that is /hunt) and not for reviewing a diff (that is /check). Named bugs, not bug: /bug is a Claude Code built-in.
+---
+
+# Bugs: Find It Before the User Does
+
+`/hunt` needs a symptom. `/check` needs a diff. This one needs neither: it goes looking.
+
+## The Question
+
+Across Pake's fix history the dominant defect is not a crash. It is a wrong-but-plausible behavior: a SPA route treated as a download, a menu command aimed at the wrong window, a blank shell shown before the page is ready, or a flag that is a no-op on one platform. Nothing panics; the user just gets a worse desktop app than the browser.
+
+So the question that finds bugs here is never "can this crash?" It is:
+
+> What does this code do when the page is an **SPA route**, the window is **not the main label**, the document is an **error/blank shell**, the click has a **modifier key**, or the platform **ignores the Chromium flag**?
+
+Aim it at a boundary, not at a file.
+
+## 1. Pick the surface
+
+Name the area and the depth. A whole-repo sweep with no budget produces speculation; pick one hotspot and go deep. Start from the Hotspot Map in `AGENTS.md` (Current Risk Areas + table below) rather than inventing a scope.
+
+| Hotspot | Primary paths | Locked tests (examples) |
+|---|---|---|
+| Link / download heuristics | `src-tauri/src/inject/event.js` | `event-link-guard.test.js`, `download-http-status.test.ts` |
+| Download success semantics | `src-tauri/src/app/invoke.rs`, `window.rs` `on_download` | `download-http-status.test.ts` |
+| Menu / focused window | `src-tauri/src/app/menu.rs` | `menu-focused-window.test.ts` |
+| Startup visibility | `src-tauri/src/lib.rs`, `setup.rs` | `startup-window-reveal.test.ts` |
+| Auth / popup | `inject/auth.js`, `inject/event.js` | `auth-sso-patterns.test.js`, `new-window-macos.test.js` |
+| Clipboard | `inject/event.js` | `event-clipboard-shortcuts.test.js` |
+| Multi-window / icon | `window.rs`, `setup.rs` | `window-icon-reapply.test.ts` |
+| Platform fake capability | `cert.rs`, proxy, WebKit flags in `lib.rs` | `macos-proxy-feature.test.ts`, Linux flag unit tests |
+| CLI / config contract | `bin/`, `schema/pake.schema.json` | `config-file.test.ts`, `cli-options.test.ts` |
+
+## 2. Read the area's own fix history first
+
+```bash
+git log --oneline --grep='^fix' -i -- <path>
+git log --pretty=format:'%h %s%n%b' --grep='^fix' -i -- <path> | head -200
+```
+
+Bugs recur by shape within a module. Two signals worth acting on:
+
+- A fix chain of three or more commits each "completing" the previous one means a fourth sibling is probably still out there. Real chains here: download path heuristics (`/releases/` → `/assets/` → next SPA root), startup reveal (blank → about:blank → user cancel), menu target (`"pake"` hardcode → focused window → remaining hardcodes).
+- A commit body that says the prior fix was incomplete means that pattern's grep was under-run once already. Re-run it.
+
+## 3. Sweep the boundaries, in this order
+
+Highest historical yield first. For each, read the matching Risk Areas note in `AGENTS.md` before hypothesizing.
+
+| Boundary | What to ask | Where it lives |
+|---|---|---|
+| Download / navigation heuristics | Would a SPA route under this path/extension be intercepted? Prefer extension + `download` attr + query hints over broad path roots. | `inject/event.js` |
+| Success vs transport | Is HTTP non-2xx, empty body, or missing file still toasted as success? | `invoke.rs`, `on_download` |
+| Window identity | Does this path hardcode `"pake"` when the user may be on `pake-N` or the focused window? | `menu.rs`, `invoke.rs`, `setup.rs`, `window.rs` |
+| Eval on dead pages | Does this menu/shortcut need a page JS context? Error and blank shells have none; prefer native `reload` / `navigate` / platform history. | `menu.rs` |
+| Startup vs user control | Can page-load or fallback re-show a window the user already hid? Latch every user visibility path. | `lib.rs`, `setup.rs` |
+| Auth / popup | Does macOS auth still crash, strand about:blank, or open the system browser for SSO? Apple Sign-In stays native popup. | `auth.js`, `event.js` |
+| Clipboard | Does keydown steal native paste (images/files)? Is fallback gated on trusted keyup + TTL? | `event.js` |
+| Platform capability | Is this flag real on WKWebView / WebView2 / WebKitGTK, or a Chromium-only no-op? | `cert.rs`, `window.rs`, `lib.rs` |
+| Config dual track | Can a config file smuggle a value the CLI flag rejects? | `bin/helpers/merge.ts`, schema |
+
+For generic shapes (fail-open guards, recovery gated on the artifact it restores, watchdog tuned only to the fast path), invoke `/hunt` Recurring Failure mode. Do not re-derive that catalog here.
+
+## 4. Confirm before reporting
+
+A candidate is not a finding until it has evidence produced **this turn**.
+
+- **Confirmed**: a probe, a failing unit test on current code, or a complete source trace with a named trigger.
+- **Plausible**: the failure path is named, but nothing was run. Report separately and name the probe that would settle it.
+- **Not a finding**: anything inferred from a function name or "this looks risky". Grep the implementation or drop it.
+
+Oracles that settle cases here: unit tests under `tests/unit/`, `cargo test` for pure Rust helpers, a real packaged app cold start for blank-window claims, and the public site in a browser for "does this path navigate or download".
+
+Before flagging any risky-looking call, confirm it is production code. Unwraps in `#[test]`, string literals, and build scripts are not defects.
+
+## 5. Rank by blast radius
+
+1. Silently wrong navigation or download the user acts on (SPA route stolen, auth stranded)
+2. Stuck state with no recovery (error page, dead menu, latched hide)
+3. Multi-window / wrong-target action
+4. Wrong but visible (toast on wrong window, blank flash)
+5. Cosmetic
+
+## 6. Guard what gets fixed
+
+Anything confirmed and fixed needs a test that fails on the unfixed code, usually under `tests/unit/`. For a class of bug, guard the pattern (source introspection, parity, or pure helper), not only one URL string.
+
+Verify with:
+
+```bash
+npx vitest run
+cargo test
+cargo clippy --all-targets -- -D warnings
+```
+
+When the change touches `bin/`, also `pnpm run cli:build` and stage regenerated `dist/cli.js`.
+
+## Hard Rules
+
+- **No finding without this-turn evidence.** Speculation dressed as a finding wastes more review time than it saves.
+- **One archetype hit means sweep the whole repo for its signature.** Grep the shape, not the literal text, and report "checked N sites, M defective, K not applicable".
+- **Do not fix while sweeping.** Collect, then fix. Interleaving loses the sweep.
+- **Report clean boundaries as clean.** A boundary that was checked and holds is a result. Do not manufacture findings to justify the run.
+- **Findings outside the named area get listed, not fixed**, unless the maintainer agrees.
+
+## Output
+
+```
+Area: [what was swept, at what depth]
+Boundaries: [N walked, M applicable]
+
+Confirmed (severity order):
+1. [file:line] [the defect in one sentence]
+ Evidence: [probe output / failing test / measurement]
+ Blast: [what the user sees]
+
+Plausible (needs a probe):
+1. [file:line] [defect] -> [the probe that would settle it]
+
+Swept clean:
+- [boundary]: [what was checked, why it holds]
+
+Sibling sweep: [pattern signature] -> [N checked, M defective, K n/a]
+```
+
+Say whether anything was fixed or whether this was scan-only.
diff --git a/.claude/skills/bugs b/.claude/skills/bugs
new file mode 120000
index 00000000..1d7399d3
--- /dev/null
+++ b/.claude/skills/bugs
@@ -0,0 +1 @@
+../../.agents/skills/bugs
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
index cf135a7f..f2d2bce8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# AGENTS.md - Pake Project Knowledge Base
-> Project-specific Rust + Tauri rules: `.claude/rules/rust.md`. Release runbook: `.agents/skills/release/SKILL.md` (run `/release`; `.claude/skills/*` are symlinks into `.agents/skills/`, edit the `.agents` copy only). Exception: the `pake` skill's real source is `plugins/pake/skills/pake/SKILL.md` (shipped to users via the Claude Code plugin marketplace, `.claude-plugin/marketplace.json`); `.agents/skills/pake` is a symlink to it.
+> Project-specific Rust + Tauri rules: `.claude/rules/rust.md`. Skills live under `.agents/skills/` (`/release`, `/bugs`, `/github-ops`, `/code-review`; `.claude/skills/*` are symlinks into `.agents/skills/`, edit the `.agents` copy only). Exception: the `pake` skill's real source is `plugins/pake/skills/pake/SKILL.md` (shipped to users via the Claude Code plugin marketplace, `.claude-plugin/marketplace.json`); `.agents/skills/pake` is a symlink to it.
## Project Identity
@@ -71,6 +71,22 @@ Goals and project facts only; trust the agent to find its own path.
- Generated areas (`dist/`, `node_modules/`, `src-tauri/target/`, `.app/`, `src-tauri/icons/`, `src-tauri/png/`) are not source. Exception: `dist/cli.js` is the shipped CLI build artifact (see `package.json` `files`); any change under `bin/` rebuilds it via `pnpm run cli:build` and commits the regenerated file alongside the source change.
- Release status, issue closeout, npm delivery, and GitHub assets are separate truth surfaces. Verify each one live (source commit/tag, workflow run, npm registry, GitHub Release/assets, issue state); never let one passing surface imply another.
+## Hotspot Map (for `/bugs`)
+
+Proactive latent-bug sweeps use `.agents/skills/bugs/SKILL.md`. Pick one row and go deep; do not invent a whole-repo scope.
+
+| Hotspot | Paths | What usually goes wrong |
+|---|---|---|
+| Link / download heuristics | `src-tauri/src/inject/event.js` | SPA routes intercepted as downloads; path roots too broad |
+| Download success semantics | `invoke.rs`, `window.rs` `on_download` | Non-2xx toasted as success; toast/IPC pinned to `"pake"`; no session cookies |
+| Menu / focused window | `menu.rs` | Commands hit the main window, not the focused one; eval dead on error pages |
+| Startup visibility | `lib.rs`, `setup.rs` | Blank shell, `about:blank` false ready, user hide racing fallback reveal |
+| Auth / popup | `auth.js`, `event.js` | macOS auth crash, SSO in system browser, Apple popup exception |
+| Clipboard | `event.js` | keydown steals native paste; double-paste fallback |
+| Multi-window / icon | `window.rs`, `setup.rs` | Missing `reapply_window_icon` on show; secondary window toast/target |
+| Platform capability | `cert.rs`, proxy, WebKit flags | Flag name present, platform no-op |
+| CLI / config contract | `bin/`, `schema/` | Config smuggles out-of-range values CLI rejects |
+
## Current Risk Areas
- CLI options are user-facing and must stay synchronized across `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`, generated `dist/cli.js`, `schema/pake.schema.json`, and `docs/cli-usage*.md`. Schema-to-CLI sync is enforced by `tests/unit/config-file.test.ts`; the rest is manual discipline.
@@ -89,6 +105,8 @@ Goals and project facts only; trust the agent to find its own path.
- Local app builds and test runs mutate tracked files as build state: `src-tauri/pake.json`, `src-tauri/tauri.conf.json`, `src-tauri/tauri.macos.conf.json`, and regenerated icons under `src-tauri/png/` and `src-tauri/icons/`. Before committing, `git restore` whatever you did not intentionally change; never let a feature or release commit absorb this churn.
- Per-app optional fields in `default_app_list.json` currently take their defaults in Actions expressions in `release.yml` (`matrix.config.x || false` and the numeric ones), which works because every field so far is default-false or numeric. The first default-true field cannot use that path and must move its default into the jq read step: GitHub expressions cast both `null` and `false` to `0`, so `matrix.config.x != false` cannot express "default true" and would silently flip every app missing the field.
- Windows taskbar icons can register blank when an autostarted app launches before Explorer's icon cache is ready (#1323). Every hidden-to-visible path for the main window (tray show/click, activation shortcut, single-instance activation, initial delayed show) must call `reapply_window_icon` from `src-tauri/src/app/window.rs`, which reasserts both the small window icon and the large taskbar icon; adding a new `window.show()` path without it regresses the bug.
+- Download and toast paths must not hardcode `get_webview_window("pake")` when the action originates from a secondary window: IPC commands take the calling `WebviewWindow`, and `on_download` resolves toast by the event webview's label. Link-download heuristics prefer real file extensions, the `download` attribute, and `?download` / `?attachment` query hints; do not re-add broad SPA roots such as `/assets/`, `/dist/`, `/files/`, or `/releases/` (see #1337, #1339).
+- 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.
- `.github/workflows/pake-cli.yaml` and `single-app.yaml` are public build surfaces that external users trigger from their own forks (see `docs/github-actions-usage*.md`). Changes there ship to outside users on push to `main`, independent of `V*` releases; treat them like public API, not internal CI.
## Platform-Specific Development
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rs
index 875d67de..501e5f0a 100644
--- a/src-tauri/src/app/invoke.rs
+++ b/src-tauri/src/app/invoke.rs
@@ -8,6 +8,7 @@ use std::str::FromStr;
use std::sync::atomic::{AtomicI64, Ordering};
use tauri::http::Method;
use tauri::{command, AppHandle, Manager, Url, WebviewWindow};
+use tauri_plugin_http::reqwest::header::{HeaderValue, COOKIE};
use tauri_plugin_http::reqwest::{ClientBuilder, Request};
use tauri::Theme;
@@ -82,10 +83,30 @@ pub struct NotificationParams {
icon: String,
}
-#[command]
-pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result<(), String> {
- let window: WebviewWindow = app.get_webview_window("pake").ok_or("Window not found")?;
+/// Build a Cookie header from the webview session so authenticated downloads
+/// match what the page itself would request. Best-effort: missing cookies
+/// fall through to an anonymous request.
+fn cookie_header_for_url(window: &WebviewWindow, url: &Url) -> Option<HeaderValue> {
+ let cookies = window.cookies_for_url(url.clone()).ok()?;
+ if cookies.is_empty() {
+ return None;
+ }
+ let header = cookies
+ .iter()
+ .map(|cookie| format!("{}={}", cookie.name(), cookie.value()))
+ .collect::<Vec<_>>()
+ .join("; ");
+ HeaderValue::from_str(&header).ok()
+}
+#[command]
+pub async fn download_file(
+ window: WebviewWindow,
+ app: AppHandle,
+ params: DownloadFileParams,
+) -> Result<(), String> {
+ // Toast on the calling window (secondary windows included), not a hard-coded
+ // main-window label. Tauri injects the invoker as `window`.
show_toast(
&window,
&get_download_message_with_lang(MessageType::Start, params.language.clone()),
@@ -108,7 +129,10 @@ pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result
let url = Url::from_str(&params.url).map_err(|e| format!("Invalid URL: {}", e))?;
- let request = Request::new(Method::GET, url);
+ let mut request = Request::new(Method::GET, url.clone());
+ if let Some(cookie_header) = cookie_header_for_url(&window, &url) {
+ request.headers_mut().insert(COOKIE, cookie_header);
+ }
let response = client.execute(request).await;
@@ -195,12 +219,12 @@ pub fn set_dock_badge_label(app: AppHandle, label: Option<String>) -> Result<(),
#[command]
pub async fn update_theme_mode(app: AppHandle, mode: String) {
- if let Some(window) = app.get_webview_window("pake") {
- let theme = if mode == "dark" {
- Theme::Dark
- } else {
- Theme::Light
- };
+ let theme = if mode == "dark" {
+ Theme::Dark
+ } else {
+ Theme::Light
+ };
+ for window in app.webview_windows().values() {
let _ = window.set_theme(Some(theme));
}
}
diff --git a/src-tauri/src/app/menu.rs b/src-tauri/src/app/menu.rs
index 42b608a9..8287dff9 100644
--- a/src-tauri/src/app/menu.rs
+++ b/src-tauri/src/app/menu.rs
@@ -1,5 +1,9 @@
// Menu functionality is only used on macOS; the module is gated in app/mod.rs.
use crate::app::window::{open_additional_window_safe, MultiWindowState};
+use objc2::msg_send;
+use objc2::runtime::AnyObject;
+use std::io::Write;
+use std::process::{Command, Stdio};
use tauri::menu::{AboutMetadata, Menu, MenuItem, PredefinedMenuItem, Submenu};
use tauri::{AppHandle, Manager, WebviewWindow, Wry};
use tauri_plugin_opener::OpenerExt;
@@ -254,6 +258,45 @@ fn focused_webview_window(app_handle: &AppHandle) -> Option<WebviewWindow> {
.or_else(|| windows.get("pake").cloned())
}
+/// Drive WKWebView history without page JS. Blank error shells have no JS
+/// context, so `window.history.back()` via eval is a no-op exactly when the
+/// user is stuck (#1328 class).
+fn webview_history_step(window: &WebviewWindow, selector: SelName) {
+ let _ = window.with_webview(move |webview| {
+ let ptr = webview.inner() as *mut AnyObject;
+ if ptr.is_null() {
+ return;
+ }
+ unsafe {
+ match selector {
+ SelName::Back => {
+ let _: *mut AnyObject = msg_send![ptr, goBack];
+ }
+ SelName::Forward => {
+ let _: *mut AnyObject = msg_send![ptr, goForward];
+ }
+ }
+ }
+ });
+}
+
+enum SelName {
+ Back,
+ Forward,
+}
+
+/// Copy text via pbcopy so it works when the page has no JS context (error
+/// shells) and when the Clipboard API is blocked by the site CSP.
+fn copy_text_to_pasteboard(text: &str) {
+ let Ok(mut child) = Command::new("pbcopy").stdin(Stdio::piped()).spawn() else {
+ return;
+ };
+ if let Some(stdin) = child.stdin.as_mut() {
+ let _ = stdin.write_all(text.as_bytes());
+ }
+ let _ = child.wait();
+}
+
pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
match id {
"new_window" => {
@@ -266,7 +309,8 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
}
"reload" => {
if let Some(window) = focused_webview_window(app_handle) {
- let _ = window.eval("window.location.reload()");
+ // Native reload works on blank error pages where eval cannot.
+ let _ = window.reload();
}
}
"toggle_devtools" => {
@@ -296,12 +340,12 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
}
"go_back" => {
if let Some(window) = focused_webview_window(app_handle) {
- let _ = window.eval("window.history.back()");
+ webview_history_step(&window, SelName::Back);
}
}
"go_forward" => {
if let Some(window) = focused_webview_window(app_handle) {
- let _ = window.eval("window.history.forward()");
+ webview_history_step(&window, SelName::Forward);
}
}
"go_home" => {
@@ -321,7 +365,11 @@ pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {
}
"copy_url" => {
if let Some(window) = focused_webview_window(app_handle) {
- let _ = window.eval("navigator.clipboard.writeText(window.location.href)");
+ // Prefer the native webview URL so copy still works on error
+ // pages that have no document.location / clipboard API.
+ if let Ok(url) = window.url() {
+ copy_text_to_pasteboard(url.as_str());
+ }
}
}
"paste_and_match_style" => {
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 4efcb937..df239d97 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -186,15 +186,21 @@ fn open_requested_window(
Ok(window)
}
+/// Open a multi-window clone of the home app. The window is built hidden and
+/// revealed on its first real page load (see `lib.rs` on_page_load) so Cmd+N
+/// does not flash an empty shell the way the main window used to.
pub fn open_additional_window_safe(app: &AppHandle) {
#[cfg(target_os = "windows")]
{
let app_handle = app.clone();
std::thread::spawn(move || {
if let Ok(window) = open_additional_window(&app_handle) {
- let _ = window.show();
- reapply_window_icon(&window);
- let _ = window.set_focus();
+ // Fallback if PageLoadEvent::Finished never arrives.
+ let fallback = window.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(tokio::time::Duration::from_millis(3_000)).await;
+ reveal_built_window(&fallback);
+ });
}
});
}
@@ -202,13 +208,26 @@ pub fn open_additional_window_safe(app: &AppHandle) {
#[cfg(not(target_os = "windows"))]
{
if let Ok(window) = open_additional_window(app) {
- let _ = window.show();
- reapply_window_icon(&window);
- let _ = window.set_focus();
+ let fallback = window.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(tokio::time::Duration::from_millis(3_000)).await;
+ reveal_built_window(&fallback);
+ });
}
}
}
+/// Show a window that was built hidden once content is ready (or the fallback
+/// timer fires). No-ops when already visible so page-load and fallback can race.
+pub fn reveal_built_window(window: &WebviewWindow) {
+ if window.is_visible().unwrap_or(true) {
+ return;
+ }
+ let _ = window.show();
+ reapply_window_icon(window);
+ let _ = window.set_focus();
+}
+
fn build_window_with_label(
app: &AppHandle,
config: &PakeConfig,
@@ -553,7 +572,7 @@ fn build_window(
// catching it here is independent of the page CSP and the IPC channel.
{
let download_handle = app.clone();
- window_builder = window_builder.on_download(move |_webview, event| match event {
+ window_builder = window_builder.on_download(move |webview, event| match event {
DownloadEvent::Requested { url, destination } => {
match download_handle.path().download_dir() {
Ok(download_dir) => {
@@ -585,7 +604,12 @@ fn build_window(
path: _,
success,
} => {
- if let Some(window) = download_handle.get_webview_window("pake") {
+ // Toast on the window that started the download (including
+ // secondary multi-window labels), not a hard-coded "pake".
+ let toast_window = download_handle
+ .get_webview_window(webview.label())
+ .or_else(|| download_handle.get_webview_window("pake"));
+ if let Some(window) = toast_window {
let message_type = if success {
MessageType::Success
} else {
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 8dc757b4..cc1f2282 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -370,34 +370,12 @@ const DOWNLOADABLE_FILE_EXTENSIONS = {
"apk",
"ipa",
],
- data: [
- "json",
- "xml",
- "csv",
- "sql",
- "db",
- "sqlite",
- "yaml",
- "yml",
- "toml",
- "ini",
- "cfg",
- "conf",
- "log",
- ],
- code: [
- "js",
- "ts",
- "jsx",
- "tsx",
- "css",
- "scss",
- "sass",
- "less",
- "sh",
- "bat",
- "ps1",
- ],
+ // Navigable web formats (json/xml/js/css/html and friends) are intentionally
+ // omitted: documentation and SPA content negotiation often serve them as
+ // in-app pages. Real file downloads still match via the download attribute,
+ // ?download / ?attachment, or binary extensions below.
+ data: ["csv", "sql", "db", "sqlite"],
+ scripts: ["sh", "bat", "ps1"],
fonts: ["ttf", "otf", "woff", "woff2", "eot"],
design: ["ai", "psd", "sketch", "fig", "xd"],
system: [
@@ -446,12 +424,12 @@ const PREVIEWABLE_MEDIA_EXTENSIONS = [
"m4a",
];
-// Path fragments that often host real file downloads. Do not add broad static
-// asset roots such as "/assets/" or "/dist/": many SPAs use those as in-app
-// routes (e.g. MEXC /assets/future) and would be intercepted as downloads.
-// Extensionless links under these paths still match; prefer real extensions,
-// download attributes, or ?download / ?attachment query hints when possible.
-const DOWNLOAD_PATH_PATTERNS = ["/download/", "/files/", "/attachments/"];
+// Path fragments that often host real file downloads. Keep this list narrow:
+// SPA roots such as "/assets/", "/dist/", "/files/", "/releases/", and
+// "/attachments/" have already been mistaken for downloads in the wild.
+// Prefer real file extensions, the download attribute, or ?download /
+// ?attachment query hints whenever possible.
+const DOWNLOAD_PATH_PATTERNS = ["/download/"];
// Language detection utilities
function getUserLanguage() {
@@ -527,6 +505,52 @@ function isDownloadableFile(url) {
}
}
+// Public suffixes where the registrable domain needs more than two labels.
+// Not exhaustive; covers common packaging targets that last-two-label
+// matching would collapse incorrectly (e.g. amazon.co.uk vs evil.co.uk,
+// or every *.github.io site into one "domain").
+const MULTI_PART_PUBLIC_SUFFIXES = [
+ "co.uk",
+ "org.uk",
+ "ac.uk",
+ "gov.uk",
+ "com.au",
+ "net.au",
+ "org.au",
+ "co.jp",
+ "ne.jp",
+ "or.jp",
+ "co.kr",
+ "co.in",
+ "com.br",
+ "com.cn",
+ "com.tw",
+ "com.hk",
+ "com.sg",
+ "github.io",
+ "gitlab.io",
+ "pages.dev",
+];
+
+function getRootDomain(hostname) {
+ const normalized = String(hostname || "").toLowerCase();
+ if (!normalized) {
+ return "";
+ }
+
+ const parts = normalized.split(".").filter(Boolean);
+ if (parts.length <= 1) {
+ return normalized;
+ }
+
+ const lastTwo = parts.slice(-2).join(".");
+ if (MULTI_PART_PUBLIC_SUFFIXES.includes(lastTwo) && parts.length >= 3) {
+ return parts.slice(-3).join(".");
+ }
+
+ return lastTwo;
+}
+
function normalizeAnchorHref(rawHref) {
return typeof rawHref === "string" ? rawHref.trim() : "";
}
@@ -660,8 +684,11 @@ document.addEventListener("DOMContentLoaded", () => {
const isSpecialDownload = (url) =>
["blob", "data"].some((protocol) => url.startsWith(protocol));
- const isDownloadRequired = (url, anchorElement, e) =>
- anchorElement.download || e.metaKey || e.ctrlKey || isDownloadableFile(url);
+ // Cmd/Ctrl+click is a browser "open related" gesture, not "save as".
+ // Only the download attribute and downloadable-file heuristics force a
+ // download; modifiers must not rewrite ordinary navigation.
+ const isDownloadRequired = (url, anchorElement, _e) =>
+ Boolean(anchorElement.download) || isDownloadableFile(url);
const handleExternalLink = (url) => {
// Don't try to open blob: or data: URLs with shell
@@ -685,12 +712,8 @@ document.addEventListener("DOMContentLoaded", () => {
if (linkUrl.hostname === currentUrl.hostname) return true;
- // Extract root domain (e.g., bilibili.com from www.bilibili.com)
- const getRootDomain = (hostname) => {
- const parts = hostname.split(".");
- return parts.length >= 2 ? parts.slice(-2).join(".") : hostname;
- };
-
+ // e.g. www.bilibili.com and m.bilibili.com share bilibili.com;
+ // amazon.co.uk must not share a root with evil.co.uk.
return (
getRootDomain(currentUrl.hostname) === getRootDomain(linkUrl.hostname)
);
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 73740426..daa637dd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -31,7 +31,10 @@ use app::{
set_dock_badge_label, set_zoom, update_theme_mode,
},
setup::{set_global_shortcut, set_system_tray},
- window::{open_additional_window_safe, reapply_window_icon, set_window, MultiWindowState},
+ window::{
+ open_additional_window_safe, reapply_window_icon, reveal_built_window, set_window,
+ MultiWindowState,
+ },
};
use util::get_pake_config;
@@ -244,16 +247,14 @@ pub fn run_app() {
));
}
- // Reveal the main window after the first real document finishes loading so
+ // Reveal hidden windows after the first real document finishes loading so
// slow WKWebView cold starts do not expose an empty but interactive shell.
- // start_to_tray keeps the window hidden for the whole session until the user
- // opens it from the tray / shortcut.
- if !start_to_tray {
+ // - Main label "pake": once-only latch + start_to_tray opt-out.
+ // - Secondary multi-window labels ("pake-N"): reveal if still hidden (Cmd+N).
+ // start_to_tray keeps the main window hidden until the user opens it.
+ {
let page_load_revealed = startup_window_revealed.clone();
app_builder = app_builder.on_page_load(move |webview, payload| {
- if webview.label() != "pake" {
- return;
- }
if !matches!(payload.event(), PageLoadEvent::Finished) {
return;
}
@@ -262,8 +263,24 @@ pub fn run_app() {
if is_placeholder_startup_url(payload.url()) {
return;
}
- if let Some(window) = webview.app_handle().get_webview_window("pake") {
- reveal_startup_window(window, init_fullscreen, &page_load_revealed);
+
+ let label = webview.label();
+ if label == "pake" {
+ if start_to_tray {
+ return;
+ }
+ if let Some(window) = webview.app_handle().get_webview_window("pake") {
+ reveal_startup_window(window, init_fullscreen, &page_load_revealed);
+ }
+ return;
+ }
+
+ // Multi-window clones (pake-1, pake-2, …) built hidden by
+ // open_additional_window_safe.
+ if label.starts_with("pake-") {
+ if let Some(window) = webview.app_handle().get_webview_window(label) {
+ reveal_built_window(&window);
+ }
}
});
}
diff --git a/tests/unit/download-http-status.test.ts b/tests/unit/download-http-status.test.ts
index 22ef916f..2e843031 100644
--- a/tests/unit/download-http-status.test.ts
+++ b/tests/unit/download-http-status.test.ts
@@ -25,15 +25,33 @@ describe('download HTTP status handling', () => {
expect(createIdx).toBeGreaterThan(statusIdx);
});
- it('no longer treats /assets/ as a download path heuristic', () => {
+ it('keeps download path heuristics narrow (no SPA roots)', () => {
const patternsBlock = eventSource.match(
/const DOWNLOAD_PATH_PATTERNS = \[([\s\S]*?)\];/,
)?.[1];
expect(patternsBlock).toBeTruthy();
expect(patternsBlock).not.toContain('/assets/');
expect(patternsBlock).not.toContain('/dist/');
+ expect(patternsBlock).not.toContain('/files/');
+ expect(patternsBlock).not.toContain('/attachments/');
+ expect(patternsBlock).not.toContain('/releases/');
expect(patternsBlock).toContain('/download/');
- expect(patternsBlock).toContain('/files/');
- expect(patternsBlock).toContain('/attachments/');
+ });
+
+ it('toasts download progress on the calling window, not a hard-coded main label', () => {
+ // The command must accept the invoker WebviewWindow so secondary windows
+ // see their own toast instead of failing with "Window not found".
+ const downloadFn = invokeSource.slice(
+ invokeSource.indexOf('pub async fn download_file'),
+ invokeSource.indexOf('pub fn send_notification'),
+ );
+ expect(downloadFn).toMatch(/window: WebviewWindow/);
+ expect(downloadFn).not.toContain('get_webview_window("pake")');
+ });
+
+ it('attaches webview cookies to authenticated HTTP downloads', () => {
+ expect(invokeSource).toContain('cookie_header_for_url');
+ expect(invokeSource).toContain('cookies_for_url');
+ expect(invokeSource).toContain('COOKIE');
});
});
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index ebf0cd0e..42ae7e84 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -266,17 +266,96 @@ describe("event link guard", () => {
expect(isDownloadableFile("https://example.com/download/export")).toBe(
true,
);
+ // Real files under /files/ still match by extension, not the path root.
expect(isDownloadableFile("https://example.com/files/report.pdf")).toBe(
true,
);
});
+ it("does not treat /files/ SPA routes without a file extension as downloads", () => {
+ const { isDownloadableFile } = loadEventHelpers();
+
+ expect(isDownloadableFile("https://drive.example.com/files/inbox")).toBe(
+ false,
+ );
+ expect(
+ isDownloadableFile("https://app.example.com/attachments/latest"),
+ ).toBe(false);
+ });
+
it("does not treat static /dist/ SPA paths as downloads without a file extension", () => {
const { isDownloadableFile } = loadEventHelpers();
expect(isDownloadableFile("https://example.com/dist/app")).toBe(false);
});
+ it("does not force-download ordinary links on Cmd/Ctrl+click", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ runDomReady(context);
+
+ const event = makeClickEvent(
+ makeAnchor("https://example.com/app/settings", "_self"),
+ );
+ event.metaKey = true;
+ event.ctrlKey = true;
+ getClickGuard(context)(event);
+
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(context.invokeCalls).not.toContainEqual([
+ "download_file",
+ expect.anything(),
+ ]);
+ });
+
+ it("still downloads when the anchor has a download attribute", () => {
+ const context = loadEventHelpers({ withTauri: true });
+ runDomReady(context);
+
+ const anchor = makeAnchor("https://example.com/app/settings", "_self");
+ anchor.download = "settings.html";
+ const event = makeClickEvent(anchor);
+ getClickGuard(context)(event);
+
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(context.invokeCalls).toContainEqual([
+ "download_file",
+ {
+ params: {
+ url: "https://example.com/app/settings",
+ filename: "settings.html",
+ language: "en-US",
+ },
+ },
+ ]);
+ });
+
+ it("does not treat navigable web formats as downloads by extension alone", () => {
+ const { isDownloadableFile } = loadEventHelpers();
+
+ expect(isDownloadableFile("https://example.com/api/config.json")).toBe(
+ false,
+ );
+ expect(isDownloadableFile("https://example.com/docs/app.js")).toBe(false);
+ expect(isDownloadableFile("https://example.com/theme.css")).toBe(false);
+ // Binary / archive extensions still download.
+ expect(isDownloadableFile("https://example.com/report.pdf")).toBe(true);
+ expect(isDownloadableFile("https://example.com/pkg.zip")).toBe(true);
+ });
+
+ it("scopes root domains correctly for multi-part public suffixes", () => {
+ const { getRootDomain } = loadEventHelpers();
+
+ expect(getRootDomain("www.amazon.co.uk")).toBe("amazon.co.uk");
+ expect(getRootDomain("evil.co.uk")).toBe("evil.co.uk");
+ expect(getRootDomain("www.amazon.co.uk")).not.toBe(
+ getRootDomain("evil.co.uk"),
+ );
+ expect(getRootDomain("alice.github.io")).toBe("alice.github.io");
+ expect(getRootDomain("bob.github.io")).toBe("bob.github.io");
+ expect(getRootDomain("m.bilibili.com")).toBe("bilibili.com");
+ expect(getRootDomain("www.bilibili.com")).toBe("bilibili.com");
+ });
+
it("navigates macOS auth URLs in the current window", () => {
const { openAuthNavigation, window } = loadEventHelpers({
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_5)",
diff --git a/tests/unit/menu-focused-window.test.ts b/tests/unit/menu-focused-window.test.ts
index 1880aed1..28868c3b 100644
--- a/tests/unit/menu-focused-window.test.ts
+++ b/tests/unit/menu-focused-window.test.ts
@@ -3,16 +3,32 @@ import path from 'node:path';
import { describe, expect, it } from 'vitest';
describe('macOS menu window targeting', () => {
- it('routes window commands through the focused webview helper', () => {
- const source = fs.readFileSync(
- path.join(process.cwd(), 'src-tauri/src/app/menu.rs'),
- 'utf8',
- );
- const handler = source.slice(source.indexOf('pub fn handle_menu_click'));
+ const source = fs.readFileSync(
+ path.join(process.cwd(), 'src-tauri/src/app/menu.rs'),
+ 'utf8',
+ );
+ const handler = source.slice(source.indexOf('pub fn handle_menu_click'));
+ it('routes window commands through the focused webview helper', () => {
expect(source).toContain('fn focused_webview_window');
expect(source).toContain('window.is_focused()');
expect(handler).not.toContain('get_webview_window("pake")');
expect(handler).toContain('focused_webview_window(app_handle)');
});
+
+ it('uses native reload and history so error pages stay operable', () => {
+ // Blank WebView error shells have no JS context; eval-based navigation
+ // is a no-op exactly when the user is stuck (#1328 class).
+ expect(handler).toContain('window.reload()');
+ expect(handler).not.toContain('window.location.reload()');
+ expect(handler).toContain('webview_history_step');
+ expect(handler).not.toContain('window.history.back()');
+ expect(handler).not.toContain('window.history.forward()');
+ });
+
+ it('copies the native webview URL without requiring page JS', () => {
+ expect(handler).toContain('window.url()');
+ expect(handler).toContain('copy_text_to_pasteboard');
+ expect(handler).not.toContain('navigator.clipboard.writeText(window.location.href)');
+ });
});
diff --git a/tests/unit/startup-window-reveal.test.ts b/tests/unit/startup-window-reveal.test.ts
index cd38a51a..87cbc85b 100644
--- a/tests/unit/startup-window-reveal.test.ts
+++ b/tests/unit/startup-window-reveal.test.ts
@@ -18,9 +18,11 @@ describe('startup window reveal', () => {
expect(libSource).toContain('claim_startup_reveal');
expect(libSource).toContain('STARTUP_WINDOW_FALLBACK_DELAY');
expect(libSource).toContain('is_placeholder_startup_url');
- expect(libSource).toMatch(
- /if !start_to_tray \{[\s\S]*?app_builder = app_builder\.on_page_load/,
- );
+ // Main window still respects start_to_tray; secondary multi-window labels
+ // share the same page-load hook via reveal_built_window.
+ expect(libSource).toContain('if start_to_tray');
+ expect(libSource).toContain('reveal_built_window');
+ expect(libSource).toContain('label.starts_with("pake-")');
expect(libSource).not.toContain('WINDOW_SHOW_DELAY');
});
diff --git a/tests/unit/window-icon-reapply.test.ts b/tests/unit/window-icon-reapply.test.ts
index f4719b22..473513b8 100644
--- a/tests/unit/window-icon-reapply.test.ts
+++ b/tests/unit/window-icon-reapply.test.ts
@@ -28,7 +28,11 @@ describe('Windows taskbar icon reapplication', () => {
(show.index ?? 0) + show[0].length,
(show.index ?? 0) + show[0].length + 160,
);
- expect(followingSource).toContain(`reapply_window_icon(&${show[1]});`);
+ // Accept both reapply_window_icon(&window) and reapply_window_icon(window)
+ // when the binding is already a reference (reveal_built_window).
+ expect(followingSource).toMatch(
+ new RegExp(`reapply_window_icon\\(&?${show[1]}\\);`),
+ );
}
}
});