Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Seanaye/fix/native app open link (#8060)
Sean Aye56d2be4b2fd7
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 5043852c05..95ef5cd4b6 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -16,6 +16,7 @@"native:e2e:build": "bash tests/native/build.sh","native:e2e": "bash tests/native/run.sh","native:e2e:smoke": "bash tests/native/run.sh --smoke",+ "native:e2e:links": "bash tests/native/run.sh --links","native:e2e:fixtures": "bun test tests/native/fixtures","native:e2e:check": "tsc -p tests/native/tsconfig.json && tsc -p tests/native/tsconfig.browser.json","native:e2e:matrix": "bash tests/native/run.sh --matrix",diff --git a/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.test.tsx b/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.test.tsxnew file mode 100644index 0000000000..6588d1162a--- /dev/null+++ b/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.test.tsx@@ -0,0 +1,74 @@+import { cleanup, render, screen } from '@solidjs/testing-library';+import type { ParentProps } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@components/app/side-panel', () => ({+ SidePanel: {+ Footer: (props: ParentProps) => props.children,+ Section: () => null,+ Loading: () => null,+ },+ GithubPullRequestChecksContent: () => null,+}));+vi.mock('./PrLinkedWorkSection', () => ({ PrLinkedWorkSection: () => null }));+vi.mock('./PrAgentSessionsSection', () => ({+ PrAgentSessionsSection: () => null,+}));++import { PrSidePanelSections } from './PrSidePanelSections';++const pullRequest = {+ displayName: 'macro-inc/macro#7858',+ githubKey: 'macro-inc/macro#7858',+ number: 7858,+ owner: 'macro-inc',+ repo: 'macro',+ url: 'https://github.com/macro-inc/macro/pull/7858',+};++beforeEach(() => {+ vi.spyOn(window, 'open').mockReturnValue(null);+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('PR side-panel external link', () => {+ it.each([false, true])(+ 'uses native anchor semantics rather than a frontend opener (Tauri: %s)',+ (native) => {+ if (native) vi.stubGlobal('__TAURI_INTERNALS__', {});+ render(() => (+ <aside onClick={(event) => event.stopPropagation()}>+ <PrSidePanelSections enrichment={pullRequest} status="success" />+ </aside>+ ));+ const link = screen.getByRole('link', {+ name: pullRequest.displayName,+ });+ expect(link.getAttribute('href')).toBe(pullRequest.url);+ expect(link.getAttribute('target')).toBe('_blank');+ expect(link.getAttribute('rel')).toBe('noreferrer');++ for (const init of [+ { detail: 1 },+ { detail: 0 },+ { ctrlKey: true },+ { metaKey: true },+ { shiftKey: true },+ ]) {+ const event = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ ...init,+ });+ link.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ }+ expect(window.open).not.toHaveBeenCalled();+ }+ );+});diff --git a/apps/web/tauri/navigation_plugin/Cargo.toml b/apps/web/tauri/navigation_plugin/Cargo.tomlindex 192f99b3cc..90c665173e 100644--- a/apps/web/tauri/navigation_plugin/Cargo.toml+++ b/apps/web/tauri/navigation_plugin/Cargo.toml@@ -15,3 +15,6 @@ tauri-plugin-opener = "2"thiserror = { workspace = true }tracing = { workspace = true }url = { workspace = true }++[dev-dependencies]+tauri = { workspace = true, features = ["test"] }diff --git a/apps/web/tauri/navigation_plugin/src/lib.rs b/apps/web/tauri/navigation_plugin/src/lib.rsindex 1381d8c971..3b2e4144a8 100644--- a/apps/web/tauri/navigation_plugin/src/lib.rs+++ b/apps/web/tauri/navigation_plugin/src/lib.rs@@ -29,6 +29,9 @@ enum NavigationOutput<'a> {/// site — so the navigation is cancelled and re-emitted as a `navigate`/// event for the SPA router to handle in-place.AppLink(MacroScheme),+ /// Browser-only URLs and local files outside the allowed cache directory+ /// must not be handed to the operating system's URL handler.+ Blocked,}/// Payload of the `navigate` event consumed by the frontend router bridge.@@ -98,12 +101,23 @@ impl MacroNavigationPlugin {}match self.as_internal_url(url) {Ok(()) => NavigationOutput::Internal,+ Err(_)+ if matches!(+ url.scheme(),+ "about" | "blob" | "data" | "javascript" | "file"+ ) =>+ {+ NavigationOutput::Blocked+ }Err(external) => NavigationOutput::External(external),}}#[tracing::instrument(ret, level = tracing::Level::DEBUG, skip(self))]fn as_app_link(&self, url: &Url) -> Option<MacroScheme> {+ if url.scheme() == "macro" {+ return MacroScheme::new(url.clone()).ok();+ }if !is_app_link(self.app_link_hosts, url) {return None;}@@ -138,6 +152,63 @@ impl MacroNavigationPlugin {Err(ExternalUrl(Cow::Borrowed(url)))}}++ fn new_window_destination<'a>(&self, url: &'a Url) -> NavigationOutput<'a> {+ match self.get_destination(url) {+ // A relative/same-origin app link should use the SPA router, not+ // create a second webview or reload the existing app.+ NavigationOutput::Internal => MacroScheme::from_url(url)+ .map(NavigationOutput::AppLink)+ .unwrap_or(NavigationOutput::Blocked),+ destination => destination,+ }+ }++ /// Route desktop anchors and `window.open` requests at the webview boundary.+ /// Never create a popup webview: app links stay in the SPA and external URLs+ /// go to the system handler. Mobile keeps the opener plugin's JS fallback.+ pub fn on_new_window<R: Runtime>(+ &self,+ app: &tauri::AppHandle<R>,+ url: &Url,+ ) -> tauri::webview::NewWindowResponse<R> {+ self.dispatch(app, self.new_window_destination(url));+ tauri::webview::NewWindowResponse::Deny+ }++ /// Return true only when the current webview may load the URL itself.+ fn dispatch<R: Runtime>(+ &self,+ app: &tauri::AppHandle<R>,+ destination: NavigationOutput<'_>,+ ) -> bool {+ match destination {+ NavigationOutput::External(external_url) => {+ // Opening a URL can block (and Android disallows it on the UI thread).+ let app = app.clone();+ let url = external_url.0.into_owned();+ std::thread::spawn(move || {+ app.opener()+ .open_url(transform_external_url(url).as_str(), None::<&str>)+ .log_and_consume();+ });+ false+ }+ NavigationOutput::AppLink(scheme) => {+ app.emit(+ "navigate",+ NavigatePayload {+ path: scheme.path(),+ query: scheme.query().unwrap_or_default(),+ },+ )+ .log_and_consume();+ false+ }+ NavigationOutput::Internal => true,+ NavigationOutput::Blocked => false,+ }+ }}/// Whether `url` is an `http(s)://<host>/app...` link for one of `hosts`,@@ -209,38 +280,6 @@ impl<R: Runtime> Plugin<R> for MacroNavigationPlugin {}fn on_navigation(&mut self, webview: &tauri::Webview<R>, url: &tauri::Url) -> bool {- let dest = self.get_destination(url);-- match dest {- NavigationOutput::External(external_url) => {- // we are navigating somewhere external to the app- // open in system default browser- // spawn a detached thread to avoid blocking,- // on android this panics if called on the main thread- let app_handle = webview.app_handle().clone();- let url = external_url.0.into_owned();- std::thread::spawn(move || {- app_handle- .opener()- .open_url(transform_external_url(url).as_str(), None::<&str>)- .log_and_consume();- });- false- }- NavigationOutput::Internal => true,- NavigationOutput::AppLink(scheme) => {- webview- .app_handle()- .emit(- "navigate",- NavigatePayload {- path: scheme.path(),- query: scheme.query().unwrap_or_default(),- },- )- .log_and_consume();- false- }- }+ self.dispatch(webview.app_handle(), self.get_destination(url))}}diff --git a/apps/web/tauri/navigation_plugin/src/tests.rs b/apps/web/tauri/navigation_plugin/src/tests.rsindex c4e6c30c08..c03227cbda 100644--- a/apps/web/tauri/navigation_plugin/src/tests.rs+++ b/apps/web/tauri/navigation_plugin/src/tests.rs@@ -121,6 +121,128 @@ fn get_destination_no_app_link_hosts_keeps_old_behavior() {));}+#[test]+fn popup_and_main_frame_share_external_url_policy() {+ let plugin = test_plugin();+ for input in [+ "https://github.com/macro-inc/macro/pull/7858",+ "http://example.com/",+ "mailto:[email protected]",+ "tel:+15551234567",+ "codex://new?prompt=hello",+ "cursor://anysphere.cursor-deeplink/prompt?text=hello",+ "zed://agent?prompt=hello",+ ] {+ let url = Url::parse(input).unwrap();+ for destination in [+ plugin.get_destination(&url),+ plugin.new_window_destination(&url),+ ] {+ match destination {+ NavigationOutput::External(external) => assert_eq!(external.0.as_ref(), &url),+ other => panic!("expected External for {url}, got {other:?}"),+ }+ }+ }+}++#[test]+fn popup_app_links_include_same_origin_and_macro_scheme() {+ let plugin = test_plugin();+ for input in [+ "https://macro.com/app/mail?view=all",+ "https://dev.macro.com/app/mail?view=all",+ "https://www.macro.com/app/mail?view=all",+ "macro:///mail?view=all",+ "tauri://localhost/app/mail?view=all",+ "http://tauri.localhost/app/mail?view=all",+ "http://localhost:3000/app/mail?view=all",+ ] {+ let url = Url::parse(input).unwrap();+ match plugin.new_window_destination(&url) {+ NavigationOutput::AppLink(scheme) => {+ assert_eq!(scheme.path(), "/mail", "{url}");+ assert_eq!(scheme.query(), Some("view=all"), "{url}");+ }+ other => panic!("expected AppLink for {url}, got {other:?}"),+ }+ }+}++#[test]+fn browser_only_urls_and_untrusted_local_files_are_blocked() {+ let plugin = test_plugin();+ for input in [+ "about:blank",+ "javascript:alert(1)",+ "data:text/html,test",+ "blob:tauri://localhost/123",+ "file:///etc/passwd",+ ] {+ let url = Url::parse(input).unwrap();+ assert!(+ matches!(plugin.get_destination(&url), NavigationOutput::Blocked),+ "{url}"+ );+ assert!(+ matches!(+ plugin.new_window_destination(&url),+ NavigationOutput::Blocked+ ),+ "{url}"+ );+ }+}++#[test]+fn popup_app_link_emits_once_and_never_creates_a_webview() {+ use std::sync::Mutex;+ use tauri::Listener;++ let app = tauri::test::mock_builder()+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .unwrap();+ let received = Arc::new(Mutex::new(Vec::new()));+ let events = received.clone();+ app.listen("navigate", move |event| {+ events+ .lock()+ .unwrap()+ .push(serde_json::from_str::<serde_json::Value>(event.payload()).unwrap());+ });++ let response = test_plugin().on_new_window(+ app.handle(),+ &Url::parse("https://macro.com/app/mail?view=all").unwrap(),+ );++ assert!(matches!(response, tauri::webview::NewWindowResponse::Deny));+ assert_eq!(+ *received.lock().unwrap(),+ vec![serde_json::json!({"path": "/mail", "query": "view=all"})],+ );+ assert!(app.webview_windows().is_empty());+}++#[test]+fn blocked_popup_neither_opens_nor_emits_navigation() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ use tauri::Listener;++ let app = tauri::test::mock_builder()+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .unwrap();+ let received = Arc::new(AtomicUsize::new(0));+ let events = received.clone();+ app.listen("navigate", move |_| {+ events.fetch_add(1, Ordering::Relaxed);+ });+ // No opener plugin is installed: browser-only URLs must never reach it.+ let response = test_plugin().on_new_window(app.handle(), &Url::parse("about:blank").unwrap());+ assert!(matches!(response, tauri::webview::NewWindowResponse::Deny));+ assert_eq!(received.load(Ordering::Relaxed), 0);+}+#[test]fn from_url_extracts_correct_path_from_universal_link() {let url = Url::parse("https://macro.com/app/component/doc123").unwrap();diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 1490d9d3cb..b4a5c3bf9d 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -155,6 +155,24 @@ pub fn run() {let embedded_bundle_build = embedded_bundle_build();let bundle_routes = BundleRoutes::new(embedded_bundle_build);let bundle_asset_resolver = BundleAssetResolver::new(bundle_routes.clone(), FileSystem);+ let context = tauri::generate_context!();+ #[cfg(desktop)]+ let (context, startup_windows) = {+ let mut context = context;+ // Install the popup handler before the first page loads. Leave mobile+ // window creation to Tauri and preserve all configured window options.+ let mut windows = Vec::new();+ for config in &mut context.config_mut().app.windows {+ if config.create {+ windows.push(config.clone());+ config.create = false;+ }+ }+ (context, windows)+ };+ let navigation = MacroNavigationPlugin::new(ALLOWED_DOMAINS)+ .expect("Domains must be valid urls")+ .with_app_link_hosts(APP_LINK_HOSTS);let mut builder = tauri::Builder::default();#[cfg(desktop)]@@ -210,12 +228,14 @@ pub fn run() {.merge_header_callback(Box::new(merge_header_callback)).build(),)- .plugin(tauri_plugin_opener::init()).plugin(- MacroNavigationPlugin::new(ALLOWED_DOMAINS)- .expect("Domains must be valid urls")- .with_app_link_hosts(APP_LINK_HOSTS),+ tauri_plugin_opener::Builder::new()+ // Desktop handles actual webview navigation, not bubbling DOM+ // clicks. Mobile does not support Tauri's on_new_window hook.+ .open_js_links_on_click(cfg!(mobile))+ .build(),)+ .plugin(navigation.clone()).plugin(macro_bundle_updater_plugin::inbound::plugin::MacroBundleUpdaterPlugin::new(AppEnvironment::current()@@ -327,6 +347,14 @@ pub fn run() {staged_upload::upload_staged_file_to_presigned_url,]).setup(move |app| {+ #[cfg(desktop)]+ for config in &startup_windows {+ let navigation = navigation.clone();+ let handle = app.handle().clone();+ tauri::WebviewWindowBuilder::from_config(app, config)?+ .on_new_window(move |url, _features| navigation.on_new_window(&handle, &url))+ .build()?;+ }#[cfg(desktop)]desktop_update::setup(app, recording)?;diagnostics::setup(app, diagnostics);@@ -344,7 +372,7 @@ pub fn run() {Ok(())})- .build(tauri::generate_context!())+ .build(context).expect("error while building tauri application").run(move |app_handle, event| match &event {RunEvent::Ready if !recording => {diff --git a/apps/web/tests/native/README.md b/apps/web/tests/native/README.mdindex cf8378633a..7bc31d5cf2 100644--- a/apps/web/tests/native/README.md+++ b/apps/web/tests/native/README.md@@ -74,6 +74,24 @@ not pointer hit-testing: WebKitWebDriver's native clicks can land on an adjacentrow in the Tauri window, and All is now beyond the numeric tab shortcuts.Assertions compare exact row identities, not just counts.+## Native external-link regression++After rebuilding the native binary, run `bun run native:e2e:links` inside the+same `.#tauri-e2e` shell. This focused suite serves a small HTML fixture instead+of the full frontend; it uses the real app's window creation, navigation plugin,+Tauri event IPC, and Linux WebKit. No login, backend, or frontend WASM is used at+runtime. A disposable `xdg-open` executable records launches at the OS process+boundary so no real browser or external network request is started.++Checks include the plain PR anchor inside a propagation-stopping panel, pointer+and keyboard activation, a normal `_blank` link, same-frame external navigation,+`window.open`, and absolute/relative Macro app links. Each external activation+must launch exactly once and retain the original webview. Prevented clicks and+browser-only/local-file popup URLs must not launch anything. The desktop JS click+interceptor must be absent. Artifacts are under `test-results/native/links-*`.+This is Linux coverage; macOS/Windows native popup handling and the unchanged+mobile JS fallback need platform-specific verification.+## Exhaustive filter-selection matrix```sh@@ -194,6 +212,8 @@ bun run native:e2e:check # standalone harness TypeScript check```- Missing WebKitWebDriver/Xvfb: enter `.#tauri-e2e`, not the default shell.+ This shell also pins the software EGL renderer to the same Nix package set;+ loading a newer host Mesa can otherwise abort WebKit with `EGL_BAD_PARAMETER`.- `unshare: Operation not permitted`: the host/CI runner must permit unprivilegeduser namespaces. Fail closed; do not remove isolation or run against hosted data.- Startup timeout: inspect Vite/native logs and request errors first. Never resetdiff --git a/apps/web/tests/native/fixtures/links-browser.ts b/apps/web/tests/native/fixtures/links-browser.tsnew file mode 100644index 0000000000..005a2c3e15--- /dev/null+++ b/apps/web/tests/native/fixtures/links-browser.ts@@ -0,0 +1,40 @@+import { listen } from '@tauri-apps/api/event';++declare global {+ interface Window {+ linkFixture: {+ events: { path: string; query: string }[];+ windowClicks: boolean[];+ clickTargets: string[];+ popupUrl: string;+ };+ }+}++window.linkFixture = {+ events: [],+ windowClicks: [],+ clickTargets: [],+ popupUrl: 'https://example.com/programmatic',+};+window.addEventListener('click', (event) => {+ window.linkFixture.windowClicks.push(event.defaultPrevented);+ window.linkFixture.clickTargets.push(+ event.target instanceof HTMLElement ? event.target.id : 'unknown'+ );+});+document.getElementById('stopped')!.addEventListener('click', (event) => {+ event.stopPropagation();+});+document+ .getElementById('prevented-link')!+ .addEventListener('click', (event) => {+ event.preventDefault();+ });+document.getElementById('popup')!.addEventListener('click', () => {+ window.open(window.linkFixture.popupUrl, '_blank', 'noopener,noreferrer');+});+await listen<{ path: string; query: string }>('navigate', ({ payload }) => {+ window.linkFixture.events.push(payload);+});+document.documentElement.dataset.ready = 'true';diff --git a/apps/web/tests/native/fixtures/links.html b/apps/web/tests/native/fixtures/links.htmlnew file mode 100644index 0000000000..2edb03388e--- /dev/null+++ b/apps/web/tests/native/fixtures/links.html@@ -0,0 +1,18 @@+<!doctype html>+<html lang="en">+ <head><meta charset="utf-8"><title>Native link regression</title></head>+ <body>+ <h1>Native link regression</h1>+ <aside id="stopped">+ <a id="stopped-link" target="_blank" rel="noreferrer" class="truncate hover:underline"+ href="https://github.com/macro-inc/macro/pull/7858">macro-inc/macro#7858</a>+ </aside>+ <p><a id="plain-link" href="https://example.com/plain" target="_blank" rel="noreferrer">Plain popup</a></p>+ <p><a id="self-link" href="https://example.com/self">Same-frame external link</a></p>+ <p><a id="prevented-link" href="https://example.com/prevented" target="_blank">Prevented link</a></p>+ <p><a id="app-link" href="https://macro.com/app/mail?view=all" target="_blank">Macro app link</a></p>+ <p><a id="relative-link" href="/app/mail?view=all" target="_blank">Relative app link</a></p>+ <button id="popup" type="button">Programmatic popup</button>+ <script type="module" src="/links.js"></script>+ </body>+</html>diff --git a/apps/web/tests/native/links-runner.ts b/apps/web/tests/native/links-runner.tsnew file mode 100644index 0000000000..33e5a32542--- /dev/null+++ b/apps/web/tests/native/links-runner.ts@@ -0,0 +1,233 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import { type Browser, remote } from 'webdriverio';+import type {} from './fixtures/links-browser';++assert.equal(process.env.MACRO_E2E_NETNS, '1', 'Run through isolated run.sh');+const web = resolve(import.meta.dirname, '../..');+const binaries = resolve(web, 'tauri/target/e2e');+const artifacts = resolve(+ web,+ 'test-results/native',+ `links-${new Date().toISOString().replaceAll(':', '-')}`+);+const launcherDirectory = resolve(artifacts, 'bin');+await mkdir(launcherDirectory, { recursive: true });+const launchLog = resolve(artifacts, 'opened-urls.txt');+await Bun.write(launchLog, '');+// Exercise the real opener/OS process boundary without launching a browser or+// sending requests outside the isolated network namespace.+await writeFile(+ resolve(launcherDirectory, 'xdg-open'),+ '#!/bin/sh\nprintf "%s\\n" "$1" >> "$MACRO_LINK_TEST_LOG"\n',+ { mode: 0o755 }+);+const bundle = await Bun.build({+ entrypoints: [resolve(import.meta.dirname, 'fixtures/links-browser.ts')],+ target: 'browser',+});+assert(bundle.success, String(bundle.logs));+const javascript = await bundle.outputs[0].text();+const html = await Bun.file(+ resolve(import.meta.dirname, 'fixtures/links.html')+).text();+const server = Bun.serve({+ hostname: '127.0.0.1',+ port: 3009,+ fetch(request) {+ const script = new URL(request.url).pathname === '/links.js';+ return new Response(script ? javascript : html, {+ headers: { 'Content-Type': script ? 'text/javascript' : 'text/html' },+ });+ },+});+const driver = Bun.spawn(+ [+ resolve(binaries, 'tools/bin/tauri-driver'),+ '--port',+ '4444',+ '--native-driver',+ Bun.which('WebKitWebDriver')!,+ ],+ {+ env: {+ ...process.env,+ PATH: `${launcherDirectory}:${process.env.PATH}`,+ MACRO_LINK_TEST_LOG: launchLog,+ WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: '1',+ WEBKIT_DISABLE_DMABUF_RENDERER: '1',+ LIBGL_ALWAYS_SOFTWARE: '1',+ },+ stdout: Bun.file(resolve(artifacts, 'tauri.log')),+ stderr: Bun.file(resolve(artifacts, 'tauri.stderr.log')),+ }+);+const watchdog = setTimeout(() => {+ console.error(`Native link tests timed out. Artifacts: ${artifacts}`);+ process.exit(1);+}, 120_000);+let browser: Browser | undefined;+const expected: string[] = [];+const openedUrls = async () =>+ (await Bun.file(launchLog).text()).split('\n').filter(Boolean);++try {+ for (;;) {+ assert.equal(driver.exitCode, null, 'Driver exited before ready');+ try {+ if ((await fetch('http://localhost:4444/status')).ok) break;+ } catch {+ // Wait for WebKitWebDriver to bind.+ }+ await Bun.sleep(100);+ }+ const capabilities: WebdriverIO.Capabilities & {+ 'tauri:options': { application: string };+ } = { 'tauri:options': { application: resolve(binaries, 'app') } };+ browser = await remote({+ hostname: '127.0.0.1',+ port: 4444,+ logLevel: 'warn',+ connectionRetryCount: 0,+ connectionRetryTimeout: 30_000,+ capabilities,+ });+ await browser.waitUntil(+ () =>+ browser!.execute(() => document.documentElement.dataset.ready === 'true'),+ { timeout: 30_000 }+ );+ const originalUrl = await browser.getUrl();+ async function expectOpened(url: string) {+ expected.push(url);+ await browser!.waitUntil(+ async () => (await openedUrls()).length >= expected.length+ );+ assert.deepEqual(+ await openedUrls(),+ expected,+ 'Each activation must open exactly once'+ );+ assert.equal(+ await browser!.getUrl(),+ originalUrl,+ 'External URL replaced the app'+ );+ assert.equal(+ (await browser!.getWindowHandles()).length,+ 1,+ 'Unexpected popup webview'+ );+ }++ await browser.$('#stopped-link').click();+ await expectOpened('https://github.com/macro-inc/macro/pull/7858');+ await browser.keys('Enter');+ await expectOpened('https://github.com/macro-inc/macro/pull/7858');+ assert.deepEqual(+ await browser.execute(() => window.linkFixture.windowClicks),+ []+ );++ await browser.$('#plain-link').click();+ await expectOpened('https://example.com/plain');+ assert.equal(+ await browser.execute(() => window.linkFixture.windowClicks.at(-1)),+ false,+ 'Desktop must not install the JS click interceptor'+ );+ await browser.$('#self-link').click();+ await expectOpened('https://example.com/self');+ await browser.$('#popup').click();+ await expectOpened('https://example.com/programmatic');++ // WebKitWebDriver can miss short text links with pointer coordinates. The+ // original PR link above covers pointer activation; use real keyboard+ // activation for the remaining links, not a synthetic navigation callback.+ async function activate(id: string) {+ await browser!.$(`#${id}`).execute((element) => element.focus());+ await browser!.keys('Enter');+ assert.equal(+ await browser!.execute(() => window.linkFixture.clickTargets.at(-1)),+ id+ );+ }+ for (const id of ['app-link', 'relative-link']) {+ await activate(id);+ const count = id === 'app-link' ? 1 : 2;+ await browser.waitUntil(+ () =>+ browser!.execute(+ (count) => window.linkFixture.events.length >= count,+ count+ ),+ { timeoutMsg: `No native navigation event for ${id}` }+ );+ assert.deepEqual(+ await browser.execute(() => window.linkFixture.events),+ Array.from({ length: count }, () => ({+ path: '/mail',+ query: 'view=all',+ }))+ );+ }+ await activate('prevented-link');+ for (const url of [+ 'about:blank',+ 'data:text/html,blocked',+ 'file:///etc/passwd',+ ]) {+ await browser.execute((url) => {+ window.linkFixture.popupUrl = url;+ }, url);+ await activate('popup');+ }+ await Bun.sleep(500);+ assert.deepEqual(await openedUrls(), expected);+ assert.equal(await browser.getUrl(), originalUrl);+ assert.equal((await browser.getWindowHandles()).length, 1);+ await browser.saveScreenshot(resolve(artifacts, 'links.png'));+ console.log(+ 'PASS: native popup and same-frame routing, stopped clicks, keyboard, cancellation, no duplicates, and in-app links'+ );+} catch (error) {+ if (browser) {+ try {+ await Bun.write(+ resolve(artifacts, 'failure-state.json'),+ JSON.stringify(+ await browser.execute(() => ({+ fixture: window.linkFixture,+ url: location.href,+ focusedElement: document.activeElement?.id,+ })),+ null,+ 2+ )+ );+ await browser.saveScreenshot(resolve(artifacts, 'failure.png'));+ await Bun.write(+ resolve(artifacts, 'failure.html'),+ await browser.getPageSource()+ );+ } catch {+ // A crashed webview may not be available for diagnostics.+ }+ }+ throw error;+} finally {+ if (browser) {+ try {+ await browser.deleteSession();+ } catch {+ // Driver cleanup below still owns processes if the webview crashed.+ }+ }+ driver.kill();+ await Promise.race([driver.exited, Bun.sleep(2000)]);+ if (driver.exitCode === null) driver.kill('SIGKILL');+ await server.stop(true);+ clearTimeout(watchdog);+ console.log(`Artifacts: ${artifacts}`);+}diff --git a/apps/web/tests/native/run.sh b/apps/web/tests/native/run.shindex 7a7e1b73af..a9bf2175a3 100644--- a/apps/web/tests/native/run.sh+++ b/apps/web/tests/native/run.sh@@ -1,6 +1,11 @@#!/usr/bin/env bashset -euo pipefailroot=$(git rev-parse --show-toplevel)+runner=runner.ts+if [[ ${1:-} == --links ]]; then+ runner=links-runner.ts+ shift+fifor tool in bun unshare ip dbus-run-session xvfb-run WebKitWebDriver; doif ! command -v "$tool" >/dev/null; thenecho "Missing $tool. Run inside: nix develop .#tauri-e2e" >&2@@ -36,7 +41,7 @@ unshare --user --map-root-user --net --pid --fork --mount-proc --kill-child=SIGKip link set lo upexport MACRO_E2E_NETNS=1exec dbus-run-session -- xvfb-run --auto-servernum --server-args="-screen 0 1440x1000x24 -nolisten tcp" \- bun "$1/apps/web/tests/native/runner.ts" "${@:2}"- ' bash "$root" "$@" &+ bun "$1/apps/web/tests/native/$2" "${@:3}"+ ' bash "$root" "$runner" "$@" &child=$!wait "$child"diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex b387f7000f..25090f22b8 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -19,6 +19,22 @@ must load through the webview, not native HTTP. A `vite:preloadError` with`scheme tauri not supported` indicates an asset-routing failure; reloading thesame bundle does not resolve it.+## External links in the native app++Desktop external links open in the system browser, whether activated by a normal+anchor, a `target="_blank"` anchor, or `window.open(url)`. Native webview navigation+handles this, not a window-level DOM click listener. Each activation should open+exactly once, without replacing the app or creating another app window. Macro app+links (including same-origin popup links) route inside the existing SPA.++Verify the `owner/repo#number` footer link in a pull request's floating details+panel with both a click and keyboard activation. The panel stops click propagation;+that must not prevent the link from opening or dismiss the panel. Also verify a+prevented click does nothing. Browser-only URLs such as `about:blank`, `data:`,+`blob:` and `javascript:` must not launch an external handler. Web browser anchor+behavior is unchanged. iOS/Android retain their existing JS opener fallback because+Tauri's native popup callback is desktop-only.+## Returning from another pageA browser back/forward-cache restore reconnects the GraphQL cache worker anddiff --git a/nix/tauri-dev-shells.nix b/nix/tauri-dev-shells.nixindex 172206661d..12bb9fd7e9 100644--- a/nix/tauri-dev-shells.nix+++ b/nix/tauri-dev-shells.nix@@ -89,6 +89,9 @@# WebDriver is installed at a pinned version by the test build script.# Keep display/network isolation tools out of the ordinary desktop shell.tauri-e2e = config.devShells.tauri-linux.overrideAttrs (old: {+ # Xvfb tests use software rendering. Do not dlopen the host's Mesa,+ # which may require a newer glibc than this pinned WebKit runtime.+ __EGL_VENDOR_LIBRARY_FILENAMES = "${tauriPkgs.mesa}/share/glvnd/egl_vendor.d/50_mesa.json";buildInputs =(old.buildInputs or [ ])++ (with tauriPkgs; [