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: hold a new-tab link that has no address when the click begins

Tw9339aeb9f84007
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.md
index 45259290..ed7fd227 100644
--- a/.claude/rules/tauri-runtime.md
+++ b/.claude/rules/tauri-runtime.md
@@ -22,7 +22,7 @@ paths:
- A popup's page closes it with `window.close()`. WKWebView closes nothing for that call unless its UI delegate implements `webViewDidClose:`, which Wry's does not; `src-tauri/src/app/popup_close.rs` closes the window, and only for windows a page opened (`page_popup`), since WebKit sends the same message for a main window whose page calls `window.close()`. WebView2 raises `WindowCloseRequested`, which Wry answers by destroying only the web view's container, so the Windows arm in `build_window` closes the window too (measured in a Windows 11 VM: the popup had answered its opener and stayed on screen titled `callback`). On Linux the window stays with its web view destroyed, as before. On macOS the timing is load-bearing twice. WebKit cancels a closing page's requests, a callback page closes in its first script, and Tauri's notification plugin has an IPC call out in every document (`is_permission_granted`); the answer to a cancelled `ipc://` request makes WebKit raise, and under the release profile's old `panic = "abort"` Wry's `objc2::exception::catch` could not hold, so the whole app quit on every sign-in (measured on macOS 26.7; with `panic = "unwind"` the same run passed, at 2.0 MB more per architecture, 11.8 to 13.8 MB). So `event.js` delays every top-level page's own `window.close()` by `WINDOW_CLOSE_DELAY_MS` (every page, because a `noopener` popup has no `window.opener` to tell it by; in the main window it is a precaution, since a self-closing first page there did not abort in three runs without it), and the native side hides the window at once and destroys it after `CLOSE_GRACE`, because destroying the web view cancels requests too. Not covered: an opener that closes a cross-origin popup calls the engine's own `close`, a page that navigates within the delay after `close()` loses the close, and the same abort is possible wherever a page with an IPC call in flight is torn down. Page-opened popups take `pake-popup-N` labels (`POPUP_WINDOW_LABEL_PREFIX`) and the window-state plugin filters them out, so a popup opens at the size its page asked for and a Cmd+N window never inherits one. Verify on a real bundle with `tests/integration/signin-popup-server.mjs`, whose app pages send that opener policy: each of its three buttons must end with the app's page in place, the answer received, the popup gone and the app still running, several times in a row, and its `/selfclose` page must leave the main window open.
- A WKWebView whose web content process dies goes white and stays white, with no URL. `recovery.rs` reloads it from Tauri's `on_web_content_process_terminate` hook, set in `lib.rs`, at most `MAX_RELOADS` times in `RELOAD_WINDOW` as on Windows and Linux. The hook must stay set: without one Tauri 2.12 reloads every time with no limit, and when Pake still replaced Wry's delegate method and called the original first (the route under Tauri 2.10, which passed no handler down), the upgrade made the third death in a minute reload as well (measured on a real bundle, 2026-11-18). Read a window's address only through `page_url`: Wry's getter unwrapped WKWebView's `URL` through 0.54.2, which is nil for such a web view, and the panic aborted the app under `panic = "abort"`; Wry 0.57 returns an error instead, and `page_url` stays the one reader, asking the web view first. A user's X app went white and then crashed on Cmd+Q, in `save_last_url` on `RunEvent::Exit` (2026-11-18); `page_url` in `window.rs` asks the web view first and is the only reader. Verify on a real bundle by killing the app's own `com.apple.WebKit.WebContent` process (the one that appears after launch): the page comes back twice, the third time it stays white, and quitting then leaves no crash report.
- Auth routing matches provider hostnames and endpoint-shaped paths separately, never query strings or fragments. Tracking links carrying a login URL must still open externally. Cover main-page and subframe clicks in `tests/browser/popup-routing.mjs`; classifier-only tests do not prove routing.
-- tauri-plugin-shell and tauri-plugin-opener each ship a click listener of their own in every page: shell's, on `body`, opens any `a[target="_blank"]` with an http(s) address in the system browser and never asks whether the page prevented the click; opener's, on `window`, does ask. So an internal `target="_blank"` link must not still read `_blank` when the click bubbles. `detectAnchorElementClick` retargets it to `_self` under every setting; with `--new-window` it puts `_blank` back after the click and `openUnhandledBlankLink`, last in the bubble on `window`, opens the in-app window only when nobody prevented the click. Left as `_blank` under `--new-window`, a link the page handled itself went to the browser as well (Douyin's episode list, whose links carry `href="undefined"`: every switch opened douyin.com/undefined, a user's report, 2026-11-18), and a plain internal new-tab link opened in the browser instead of the app. `tests/browser/popup-routing.mjs` models the shell listener; verify on a real bundle that a handled link opens nothing and an unhandled one opens a second window, with no request from a browser at the fixture server.
+- tauri-plugin-shell and tauri-plugin-opener each ship a click listener of their own in every page: shell's, on `body`, opens any `a[target="_blank"]` with an http(s) address in the system browser and never asks whether the page prevented the click; opener's, on `window`, does ask. So an internal `target="_blank"` link must not still read `_blank` when the click bubbles. `detectAnchorElementClick` retargets it to `_self` under every setting; with `--new-window` it puts `_blank` back after the click and `openUnhandledBlankLink`, last in the bubble on `window`, opens the in-app window only when nobody prevented the click. Left as `_blank` under `--new-window`, a link the page handled itself went to the browser as well (the first reading of Douyin's episode list, a user's report, 2026-11-18), and a plain internal new-tab link opened in the browser instead of the app. That fix did not reach the user: read on the real page with a probe, Douyin's covers are `<a target="_blank">` with no `href` when the click begins, the page's own handler sets `href` to `"undefined"` during the click and prevents it, and the guard skipped a link with no address, under every setting. So the guard also holds a `_blank` link with no address (`holdAddresslessNewTabLink`): the target is `_self` for the click, and `openUnhandledBlankLink` routes the link at the end of the bubble if it got an address and nobody handled it (`routeLateNewTabLink`). The rule is about what the link reads in the bubble, not at the start: reproduce a report on the site itself before modelling it. `tests/browser/popup-routing.mjs` models the shell listener; verify on a real bundle that a handled link opens nothing and an unhandled one opens a second window, with no request from a browser at the fixture server.
- Blank/two-stage popups need a real WindowProxy, not the main window. Normalize omitted/empty URLs to `about:blank` in both JS entry points: Tauri through 2.10 rejected WebKit's empty URL before calling `on_new_window` (2.12 maps it to `about:blank` itself, so the JS side is now a second guard). The default native handler must create a managed blank popup with Pake's download delegate even without `--new-window`; `NewWindowResponse::Allow` does not provide that delegate. Verify actual macOS attachment bytes and preservation of the main URL, not only Chromium popup creation.
- `--download-dir` / `downloadDir` is embedded as trusted `pake.download_dir`, shared by native and IPC downloads through `get_download_dir`. Empty means system Downloads; quoted `~/path` expands against the runtime user home. Reject relative paths and absolute tilde suffixes, create missing directories on download, and surface directory creation plus file open/write failures without redirecting to another folder. Do not accept a directory from remote-page IPC arguments.
- Do not open a synchronous native save dialog inside `on_download(Requested)`. Wry (through 0.57.2) holds a `RefCell` mutable borrow across that callback; a modal panel allows another download callback to reenter and panic. A native two-download probe reproduced this with 100 ms and 500 ms spacing. The macOS completion event also omits the destination path, so URL-only bookkeeping cannot safely identify concurrent downloads of the same URL.
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index d2929cf2..39f6dffd 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -321,6 +321,30 @@ mod popup_tests {
assert!(script.contains("window.addEventListener(\"click\", openUnhandledBlankLink);"));
}
+ #[test]
+ fn a_new_tab_link_without_an_address_never_bubbles_as_blank() {
+ // Douyin's episode covers have no href when the click begins and get
+ // "undefined" from the page's own handler during it. The click guard
+ // must take the _blank target away before it looks for an address, or
+ // tauri-plugin-shell's listener opens that address in the browser.
+ let script = include_str!("../inject/event.js").replace("\r\n", "\n");
+ let held = script
+ .find("!anchorElement.href &&\n anchorElement.target === \"_blank\"")
+ .expect("a link with no address is looked at");
+ let with_address = script
+ .find("if (anchorElement && anchorElement.href) {")
+ .expect("links with an address follow");
+ assert!(held < with_address);
+ let hold = script
+ .find("const holdAddresslessNewTabLink = (e, anchorElement) => {")
+ .expect("the link is held for the click");
+ let retarget = script[hold..]
+ .find("anchorElement.target = \"_self\";")
+ .expect("its new-tab target is taken away");
+ assert!(retarget < 120);
+ assert!(script.contains("routeLateNewTabLink(e, pending.anchor);"));
+ }
+
#[test]
fn a_site_sees_no_tauri_global_api_and_the_users_own_code_keeps_the_name() {
// DeepSeek reads `"__TAURI__" in window` and warns of an abnormal
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 0e2eac60..9aa70c24 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -875,8 +875,61 @@ document.addEventListener("DOMContentLoaded", () => {
const pending = pendingBlankLink;
pendingBlankLink = null;
if (!pending || pending.event !== e || e.defaultPrevented) return;
+ if (pending.url) {
+ e.preventDefault();
+ originalWindowOpen.call(window, pending.url, "_blank");
+ return;
+ }
+ routeLateNewTabLink(e, pending.anchor);
+ };
+
+ // A held link got its address during the click and nobody handled it: route
+ // it now as the click guard would have at the start. An internal address
+ // without --new-window is left to the default action, which follows the
+ // link's _self target inside the app.
+ const routeLateNewTabLink = (e, anchorElement) => {
+ let lateUrl;
+ try {
+ lateUrl = new URL(anchorElement.href);
+ } catch (error) {
+ return;
+ }
+ if (!["http:", "https:"].includes(lateUrl.protocol)) return;
+ const absoluteUrl = lateUrl.href;
+ if (forceInternalNavigation || window.isAuthLink(absoluteUrl)) {
+ e.preventDefault();
+ window.location.href = absoluteUrl;
+ return;
+ }
+ if (isInternalUrl(absoluteUrl)) {
+ if (window.pakeConfig?.new_window) {
+ e.preventDefault();
+ originalWindowOpen.call(window, absoluteUrl, "_blank");
+ }
+ return;
+ }
e.preventDefault();
- originalWindowOpen.call(window, pending.url, "_blank");
+ handleExternalLink(absoluteUrl);
+ };
+
+ // A new-tab link with no address yet. Some pages give the link its address
+ // during the click and handle the click themselves: Douyin's episode covers
+ // are <a target="_blank"> with no href, their own handler sets the href to
+ // "undefined", switches the video and prevents the default. The click guard
+ // skipped a link with no address, so it kept its _blank target through the
+ // bubble, where Tauri's shell plugin opens whatever address the link has by
+ // then, handled or not: the browser came up at douyin.com/undefined on every
+ // switch, with or without --new-window (the same user's second report,
+ // 2026-11-19; the first fix only held links that had an address when the
+ // click began). The target is taken away for the click, and
+ // openUnhandledBlankLink routes the link if nobody handled it.
+ const holdAddresslessNewTabLink = (e, anchorElement) => {
+ const askedFor = anchorElement.target;
+ anchorElement.target = "_self";
+ pendingBlankLink = { event: e, anchor: anchorElement, url: null };
+ setTimeout(() => {
+ anchorElement.target = askedFor;
+ }, 0);
};
// An internal link that asks for a new tab (target _blank or _new).
@@ -921,6 +974,15 @@ document.addEventListener("DOMContentLoaded", () => {
if (anchorElement && nativeDownloadAnchors.has(anchorElement)) return;
+ if (
+ anchorElement &&
+ !anchorElement.href &&
+ anchorElement.target === "_blank"
+ ) {
+ holdAddresslessNewTabLink(e, anchorElement);
+ return;
+ }
+
if (anchorElement && anchorElement.href) {
const rawHref = anchorElement.getAttribute("href") || "";
if (shouldBypassPakeLinkHandling(rawHref)) {
diff --git a/tests/browser/popup-routing.mjs b/tests/browser/popup-routing.mjs
index 0c0a02a3..e341c522 100644
--- a/tests/browser/popup-routing.mjs
+++ b/tests/browser/popup-routing.mjs
@@ -216,6 +216,45 @@ test("a new-window link the page handled itself opens nothing", async () => {
);
});
+for (const newWindow of [false, true]) {
+ test(`a new-tab link that gets its address during a handled click opens nothing (new_window ${newWindow})`, async () => {
+ // Douyin's episode covers as they are on the page: no href when the click
+ // begins, "undefined" once their own handler has run and prevented it.
+ await fixture(
+ false,
+ async (page, target, context) => {
+ await page.evaluate(() => {
+ document.body.innerHTML =
+ '<div id="root"><a id="episode" target="_blank"><span>Episode 2</span></a></div>';
+ window.switched = 0;
+ document.querySelector("#root").addEventListener("click", (event) => {
+ document.querySelector("#episode").href = undefined;
+ event.preventDefault();
+ window.switched += 1;
+ });
+ });
+ let popups = 0;
+ context.on("page", () => (popups += 1));
+ await page.locator("#episode span").click();
+ await page.waitForTimeout(300);
+ assert.equal(await page.evaluate(() => window.switched), 1);
+ assert.equal(
+ await page.evaluate(() => document.querySelector("#episode").href),
+ "https://mail.example.com/undefined",
+ );
+ assert.deepEqual(await page.evaluate(() => window.opened), []);
+ assert.equal(popups, 0);
+ assert.equal(page.url(), "https://mail.example.com/");
+ assert.equal(
+ await page.evaluate(() => document.querySelector("#episode").target),
+ "_blank",
+ );
+ },
+ { new_window: newWindow },
+ );
+ });
+}
+
test("a new-window link nobody handled opens in the app, not the browser", async () => {
await fixture(
false,
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index c74256a9..92177568 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -1121,6 +1121,98 @@ describe("event link guard", () => {
).toEqual([]);
});
+ const loadPageWithBubble = (newWindow) => {
+ vi.useFakeTimers();
+ const context = loadEventHelpers({ withTauri: true });
+ context.window.pakeConfig = { new_window: newWindow };
+ const nativeOpen = vi.fn(() => ({}));
+ context.window.open = nativeOpen;
+ runDomReady(context);
+ const lastInBubble = context.eventListeners.click.find(
+ ({ handler }) => handler.name === "openUnhandledBlankLink",
+ ).handler;
+ return { context, nativeOpen, lastInBubble };
+ };
+ const shellOpens = (context) =>
+ context.invokeCalls.filter(([cmd]) => cmd === "plugin:shell|open");
+
+ for (const newWindow of [false, true]) {
+ it(`takes the new-tab target off a link with no address for the click (new_window ${newWindow})`, () => {
+ // Douyin's episode covers: <a target="_blank"> with no href. Their own
+ // handler sets href to "undefined" during the click, switches the video
+ // and prevents the default. Left as _blank the link reached the shell
+ // plugin's listener, which opened douyin.com/undefined in the browser.
+ try {
+ const { context, nativeOpen, lastInBubble } =
+ loadPageWithBubble(newWindow);
+ const anchor = makeAnchor("", "_blank");
+ const event = { ...makeClickEvent(anchor), defaultPrevented: false };
+ getClickGuard(context)(event);
+ // What the shell plugin's listener would read in the bubble.
+ expect(anchor.target).toBe("_self");
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ // The page's handler: an address appears and the click is handled.
+ anchor.href = "https://example.com/undefined";
+ event.defaultPrevented = true;
+ lastInBubble(event);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(nativeOpen).not.toHaveBeenCalled();
+ expect(shellOpens(context)).toEqual([]);
+ vi.runAllTimers();
+ expect(anchor.target).toBe("_blank");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ }
+
+ it("routes a link that got an external address during the click, once", () => {
+ try {
+ const { context, nativeOpen, lastInBubble } = loadPageWithBubble(false);
+ const anchor = makeAnchor("", "_blank");
+ const event = { ...makeClickEvent(anchor), defaultPrevented: false };
+ getClickGuard(context)(event);
+ anchor.href = "https://other.example.org/page";
+ lastInBubble(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(shellOpens(context)).toHaveLength(1);
+ expect(nativeOpen).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps a link that got an internal address during the click in the app", () => {
+ try {
+ // Without --new-window the default action follows the _self target.
+ const off = loadPageWithBubble(false);
+ const stay = makeAnchor("", "_blank");
+ const first = { ...makeClickEvent(stay), defaultPrevented: false };
+ getClickGuard(off.context)(first);
+ stay.href = "https://example.com/video/2";
+ off.lastInBubble(first);
+ expect(first.preventDefault).not.toHaveBeenCalled();
+ expect(shellOpens(off.context)).toEqual([]);
+ expect(off.nativeOpen).not.toHaveBeenCalled();
+ vi.useRealTimers();
+
+ // With it the link opens in an app window.
+ const on = loadPageWithBubble(true);
+ const open = makeAnchor("", "_blank");
+ const second = { ...makeClickEvent(open), defaultPrevented: false };
+ getClickGuard(on.context)(second);
+ open.href = "https://example.com/video/2";
+ on.lastInBubble(second);
+ expect(second.preventDefault).toHaveBeenCalledOnce();
+ expect(on.nativeOpen.mock.calls).toEqual([
+ ["https://example.com/video/2", "_blank"],
+ ]);
+ expect(shellOpens(on.context)).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("opens a new-window link nobody handled in an in-app window", () => {
try {
const { context, nativeOpen, lastInBubble } = loadNewWindowPage();