Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(desktop): keep external links from replacing the chat

Eloi Torrents92c6ef194b71
diff --git a/app/src/utils/openUrl.test.ts b/app/src/utils/openUrl.test.ts
index cc6da9d403..1d0fc26c88 100644
--- a/app/src/utils/openUrl.test.ts
+++ b/app/src/utils/openUrl.test.ts
@@ -1,13 +1,9 @@
-/**
- * Unit tests for `openUrl`. The Tauri path is exercised in callers'
- * integration tests; here we focus on the browser fallback and the
- * CEF-IPC-not-ready recovery so the non-Tauri branch (used by dev
- * preview builds) and the CEF gap window (#1472 / REACT-T/S/R) do
- * not regress.
- */
+/** Desktop links must never fall back to in-webview navigation. */
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
const isTauriMock = vi.fn();
+const isTauriRuntimeMock = vi.fn();
+vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => isTauriRuntimeMock() }));
const tauriOpenUrlMock = vi.fn();
const revealItemInDirMock = vi.fn();
const addBreadcrumbMock = vi.fn();
@@ -32,6 +28,7 @@ describe('openUrl', () => {
beforeEach(() => {
vi.clearAllMocks();
+ isTauriRuntimeMock.mockImplementation(() => isTauriMock());
// Default this device to macOS so existing POSIX-path reveal tests pass; the
// #4278 cross-host tests override per-case.
platformMock.mockResolvedValue('macos');
@@ -91,7 +88,7 @@ describe('openUrl', () => {
expect.objectContaining({
category: 'ipc',
level: 'warning',
- message: 'tauriOpenUrl failed; evaluating fallback',
+ message: 'tauriOpenUrl failed; keeping app navigation',
data: expect.objectContaining({ url: 'obsidian:' }),
})
);
@@ -100,31 +97,24 @@ describe('openUrl', () => {
expect(call?.data?.url).not.toContain('/Users/me');
});
- it('falls back to window.open when tauriOpenUrl rejects on an http URL (CEF IPC race recovery, #1472)', async () => {
- // Concrete repro for OPENHUMAN-REACT-T/S/R: CEF embedder
- // injects `window.ipc.postMessage` after `on_after_created`. A
- // click landing in that gap causes `tauriOpenUrl` to reject with
- // a TypeError. For http(s) URLs the safe recovery is to hand off
- // to `window.open` so the Billing dashboard still opens.
+ it('keeps the desktop app when the opener rejects an HTTPS URL', async () => {
isTauriMock.mockReturnValue(true);
const ipcError = new TypeError("Cannot read properties of undefined (reading 'postMessage')");
tauriOpenUrlMock.mockRejectedValue(ipcError);
const { openUrl } = await import('./openUrl');
- await openUrl('https://tinyhumans.ai/dashboard?token=secret-redact-me');
-
- expect(windowOpenMock).toHaveBeenCalledWith(
- 'https://tinyhumans.ai/dashboard?token=secret-redact-me',
- '_blank',
- 'noopener,noreferrer'
+ await expect(openUrl('https://tinyhumans.ai/dashboard?token=secret-redact-me')).rejects.toThrow(
+ ipcError
);
+
+ expect(windowOpenMock).not.toHaveBeenCalled();
// Breadcrumb keeps only origin for http(s) — pathname + query (which may
// carry tokens / emails / vault paths) must not be sent to Sentry.
expect(addBreadcrumbMock).toHaveBeenCalledWith(
expect.objectContaining({
category: 'ipc',
level: 'warning',
- message: 'tauriOpenUrl failed; evaluating fallback',
+ message: 'tauriOpenUrl failed; keeping app navigation',
data: expect.objectContaining({ url: 'https://tinyhumans.ai' }),
})
);
@@ -133,6 +123,15 @@ describe('openUrl', () => {
expect(call?.data?.url).not.toContain('/dashboard');
});
+ it('does not treat a desktop with an unavailable IPC bridge as a browser', async () => {
+ isTauriMock.mockReturnValue(false);
+ isTauriRuntimeMock.mockReturnValue(true);
+ tauriOpenUrlMock.mockRejectedValue(new Error('IPC unavailable'));
+ const { openUrl } = await import('./openUrl');
+ await expect(openUrl('https://example.com')).rejects.toThrow('IPC unavailable');
+ expect(windowOpenMock).not.toHaveBeenCalled();
+ });
+
it('revealPath dispatches to tauri-plugin-opener under Tauri (#2281 Reveal Folder fallback)', async () => {
isTauriMock.mockReturnValue(true);
revealItemInDirMock.mockResolvedValue(undefined);
@@ -200,23 +199,21 @@ describe('openUrl', () => {
});
});
- it('trims surrounding whitespace before classifying an http URL for fallback', async () => {
+ it('trims surrounding whitespace before calling the desktop opener', async () => {
isTauriMock.mockReturnValue(true);
tauriOpenUrlMock.mockRejectedValue(
new TypeError("Cannot read properties of undefined (reading 'postMessage')")
);
const { openUrl } = await import('./openUrl');
- await openUrl(' https://tinyhumans.ai/dashboard?token=secret-redact-me ');
+ await expect(
+ openUrl(' https://tinyhumans.ai/dashboard?token=secret-redact-me ')
+ ).rejects.toThrow('postMessage');
expect(tauriOpenUrlMock).toHaveBeenCalledWith(
'https://tinyhumans.ai/dashboard?token=secret-redact-me'
);
- expect(windowOpenMock).toHaveBeenCalledWith(
- 'https://tinyhumans.ai/dashboard?token=secret-redact-me',
- '_blank',
- 'noopener,noreferrer'
- );
+ expect(windowOpenMock).not.toHaveBeenCalled();
expect(addBreadcrumbMock).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ url: 'https://tinyhumans.ai' }) })
);
diff --git a/app/src/utils/openUrl.ts b/app/src/utils/openUrl.ts
index a55ef1d4fc..e54af89c24 100644
--- a/app/src/utils/openUrl.ts
+++ b/app/src/utils/openUrl.ts
@@ -1,11 +1,10 @@
import * as Sentry from '@sentry/react';
+import { isTauri as isTauriRuntime } from '@tauri-apps/api/core';
import { revealItemInDir, openUrl as tauriOpenUrl } from '@tauri-apps/plugin-opener';
import { platform } from '@tauri-apps/plugin-os';
import { isTauri } from './tauriCommands/common';
-const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url.trim());
-
/**
* Returns a low-PII representation of `url` for telemetry breadcrumbs.
* For http(s) we keep only the origin so the host is identifiable but the
@@ -35,23 +34,15 @@ const getTelemetryUrl = (url: string): string => {
* registered application instead of staying inside the embedded
* webview.
*
- * CEF embedder note: the IPC bridge (`window.ipc.postMessage`) is
- * injected on the renderer-side after `on_after_created` fires.
- * A click landing in that gap causes the plugin's `invoke()` glue
- * to reject with `TypeError: Cannot read properties of undefined
- * (reading 'postMessage')`. For http(s) URLs we recover by falling
- * back to `window.open` so the user-facing flow still works. For
- * non-http schemes we re-throw — `window.open` would spawn a Tauri
- * webview window that cannot handle custom schemes, which is worse
- * UX than a propagated error the caller can surface.
- *
- * In a browser context (no Tauri) we keep the `window.open` path so
- * `https://` / `mailto:` links still work for dev/preview builds.
+ * Desktop opener failures propagate to the caller. Falling back to
+ * `window.open` in a desktop webview can replace the app with the remote
+ * page, leaving no browser controls to return to the chat.
+ * Browser preview builds use `window.open` normally.
*/
export const openUrl = async (url: string): Promise<void> => {
const normalizedUrl = url.trim();
- if (isTauri()) {
+ if (isTauriRuntime()) {
try {
await tauriOpenUrl(normalizedUrl);
return;
@@ -59,13 +50,10 @@ export const openUrl = async (url: string): Promise<void> => {
Sentry.addBreadcrumb({
category: 'ipc',
level: 'warning',
- message: 'tauriOpenUrl failed; evaluating fallback',
- data: { url: getTelemetryUrl(normalizedUrl), error: String(err) },
+ message: 'tauriOpenUrl failed; keeping app navigation',
+ data: { url: getTelemetryUrl(normalizedUrl) },
});
- if (!isHttpUrl(normalizedUrl)) {
- throw err;
- }
- // http(s) URL — safe to fall back to window.open.
+ throw err;
}
}
window.open(normalizedUrl, '_blank', 'noopener,noreferrer');
diff --git a/app/test/e2e/specs/agent-harness-behaviors.spec.ts b/app/test/e2e/specs/agent-harness-behaviors.spec.ts
index 74c236fc82..5f280b620e 100644
--- a/app/test/e2e/specs/agent-harness-behaviors.spec.ts
+++ b/app/test/e2e/specs/agent-harness-behaviors.spec.ts
@@ -42,7 +42,7 @@ import {
waitForAssistantReplyContaining,
waitForSocketConnected,
} from '../helpers/chat-harness';
-import { textExists } from '../helpers/element-helpers';
+import { clickText, textExists } from '../helpers/element-helpers';
import { resetApp } from '../helpers/reset-app';
import { navigateViaHash } from '../helpers/shared-flows';
import { setMockBehavior, startMockServer, stopMockServer } from '../mock-server';
@@ -238,6 +238,86 @@ describe('agent harness behaviors', () => {
await stopMockServer();
});
+ it('keeps the chat when opening a reply link succeeds or the desktop opener fails', async function () {
+ this.timeout(90_000);
+ setMockBehavior(
+ 'llmForcedResponses',
+ JSON.stringify([{ content: '[EXTERNAL_PR_LINK](https://example.com/repo/pull/1)' }])
+ );
+ const threadId = await startNewThread();
+ await sendPrompt('show the test PR link');
+ expect(await waitForAssistantReplyContaining('EXTERNAL_PR_LINK')).toBe(true);
+ const appUrl = await browser.getUrl();
+ for (const reject of [false, true]) {
+ // Keep this entirely offline: replace only the OS-opener IPC and record
+ // any browser fallback. Other IPC continues through the existing bridge.
+ await browser.execute((shouldReject: boolean) => {
+ const win = window as unknown as {
+ isTauri?: boolean;
+ __TAURI_INTERNALS__?: { invoke: (...args: unknown[]) => Promise<unknown> };
+ __linkTest?: { opened: string[]; fallback: number; restore: () => void };
+ };
+ const originalRuntime = win.isTauri;
+ const originalInternals = win.__TAURI_INTERNALS__;
+ const originalOpen = window.open;
+ const state = {
+ opened: [] as string[],
+ fallback: 0,
+ restore: () => {
+ win.isTauri = originalRuntime;
+ win.__TAURI_INTERNALS__ = originalInternals;
+ window.open = originalOpen;
+ },
+ };
+ win.__linkTest = state;
+ win.isTauri = true;
+ win.__TAURI_INTERNALS__ = {
+ ...originalInternals,
+ invoke: async (...args: unknown[]) => {
+ if (args[0] === 'plugin:opener|open_url') {
+ state.opened.push((args[1] as { url: string }).url);
+ if (shouldReject) throw new Error('mock opener unavailable');
+ return;
+ }
+ return originalInternals?.invoke(...args);
+ },
+ };
+ window.open = () => {
+ state.fallback++;
+ return null;
+ };
+ }, reject);
+ try {
+ await clickText('EXTERNAL_PR_LINK');
+ await browser.waitUntil(
+ async () =>
+ await browser.execute(() => {
+ const state = (window as unknown as { __linkTest?: { opened: string[] } }).__linkTest;
+ return state?.opened.length === 1;
+ }),
+ { timeout: 5000 }
+ );
+ expect(
+ await browser.execute(() => {
+ const state = (
+ window as unknown as { __linkTest?: { opened: string[]; fallback: number } }
+ ).__linkTest;
+ return { opened: state?.opened, fallback: state?.fallback };
+ })
+ ).toEqual({ opened: ['https://example.com/repo/pull/1'], fallback: 0 });
+ expect(await browser.getUrl()).toBe(appUrl);
+ expect(await getSelectedThreadId()).toBe(threadId);
+ expect(await chatMounted()).toBe(true);
+ } finally {
+ await browser.execute(() => {
+ const win = window as unknown as { __linkTest?: { restore: () => void } };
+ win.__linkTest?.restore();
+ delete win.__linkTest;
+ });
+ }
+ }
+ });
+
it('shows the approval card and completes after the user approves', async function () {
this.timeout(90_000);
// First write creates the file (new path → no park); the second write to the
diff --git a/crates/openhuman-app/src/external_navigation.rs b/crates/openhuman-app/src/external_navigation.rs
new file mode 100644
index 0000000000..28f8264f47
--- /dev/null
+++ b/crates/openhuman-app/src/external_navigation.rs
@@ -0,0 +1,70 @@
+//! Keep remote pages from replacing the main desktop UI.
+use tauri::{plugin::TauriPlugin, Manager};
+use tauri_plugin_opener::OpenerExt;
+use url::Url;
+
+fn is_external(url: &Url, dev_url: Option<&Url>) -> bool {
+ if !matches!(url.scheme(), "http" | "https") {
+ return false;
+ }
+ if url.host_str() == Some("tauri.localhost") && url.port().is_none() {
+ return false;
+ }
+ !dev_url.is_some_and(|dev| dev.origin() == url.origin())
+}
+
+pub fn init() -> TauriPlugin<crate::AppRuntime> {
+ tauri::plugin::Builder::new("external-navigation")
+ .on_navigation(|webview, url| {
+ let dev_url = if cfg!(debug_assertions) {
+ webview.config().build.dev_url.as_ref()
+ } else {
+ None
+ };
+ if webview.label() != "main" || !is_external(url, dev_url) {
+ return true;
+ }
+ log::debug!("[external-navigation] handing main-window navigation to OS");
+ let app = webview.app_handle().clone();
+ let target = url.to_string();
+ tauri::async_runtime::spawn_blocking(move || {
+ if app.opener().open_url(target, None::<&str>).is_err() {
+ log::warn!("[external-navigation] OS opener failed; retained main window");
+ }
+ });
+ false
+ })
+ .build()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn remote_navigation_is_external_but_app_origins_are_preserved() {
+ let dev = Url::parse("http://localhost:1420").unwrap();
+ for href in [
+ "https://github.com/example/repo/pull/1",
+ "http://localhost:8000",
+ "https://tauri.localhost.example.com",
+ ] {
+ assert!(
+ is_external(&Url::parse(href).unwrap(), Some(&dev)),
+ "{href}"
+ );
+ }
+ for href in [
+ "tauri://localhost/#/chat",
+ "http://tauri.localhost/#/chat",
+ "https://tauri.localhost/#/chat",
+ "http://localhost:1420/#/chat",
+ ] {
+ assert!(
+ !is_external(&Url::parse(href).unwrap(), Some(&dev)),
+ "{href}"
+ );
+ }
+ assert!(is_external(&dev, None));
+ }
+}
diff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rs
index bdc53a537a..db5dc024f9 100644
--- a/crates/openhuman-app/src/lib.rs
+++ b/crates/openhuman-app/src/lib.rs
@@ -73,6 +73,7 @@ mod deep_link_ipc_windows;
mod deep_link_registration_check;
mod dictation_hotkeys;
mod directory_picker;
+mod external_navigation;
mod file_logging;
// Routing the frontend to a core that is not the one in this process. Leaf
// gated: with `gateways` off the commands are simply absent, which is what the
@@ -3010,6 +3011,7 @@ pub fn run() {
.open_js_links_on_click(false)
.build(),
)
+ .plugin(external_navigation::init())
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index 8b23ad1773..9268cfdee4 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -46,6 +46,7 @@ Applies to every release, all platforms.
- [ ] **SmartScreen does not block install** — Run the installer from a fresh download. Expected: SmartScreen passes (signed binary). If `Windows protected your PC` appears, the EV signature is missing or the reputation has not built up — escalate before shipping.
- [ ] **Installer creates Start Menu + Desktop shortcuts** — Defaults preserved. Expected: both shortcuts launch the app.
+- [ ] **Chat links preserve the desktop UI** — Click an HTTPS PR link in an assistant reply. Expected: the default browser opens the PR and OpenHuman stays on the same conversation. If the OS opener fails, the app must remain visible instead of navigating to the remote page. Check internal chat/settings navigation still works.
- [ ] **App registers `openhuman://` URL scheme** — From a browser, click an `openhuman://oauth/success?...` link. Expected: OS prompts to open in OpenHuman; clicking through delivers the deep link.
### Linux
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 41d0c661c8..28c0ee0f39 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -193,6 +193,8 @@ Canonical mapping of every product feature to its test source(s). Drives gap-fil
| 4.2.9 | Share cards ("Look what my agent did" post to X / LinkedIn) | VU | `app/src/features/share/shareContent.test.ts`, `app/src/features/share/shareTargets.test.ts`, `app/src/features/share/shareCaption.test.ts`, `app/src/features/share/shareCard.test.ts`, `app/src/features/share/ShareMessageButton.test.tsx`, `app/src/features/share/ShareCardModal.test.tsx` | ✅ | Hover Share button under completed agent messages opens a Canvas 2D branded card; LLM-drafted headline/caption via `inference_agent_chat_simple` with deterministic offline fallback; X/LinkedIn intent URLs + copy/save PNG; secrets/paths/emails redacted before render. MVP wires only the completed-task trigger; workflow-run + Human-tab triggers are follow-ups. WD E2E deferred |
| 4.2.10 | Durable agent reply (core stores it before announcing `chat_done`) | RU+VU | `crates/openhuman-core/src/web_chat/reply_persistence_tests.rs`, `crates/openhuman-core/src/web_chat/presentation_tests.rs`, `app/src/providers/__tests__/ChatRuntimeProvider.test.tsx` | ✅ | `deliver_response` persists an unsegmented reply under `agent:<request_id>` before publishing the terminal event, so a dropped socket, a failed `threads_message_append` or a reloaded webview costs a repaint rather than the answer; the client's append collapses onto that row by id. RU covers the write, its idempotency, the empty-reply and missing-thread paths, and that delivery still announces when the store refuses. VU covers the mirrored id, the segmented exception, the refetch that recovers a failed append, and the reconnect that rejoins orphaned thread rooms. WD E2E (kill the append mid-turn) is a follow-up |
+| 4.2.11 | External reply links preserve the desktop chat | RU+VU+WD+MS | `app/src/utils/openUrl.test.ts`, `crates/openhuman-app/src/external_navigation.rs`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts`, release-manual-smoke | 🟡 | Successful and failed OS-opener IPC covered; native origin policy covered. macOS bundle smoke verified. WD regression added; execution pending compatible desktop driver. |
+
### 4.3 Tool Invocation
| ID | Feature | Layer | Test path(s) | Status | Notes |