Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(desktop): open internal links in the portal instead of the system browser (#17124)

Arvin Xu19a744927f4b
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index fbc060b1a5d..cfd6a7ff50d 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -661,6 +661,27 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
just added (`curl -s 127.0.0.1:<vitePort>/src/path/File.tsx | grep -c myNewSymbol`) before blaming the
code. `electron-dev.sh stop <id>` then start again to get a clean server.
+### E8b. The standalone `apps/desktop` install BREAKS the root workspace's type resolution β€” re-run the root install after it
+
+- **Situation**: a worktree set up per E8 (`pnpm install` at the root, then
+ `cd apps/desktop && pnpm install`). Everything runs β€” Electron boots, the renderer serves live
+ code β€” but a full `bun run type-check` that passed BEFORE the desktop install now fails with
+ dozens of errors that have nothing to do with the change under test:
+ `Module '"@lobechat/types"' has no exported member 'MetaData' | 'HotkeyId' | …` plus
+ `Type 'UserHotkeyConfig' is missing the following properties from type 'UserHotkeyConfig'` β€”
+ the same name on both sides, i.e. **two copies of `@lobechat/types` in one program**.
+- **Doesn't work**: chasing it as a code defect, or checking the symlink
+ (`node_modules/@lobechat/types β†’ ../../packages/types` looks correct) and `packages/types/node_modules`
+ (its deps are all present). Both look fine while the program still sees two instances.
+- **Cause**: `apps/desktop` is NOT in the root pnpm workspace (see E8). Its standalone install
+ re-resolves the `packages/*` links from its own lockfile and rewrites shared package deps under
+ `packages/*/node_modules`, leaving the root workspace pointing at a second instance.
+- **Works**: run `pnpm install` at the worktree root ONE MORE TIME, after the desktop install
+ (\~1.5 min, mostly cached). Type-check goes back to 0 errors and Electron keeps working.
+ So the safe order is: root install β†’ desktop install β†’ root install again. And never publish a
+ "type-check failed" verdict from a worktree until you've re-run the root install β€” the failure is
+ environmental, and the error text (a type "missing properties from" itself) is the tell.
+
### E9. Electron dev's FIRST cold boot sits on the splash with an empty `#root` for 1–3 minutes
- **Situation**: after `electron-dev.sh start <id>`, `app-probe.sh auth` returns `isSignedIn:false`,
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index de718d7d02b..d0306d0117c 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -24,6 +24,21 @@ const getExternalNavigationHosts = () =>
.map((host) => host.trim().toLowerCase())
.filter(Boolean);
+const EXTERNALLY_OPENABLE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
+
+/**
+ * The renderer runs on `app://renderer`, so a link the renderer did not claim can
+ * reach the window-open handler with an internal URL. Handing those to the OS opens
+ * nothing β€” deny instead of silently failing.
+ */
+const isExternallyOpenableUrl = (rawUrl: string) => {
+ try {
+ return EXTERNALLY_OPENABLE_PROTOCOLS.has(new URL(rawUrl).protocol);
+ } catch {
+ return false;
+ }
+};
+
const shouldOpenTopLevelNavigationExternally = (rawUrl: string) => {
const externalNavigationHosts = getExternalNavigationHosts();
if (externalNavigationHosts.length === 0) return false;
@@ -250,6 +265,11 @@ export default class Browser {
browserWindow.webContents.setWindowOpenHandler(({ url }) => {
logger.info(`[${this.identifier}] Intercepted window open for URL: ${url}`);
+ if (!isExternallyOpenableUrl(url)) {
+ logger.debug(`[${this.identifier}] Denied non-external window open URL: ${url}`);
+ return { action: 'deny' };
+ }
+
// Open external URL in system browser
shell.openExternal(url).catch((error) => {
logger.error(`[${this.identifier}] Failed to open external URL: ${url}`, error);
diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
index 70c7551ff71..ec8fe48b232 100644
--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
@@ -799,4 +799,28 @@ describe('Browser', () => {
expect(mockShell.openExternal).not.toHaveBeenCalled();
});
});
+
+ describe('window open handling', () => {
+ let windowOpenHandler: (details: { url: string }) => { action: string };
+
+ beforeEach(() => {
+ windowOpenHandler = mockBrowserWindow.webContents.setWindowOpenHandler.mock.calls.at(-1)?.[0];
+ });
+
+ it('should open web URLs in the system browser', () => {
+ expect(windowOpenHandler).toBeDefined();
+
+ expect(windowOpenHandler({ url: 'https://github.com/lobehub/lobehub' })).toEqual({
+ action: 'deny',
+ });
+ expect(mockShell.openExternal).toHaveBeenCalledWith('https://github.com/lobehub/lobehub');
+ });
+
+ it('should deny renderer-origin URLs instead of handing them to the OS', () => {
+ expect(windowOpenHandler({ url: 'app://renderer/verify/run-1' })).toEqual({
+ action: 'deny',
+ });
+ expect(mockShell.openExternal).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/desktop/src/preload/routeInterceptor.test.ts b/apps/desktop/src/preload/routeInterceptor.test.ts
index 48ae5f9b94d..58e4b8fac4a 100644
--- a/apps/desktop/src/preload/routeInterceptor.test.ts
+++ b/apps/desktop/src/preload/routeInterceptor.test.ts
@@ -1,6 +1,7 @@
/**
* @vitest-environment happy-dom
*/
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { invoke } from './invoke';
@@ -122,6 +123,45 @@ describe('setupRouteInterceptors', () => {
expect(invoke).not.toHaveBeenCalledWith('windows.interceptRoute', expect.anything());
});
+ it('should leave renderer-handled links alone so their onClick can run', async () => {
+ setupRouteInterceptors();
+
+ // An absolute LobeHub URL: a different origin than `app://renderer`, but the
+ // renderer has claimed it and will open it in the portal itself.
+ const link = document.createElement('a');
+ link.href = 'https://app.lobehub.com/verify/run-1';
+ link.setAttribute(RENDERER_HANDLED_LINK_ATTR, 'true');
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ const preventDefaultSpy = vi.spyOn(clickEvent, 'preventDefault');
+ const stopPropagationSpy = vi.spyOn(clickEvent, 'stopPropagation');
+
+ link.dispatchEvent(clickEvent);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(invoke).not.toHaveBeenCalled();
+ expect(preventDefaultSpy).not.toHaveBeenCalled();
+ expect(stopPropagationSpy).not.toHaveBeenCalled();
+ });
+
+ it('should still intercept unclaimed links pointing at the same host', async () => {
+ setupRouteInterceptors();
+
+ const link = document.createElement('a');
+ link.href = 'https://app.lobehub.com/api/webhooks';
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ link.dispatchEvent(clickEvent);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'system.openExternalLink',
+ 'https://app.lobehub.com/api/webhooks',
+ );
+ });
+
it('should handle non-HTTP link protocols as external links', async () => {
setupRouteInterceptors();
diff --git a/apps/desktop/src/preload/routeInterceptor.ts b/apps/desktop/src/preload/routeInterceptor.ts
index e89b3205db6..cba627d308a 100644
--- a/apps/desktop/src/preload/routeInterceptor.ts
+++ b/apps/desktop/src/preload/routeInterceptor.ts
@@ -1,3 +1,5 @@
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
+
import { findMatchingRoute } from '~common/routes';
import { invoke } from './invoke';
@@ -25,6 +27,10 @@ export const setupRouteInterceptors = function () {
async (e) => {
const link = (e.target as HTMLElement).closest('a');
if (link && link.href) {
+ // The renderer claims this link and will call preventDefault() itself.
+ // Return without stopPropagation() so its onClick still receives the event.
+ if (link.hasAttribute(RENDERER_HANDLED_LINK_ATTR)) return;
+
try {
const url = new URL(link.href);
diff --git a/packages/desktop-bridge/src/index.ts b/packages/desktop-bridge/src/index.ts
index 855ab06d5aa..7134a8169cf 100644
--- a/packages/desktop-bridge/src/index.ts
+++ b/packages/desktop-bridge/src/index.ts
@@ -8,6 +8,17 @@ export {
RouteVariants,
} from './routeVariants';
+/**
+ * Marks an anchor whose click the renderer handles itself (Portal / SPA navigation).
+ *
+ * The desktop renderer runs on the `app://renderer` origin, so the preload click
+ * interceptor cannot tell an internal LobeHub URL from a third-party one by origin
+ * alone. The renderer β€” which owns the route semantics, including runtime-only data
+ * like workspace slugs β€” declares ownership with this attribute, and the interceptor
+ * leaves those clicks untouched so the React `onClick` can run.
+ */
+export const RENDERER_HANDLED_LINK_ATTR = 'data-lobe-renderer-link';
+
// Desktop window constants
export const TITLE_BAR_HEIGHT = 38;
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx
index abe85c91766..b8626250d34 100644
--- a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx
@@ -1,5 +1,7 @@
'use client';
+import { isDesktop } from '@lobechat/const';
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { BotIcon, CheckCircleIcon, CheckSquareIcon, FileTextIcon } from 'lucide-react';
@@ -80,9 +82,13 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,
const handleClick = useCallback(
async (event: MouseEvent<HTMLAnchorElement>) => {
- if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
- return;
- }
+ if (event.button !== 0) return;
+
+ // On the web a modifier-click means "open in a new tab", so let the browser
+ // handle it. Desktop has no tabs: falling through would hand the OS an
+ // `app://renderer/...` URL, which silently opens nothing.
+ const modifierClick = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
+ if (!isDesktop && modifierClick) return;
event.preventDefault();
@@ -148,6 +154,7 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,
const link = (
<a
+ {...{ [RENDERER_HANDLED_LINK_ATTR]: 'true' }}
className={styles.link}
href={href}
rel="noopener noreferrer"
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
index a4166f435ae..ab3fd8b7d1a 100644
--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
@@ -1,11 +1,21 @@
/**
* @vitest-environment happy-dom
*/
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { fireEvent, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import Render from './index';
+let mockIsDesktop = false;
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ get isDesktop() {
+ return mockIsDesktop;
+ },
+}));
+
// `enableMessageLinkIcon` is read via useUserStore(selector). We drive the
// selector's return value through this module-level flag so each case can flip
// the "Link Icon" setting on/off without a real store.
@@ -69,6 +79,7 @@ const renderLink = (properties: Record<string, unknown>) =>
afterEach(() => {
mockShowIcon = true;
+ mockIsDesktop = false;
});
beforeEach(() => {
@@ -196,7 +207,7 @@ describe('Link Render β€” internal entities', () => {
expect(mockNavigate).not.toHaveBeenCalled();
});
- it('preserves modifier-click browser behavior', () => {
+ it('preserves modifier-click browser behavior on web', () => {
const { getByRole } = renderLink({
linkHref: '/task/T-198',
linkKind: 'generic',
@@ -208,6 +219,49 @@ describe('Link Render β€” internal entities', () => {
expect(mockOpenTaskDetail).not.toHaveBeenCalled();
});
+ it('takes over modifier-clicks on desktop, which has no new tab to open', () => {
+ mockIsDesktop = true;
+
+ const { getByRole } = renderLink({
+ linkHref: '/task/T-198',
+ linkKind: 'generic',
+ linkLabel: 'T-198',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'T-198' }), { metaKey: true });
+
+ expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198');
+ });
+});
+
+// The desktop preload intercepts every anchor click in the capture phase and, unless
+// the renderer has claimed the link, stops propagation before React's onClick runs.
+// Dropping this attribute would silently send internal links to the system browser.
+describe('Link Render β€” desktop preload contract', () => {
+ it('marks internal entity links as renderer-handled', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/verify/run-1',
+ linkKind: 'generic',
+ linkLabel: 'Verify report',
+ });
+
+ expect(getByRole('link', { name: 'Verify report' })).toHaveAttribute(
+ RENDERER_HANDLED_LINK_ATTR,
+ 'true',
+ );
+ });
+
+ it('leaves external links unclaimed so the preload opens them in the system browser', () => {
+ const { container } = renderLink({
+ linkDomain: 'github.com',
+ linkHref: 'https://github.com/lobehub/lobehub',
+ linkKind: 'github',
+ linkLabel: 'lobehub/lobehub',
+ });
+
+ expect(container.querySelector('a')).not.toHaveAttribute(RENDERER_HANDLED_LINK_ATTR);
+ });
+
it('navigates non-entity app routes without leaving the SPA', () => {
const { getByRole } = renderLink({
linkHref: '/settings/profile',
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
index 977f1513a77..3d7cf8f5740 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
@@ -1,6 +1,7 @@
/**
* @vitest-environment happy-dom
*/
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -124,6 +125,24 @@ describe('LocalFileLink Render', () => {
expect(useChatStore.getState().showPortal).toBe(true);
});
+ it('claims the link so the desktop preload does not open it in the system browser', () => {
+ render(
+ <Render
+ {...createRenderProps({
+ linkHref: '/Users/me/project/src/Group.tsx',
+ linkLabel: 'Group.tsx',
+ })}
+ />,
+ );
+
+ const link = screen.getByRole('link', { name: 'Group.tsx' });
+ expect(link).toHaveAttribute(RENDERER_HANDLED_LINK_ATTR, 'true');
+
+ // A modifier-click has no meaning on desktop β€” the portal still takes it.
+ fireEvent.click(link, { metaKey: true });
+ expect(useChatStore.getState().openLocalFiles).toHaveLength(1);
+ });
+
it('marks links outside the current workspace as user-approved external previews', () => {
useChatStore.setState({
activeAgentId: 'agent-1',
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
index ea07d95509b..68e26ec500f 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
@@ -1,6 +1,7 @@
'use client';
import { isDesktop } from '@lobechat/const';
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { A, Tooltip } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import type { MouseEvent } from 'react';
@@ -86,10 +87,10 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
const handleClick = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
+ // `parsed` is only non-null on desktop, where a local path has no meaningful
+ // modifier-click behaviour β€” always take over the click.
if (!parsed) return;
- if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
- return;
- }
+ if (event.button !== 0) return;
event.preventDefault();
openLocalFile({
@@ -103,7 +104,12 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
return (
<Tooltip mouseEnterDelay={0.1} placement={'topLeft'} title={title}>
- <A className={styles.link} href={linkHref} onClick={handleClick}>
+ <A
+ {...(parsed ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}
+ className={styles.link}
+ href={linkHref}
+ onClick={handleClick}
+ >
<span aria-hidden className={styles.icon}>
<FileIcon fileName={iconFileName} size={16} variant={'raw'} />
</span>