Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion apps/desktop/src-electron/main/window.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { resolveRendererDevUrl, resolveWindowIconPath } from "./window";
import {
resolveRendererDevUrl,
resolveWindowIconPath,
shouldOpenInSystemBrowser,
} from "./window";

describe("resolveRendererDevUrl", () => {
it("returns the dev URL for unpackaged builds", () => {
Expand Down Expand Up @@ -65,3 +69,21 @@ describe("resolveWindowIconPath", () => {
).toBeUndefined();
});
});

describe("shouldOpenInSystemBrowser", () => {
it("allows website and email links", () => {
expect(shouldOpenInSystemBrowser("https://example.com/docs")).toBe(
true,
);
expect(shouldOpenInSystemBrowser("http://localhost:3000")).toBe(true);
expect(shouldOpenInSystemBrowser("mailto:team@example.com")).toBe(true);
});

it("blocks app, file, and malformed URLs", () => {
expect(shouldOpenInSystemBrowser("neverwrite://clip")).toBe(false);
expect(shouldOpenInSystemBrowser("file:///Users/test/note.md")).toBe(
false,
);
expect(shouldOpenInSystemBrowser("not a url")).toBe(false);
});
});
28 changes: 27 additions & 1 deletion apps/desktop/src-electron/main/window.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { app, BrowserWindow, nativeTheme } from "electron";
import { app, BrowserWindow, nativeTheme, shell } from "electron";
import { ELECTRON_IPC } from "../shared/ipc";
import { writeAppLog } from "./appLogger";
import { removeWindowVaultRoute } from "./shellState";
Expand Down Expand Up @@ -44,6 +44,7 @@ function readTrafficLightPosition(

const windowsByLabel = new Map<string, BrowserWindow>();
const labelsByWebContentsId = new Map<number, string>();
const SYSTEM_BROWSER_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);

function preloadPath() {
return fileURLToPath(
Expand Down Expand Up @@ -174,6 +175,30 @@ function getOptionalNumber(
: undefined;
}

export function shouldOpenInSystemBrowser(url: string) {
try {
return SYSTEM_BROWSER_PROTOCOLS.has(new URL(url).protocol);
} catch {
return false;
}
}

function bindExternalWindowOpenHandler(window: BrowserWindow) {
window.webContents.setWindowOpenHandler(({ url }) => {
if (shouldOpenInSystemBrowser(url)) {
void shell.openExternal(url).catch((error: unknown) => {
writeAppLog("main", "error", "Failed to open external link", {
url,
error:
error instanceof Error ? error.message : String(error),
});
});
}

return { action: "deny" };
});
}

function bindWindowLifecycle(label: string, window: BrowserWindow) {
const webContentsId = window.webContents.id;
windowsByLabel.set(label, window);
Expand Down Expand Up @@ -384,6 +409,7 @@ export function createAppWindow(
},
});

bindExternalWindowOpenHandler(window);
bindWindowLifecycle(label, window);

const rendererEntry = resolveRendererEntry(search);
Expand Down
17 changes: 17 additions & 0 deletions apps/desktop/src/features/ai/components/MarkdownContent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,23 @@ describe("MarkdownContent", () => {
).not.toBeInTheDocument();
});

it("renders raw http and https URLs as external links", () => {
renderComponent(
<MarkdownContent
content="Read https://example.com/docs and try http://localhost:3000."
pillMetrics={pillMetrics}
/>,
);

expect(
screen.getByRole("link", { name: "https://example.com/docs" }),
).toHaveAttribute("href", "https://example.com/docs");
expect(
screen.getByRole("link", { name: "http://localhost:3000" }),
).toHaveAttribute("href", "http://localhost:3000");
expect(document.body).toHaveTextContent("http://localhost:3000.");
});

it("opens relative markdown text file links in a new tab from the context menu", async () => {
const invokeMock = vi.mocked(invoke);
invokeMock.mockImplementation(async (command, args) => {
Expand Down
56 changes: 37 additions & 19 deletions apps/desktop/src/features/ai/components/MarkdownContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,34 @@ type InlineContextMenuHandler = (
reference: string,
) => void;

function renderExternalLink(key: number, href: string, label = href) {
return (
<a
key={key}
href={href}
target="_blank"
rel="noopener noreferrer"
style={{
color: "var(--accent)",
whiteSpace: "normal",
overflowWrap: "anywhere",
wordBreak: "break-word",
}}
className="underline"
>
{label}
</a>
);
}

function splitTrailingUrlPunctuation(url: string) {
const match = /^(.+?)([.,!?;:]*)$/.exec(url);
return {
href: match?.[1] ?? url,
trailing: match?.[2] ?? "",
};
}

function renderInlineMarkdown(
text: string,
pillMetrics: ChatPillMetrics,
Expand All @@ -337,9 +365,9 @@ function renderInlineMarkdown(
onFileContextMenu?: InlineContextMenuHandler,
): Array<string | ReactElement> {
const parts: Array<string | ReactElement> = [];
// Process: wikilinks, inline code, bold, italic, links, and absolute vault file paths.
// Process: wikilinks, inline code, bold, italic, links, raw URLs, and absolute vault file paths.
const inlineRegex =
/(\[\[[^\]]+\]\])|(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\([^)]+\))|((?<![\w\u00C0-\u024F])(?:\/)[\w\u00C0-\u024F~.()/-]+(?::\d+|#L\d+)?)/g;
/(\[\[[^\]]+\]\])|(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\([^)]+\))|(\bhttps?:\/\/[^\s<>"']+)|((?<![\w\u00C0-\u024F])(?:\/)[\w\u00C0-\u024F~.()/-]+(?::\d+|#L\d+)?)/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
let keyIndex = 0;
Expand Down Expand Up @@ -592,26 +620,16 @@ function renderInlineMarkdown(
/>,
);
} else {
parts.push(
<a
key={key}
href={url}
target="_blank"
rel="noopener noreferrer"
style={{
color: "var(--accent)",
whiteSpace: "normal",
overflowWrap: "anywhere",
wordBreak: "break-word",
}}
className="underline"
>
{linkMatch[1]}
</a>,
);
parts.push(renderExternalLink(key, url, linkMatch[1]));
}
}
} else if (match[6]) {
const { href, trailing } = splitTrailingUrlPunctuation(full);
parts.push(renderExternalLink(key, href));
if (trailing) {
parts.push(trailing);
}
} else if (match[7]) {
// Absolute vault file path.
const filePath = safeDecodeUriComponent(full);
const excalidrawRef = parseExcalidrawReference(filePath);
Expand Down
Loading