Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(native): make browser targets clickable (#1098)

yxlyx4acde52579ac
diff --git a/apps/native/components/primitives/BrowserLinks.tsx b/apps/native/components/primitives/BrowserLinks.tsx
new file mode 100644
index 00000000..7c5a2dd9
--- /dev/null
+++ b/apps/native/components/primitives/BrowserLinks.tsx
@@ -0,0 +1,32 @@
+import { Children, Fragment, type ReactNode } from "react";
+import { browserLinkSegments } from "@/lib/browser-links";
+
+export const BROWSER_LINK_CLASS =
+ "cursor-pointer text-ink underline decoration-line underline-offset-2 transition-colors hover:decoration-ink";
+
+export function BrowserLink({ href, children, className = BROWSER_LINK_CLASS }: {
+ href: string;
+ children: ReactNode;
+ className?: string;
+}) {
+ return <a href={href} target="_blank" rel="noreferrer" className={className}>{children}</a>;
+}
+
+export function linkifyBrowserChildren(children: ReactNode): ReactNode {
+ return Children.map(children, (child, childIndex) => {
+ if (typeof child !== "string") return child;
+ return browserLinkSegments(child).map((segment, segmentIndex) =>
+ segment.kind === "text" ? (
+ <Fragment key={`${childIndex}-text-${segmentIndex}`}>{segment.value}</Fragment>
+ ) : (
+ <BrowserLink key={`${childIndex}-link-${segmentIndex}`} href={segment.href}>
+ {segment.label}
+ </BrowserLink>
+ ),
+ );
+ });
+}
+
+export function BrowserLinkText({ text }: { text: string }) {
+ return <>{linkifyBrowserChildren(text)}</>;
+}
diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsx
index 09b99b31..163cbe38 100644
--- a/apps/native/components/primitives/Markdown.tsx
+++ b/apps/native/components/primitives/Markdown.tsx
@@ -4,7 +4,9 @@ import { useMemo, type JSX, type ReactNode } from "react";
import { Streamdown, type Components, type ControlsConfig, type ExtraProps } from "streamdown";
import { code } from "@/lib/code-highlighter";
import StreamingCode from "./StreamingCode";
+import { BrowserLink, BROWSER_LINK_CLASS, linkifyBrowserChildren } from "./BrowserLinks";
import { stripCiteMarkup } from "@/lib/cite-markup";
+import { normalizeBrowserTarget } from "@/lib/browser-links";
/* ─────────────────────────────────────────────────────────
* MARKDOWN
@@ -49,8 +51,8 @@ function textOf(node: ReactNode): string {
function heading(level: 1 | 2 | 3 | 4 | 5 | 6) {
const Tag = `h${level}` as const;
- return function Heading({ node: _node, className: _className, ...rest }: El<typeof Tag>) {
- return <Tag {...rest} className={HEADING_STYLE[level]} />;
+ return function Heading({ node: _node, className: _className, children, ...rest }: El<typeof Tag>) {
+ return <Tag {...rest} className={HEADING_STYLE[level]}>{linkifyBrowserChildren(children)}</Tag>;
};
}
@@ -63,14 +65,18 @@ const STATIC_COMPONENTS: Components = {
h4: heading(4),
h5: heading(5),
h6: heading(6),
- p: ({ node: _node, className: _className, ...rest }) => <p {...rest} className="[&+p]:mt-3" />,
+ p: ({ node: _node, className: _className, children, ...rest }) => (
+ <p {...rest} className="[&+p]:mt-3">{linkifyBrowserChildren(children)}</p>
+ ),
ul: ({ node: _node, className: _className, ...rest }) => (
<ul {...rest} className="list-disc pl-5 marker:text-ink-3 [&>li+li]:mt-1 [li_&]:mt-1" />
),
ol: ({ node: _node, className: _className, ...rest }) => (
<ol {...rest} className="list-decimal pl-5 marker:text-ink-3 [&>li+li]:mt-1 [li_&]:mt-1" />
),
- li: ({ node: _node, className: _className, ...rest }) => <li {...rest} className="pl-0.5" />,
+ li: ({ node: _node, className: _className, children, ...rest }) => (
+ <li {...rest} className="pl-0.5">{linkifyBrowserChildren(children)}</li>
+ ),
blockquote: ({ node: _node, className: _className, ...rest }) => (
<blockquote {...rest} className="border-l-2 border-line pl-3 text-ink-2 [&>p+p]:mt-2" />
),
@@ -79,42 +85,55 @@ const STATIC_COMPONENTS: Components = {
{...rest}
target="_blank"
rel="noreferrer"
- className="text-ink underline decoration-line underline-offset-2 hover:decoration-ink"
+ className={BROWSER_LINK_CLASS}
>
{children}
</a>
),
hr: ({ node: _node, className: _className, ...rest }) => <hr {...rest} className="border-line" />,
- strong: ({ node: _node, className: _className, ...rest }) => <strong {...rest} className="font-semibold text-ink" />,
- del: ({ node: _node, className: _className, ...rest }) => <del {...rest} className="text-ink-3" />,
+ strong: ({ node: _node, className: _className, children, ...rest }) => (
+ <strong {...rest} className="font-semibold text-ink">{linkifyBrowserChildren(children)}</strong>
+ ),
+ em: ({ node: _node, className: _className, children, ...rest }) => (
+ <em {...rest}>{linkifyBrowserChildren(children)}</em>
+ ),
+ del: ({ node: _node, className: _className, children, ...rest }) => (
+ <del {...rest} className="text-ink-3">{linkifyBrowserChildren(children)}</del>
+ ),
thead: ({ node: _node, className: _className, ...rest }) => <thead {...rest} className="border-b border-line bg-inset" />,
tr: ({ node: _node, className: _className, ...rest }) => <tr {...rest} className="border-b border-line last:border-0" />,
- th: ({ node: _node, className: _className, ...rest }) => (
- <th {...rest} className="px-2.5 py-1.5 text-left text-[12.5px] font-semibold whitespace-nowrap text-ink" />
+ th: ({ node: _node, className: _className, children, ...rest }) => (
+ <th {...rest} className="px-2.5 py-1.5 text-left text-[12.5px] font-semibold whitespace-nowrap text-ink">
+ {linkifyBrowserChildren(children)}
+ </th>
),
- td: ({ node: _node, className: _className, ...rest }) => (
- <td {...rest} className="px-2.5 py-1.5 align-top text-[12.5px] text-ink-2" />
+ td: ({ node: _node, className: _className, children, ...rest }) => (
+ <td {...rest} className="px-2.5 py-1.5 align-top text-[12.5px] text-ink-2">
+ {linkifyBrowserChildren(children)}
+ </td>
),
};
function inlineCode(onOpen?: (path: string) => void) {
return function InlineCode({ node: _node, className: _className, children, ...rest }: El<"code">) {
const text = textOf(children);
+ const href = normalizeBrowserTarget(text);
// `src/acp.zig:96` and `file.md:7-31` open the file; the line ref is display-only.
const target = text.replace(/\/$/, "").replace(/:\d+(?:[-–]\d+)?$/, "");
- const pathish = onOpen !== undefined && PATHISH.test(target);
- return (
+ const pathish = href == null && onOpen !== undefined && PATHISH.test(target);
+ const codeNode = (
<code
{...rest}
onClick={pathish ? () => onOpen(target) : undefined}
- title={pathish ? `Open ${stripCiteMarkup(text)}` : undefined}
+ title={pathish ? `Open ${stripCiteMarkup(text)}` : href ?? undefined}
className={`rounded-[4px] bg-inset px-1 py-px font-mono text-[0.92em] text-ink shadow-hairline ${
- pathish ? "cursor-pointer underline decoration-line underline-offset-2 transition-colors hover:bg-hover hover:decoration-ink" : ""
+ pathish || href ? "cursor-pointer underline decoration-line underline-offset-2 transition-colors hover:bg-hover hover:decoration-ink" : ""
}`}
>
{children}
</code>
);
+ return href == null ? codeNode : <BrowserLink href={href}>{codeNode}</BrowserLink>;
};
}
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index 3a5806fd..9c1a1bf2 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -2,6 +2,7 @@
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
import Markdown from "@/components/primitives/Markdown";
+import { BrowserLinkText } from "@/components/primitives/BrowserLinks";
import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips, { type LiveDiff } from "@/components/primitives/ToolChips";
import ApprovalCard from "@/components/primitives/ApprovalCard";
@@ -119,7 +120,7 @@ export const UserBubble = memo(function UserBubble({ text, onEdit }: { text: str
<IconArrowUp size={14} />
</button>
</div>
- </> : words}
+ </> : <BrowserLinkText text={words} />}
</div>
</div>}
</div>
diff --git a/apps/native/electron/markdown-links.test.cjs b/apps/native/electron/markdown-links.test.cjs
new file mode 100644
index 00000000..741a2dcf
--- /dev/null
+++ b/apps/native/electron/markdown-links.test.cjs
@@ -0,0 +1,54 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const React = require('react');
+const { renderToStaticMarkup } = require('react-dom/server');
+
+const REPORTED_URL = 'http://localhost:3090/visual-tests/radius-preview';
+
+async function components() {
+ const [{ default: Markdown }, { BrowserLinkText }] = await Promise.all([
+ import('../components/primitives/Markdown.tsx'),
+ import('../components/primitives/BrowserLinks.tsx'),
+ ]);
+ return { Markdown, BrowserLinkText };
+}
+
+test('the reported inline-code URL is a clickable browser link', async () => {
+ const { Markdown } = await components();
+ const html = renderToStaticMarkup(React.createElement(Markdown, { text: `Open \`${REPORTED_URL}\`.` }));
+ assert.match(html, new RegExp(`<a href="${REPORTED_URL}"`));
+ assert.match(html, new RegExp(`<code title="${REPORTED_URL}"`));
+ assert.match(html, new RegExp(`>${REPORTED_URL}</code>`));
+});
+
+test('assistant prose autolinks bare browser destinations and formatting', async () => {
+ const { Markdown } = await components();
+ const html = renderToStaticMarkup(React.createElement(Markdown, {
+ text: 'Visit example.com, **www.example.org/docs**, or http://localhost:3000.',
+ }));
+ assert.match(html, /href="https:\/\/example\.com\/"/);
+ assert.match(html, /href="http:\/\/www\.example\.org\/docs"/);
+ assert.match(html, /href="http:\/\/localhost:3000\/"/);
+ assert.match(html, /<strong/);
+});
+
+test('explicit Markdown anchors and file-like inline code keep their meanings', async () => {
+ const { Markdown } = await components();
+ const html = renderToStaticMarkup(React.createElement(Markdown, {
+ text: '[Docs](https://example.com/docs) and `README.md`',
+ onOpenPath() {},
+ }));
+ assert.equal(html.match(/<a\b/g)?.length, 1);
+ assert.match(html, /href="https:\/\/example\.com\/docs"/);
+ assert.match(html, /title="Open README\.md"/);
+});
+
+test('raw user-message text links browser destinations without swallowing punctuation', async () => {
+ const { BrowserLinkText } = await components();
+ const html = renderToStaticMarkup(React.createElement(BrowserLinkText, {
+ text: `Try ${REPORTED_URL} or www.example.com.`,
+ }));
+ assert.match(html, new RegExp(`href="${REPORTED_URL}"`));
+ assert.match(html, /href="https:\/\/www\.example\.com\/"/);
+ assert.match(html, /<\/a>\.$/);
+});
diff --git a/apps/native/lib/browser-links.test.ts b/apps/native/lib/browser-links.test.ts
new file mode 100644
index 00000000..707dd393
--- /dev/null
+++ b/apps/native/lib/browser-links.test.ts
@@ -0,0 +1,61 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { browserLinkSegments, normalizeBrowserTarget } from "./browser-links.ts";
+
+describe("normalizeBrowserTarget", () => {
+ it("accepts explicit, named, and local browser destinations", () => {
+ assert.equal(normalizeBrowserTarget("https://example.com/docs"), "https://example.com/docs");
+ assert.equal(normalizeBrowserTarget("http://localhost:3090/visual-tests/radius-preview"), "http://localhost:3090/visual-tests/radius-preview");
+ assert.equal(normalizeBrowserTarget("www.example.com/docs"), "https://www.example.com/docs");
+ assert.equal(normalizeBrowserTarget("example.com"), "https://example.com/");
+ assert.equal(normalizeBrowserTarget("localhost:3000"), "http://localhost:3000/");
+ assert.equal(normalizeBrowserTarget("192.168.1.20:8080/health"), "http://192.168.1.20:8080/health");
+ });
+
+ it("rejects unsafe, credential-bearing, and file-like lookalikes", () => {
+ for (const value of [
+ "javascript:alert(1)",
+ "file:///tmp/example.com",
+ "https://user:[email protected]",
+ "README.md",
+ "component.tsx",
+ "src/example.com",
+ "999.1.1.1",
+ ]) assert.equal(normalizeBrowserTarget(value), null, value);
+ });
+});
+
+describe("browserLinkSegments", () => {
+ it("keeps sentence punctuation and wrappers outside the link", () => {
+ assert.deepEqual(browserLinkSegments("Open (example.com), then www.example.org/docs."), [
+ { kind: "text", value: "Open (" },
+ { kind: "link", label: "example.com", href: "https://example.com/" },
+ { kind: "text", value: "), then " },
+ { kind: "link", label: "www.example.org/docs", href: "https://www.example.org/docs" },
+ { kind: "text", value: "." },
+ ]);
+ });
+
+ it("preserves balanced URL parentheses", () => {
+ assert.deepEqual(browserLinkSegments("https://en.wikipedia.org/wiki/Foo_(bar)"), [
+ {
+ kind: "link",
+ label: "https://en.wikipedia.org/wiki/Foo_(bar)",
+ href: "https://en.wikipedia.org/wiki/Foo_(bar)",
+ },
+ ]);
+ });
+
+ it("does not link email, unsafe-scheme, or file-path lookalikes", () => {
+ for (const text of [
+ "[email protected] src/example.com README.md",
+ "javascript:example.com mailto:example.com custom:example.com",
+ ]) assert.deepEqual(browserLinkSegments(text), [{ kind: "text", value: text }]);
+ });
+
+ it("recognizes the reported local preview URL exactly", () => {
+ const url = "http://localhost:3090/visual-tests/radius-preview";
+ assert.deepEqual(browserLinkSegments(url), [{ kind: "link", label: url, href: url }]);
+ });
+});
diff --git a/apps/native/lib/browser-links.ts b/apps/native/lib/browser-links.ts
new file mode 100644
index 00000000..d614bffb
--- /dev/null
+++ b/apps/native/lib/browser-links.ts
@@ -0,0 +1,101 @@
+export type BrowserLinkSegment =
+ | { kind: "text"; value: string }
+ | { kind: "link"; label: string; href: string };
+
+const EXPLICIT_HTTP = /^https?:\/\//i;
+const LOCAL_HOST = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\d{1,3}(?:\.\d{1,3}){3})(?::\d{1,5})?(?:[/?#]|$)/i;
+const FILELIKE_SUFFIXES = new Set([
+ "c", "cc", "cpp", "css", "csv", "go", "h", "hpp", "html", "java", "js", "json",
+ "jsx", "lock", "md", "mjs", "py", "rb", "rs", "sh", "sql", "svg", "toml", "ts",
+ "tsx", "txt", "xml", "yaml", "yml", "zig",
+]);
+const CANDIDATE = /https?:\/\/[^\s<>"'`]+|www\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}(?::\d{1,5})?(?:[/?#][^\s<>"'`]*)?|(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\d{1,3}(?:\.\d{1,3}){3})(?::\d{1,5})?(?:[/?#][^\s<>"'`]*)?|(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})(?::\d{1,5})?(?:[/?#][^\s<>"'`]*)?/giu;
+const TRAILING_PUNCTUATION = /[.,;:!?]+$/u;
+const CLOSERS: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
+
+function trimCandidate(raw: string): string {
+ let value = raw;
+ let changed = true;
+ while (changed && value.length > 0) {
+ changed = false;
+ const withoutPunctuation = value.replace(TRAILING_PUNCTUATION, "");
+ if (withoutPunctuation !== value) {
+ value = withoutPunctuation;
+ changed = true;
+ continue;
+ }
+ const last = value.at(-1);
+ const opener = last == null ? undefined : CLOSERS[last];
+ if (last != null && opener != null) {
+ const opens = value.split(opener).length - 1;
+ const closes = value.split(last).length - 1;
+ if (closes > opens) {
+ value = value.slice(0, -1);
+ changed = true;
+ }
+ }
+ }
+ return value;
+}
+
+function hasSafeBoundary(text: string, start: number): boolean {
+ if (start === 0) return true;
+ const before = text.slice(0, start);
+ if (/[A-Za-z][A-Za-z0-9+.-]*:$/u.test(before)) return false;
+ return !/[A-Za-z0-9_@./\\-]/u.test(text[start - 1] ?? "");
+}
+
+function hasValidIpv4(hostname: string): boolean {
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/u.test(hostname)) return true;
+ return hostname.split(".").every(part => Number(part) <= 255);
+}
+
+function looksFilelikeHostname(hostname: string, raw: string): boolean {
+ if (raw.toLowerCase().startsWith("www.")) return false;
+ const labels = hostname.toLowerCase().split(".");
+ return labels.length === 2 && FILELIKE_SUFFIXES.has(labels[1] ?? "");
+}
+
+/** Turn text that clearly names a browser destination into a safe HTTP(S) href.
+ * Bare public hosts use HTTPS; localhost and numeric addresses use HTTP. */
+export function normalizeBrowserTarget(raw: string): string | null {
+ const value = trimCandidate(raw.trim());
+ if (!value || /\s/u.test(value)) return null;
+ const explicit = EXPLICIT_HTTP.test(value);
+ const local = LOCAL_HOST.test(value);
+ if (!explicit && !local && !/^www\./i.test(value) && !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})(?::\d{1,5})?(?:[/?#]|$)/i.test(value)) return null;
+
+ try {
+ const url = new URL(explicit ? value : `${local ? "http" : "https"}://${value}`);
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || !url.hostname) return null;
+ if (!hasValidIpv4(url.hostname) || looksFilelikeHostname(url.hostname, value)) return null;
+ return url.href;
+ } catch {
+ return null;
+ }
+}
+
+export function browserLinkSegments(text: string): BrowserLinkSegment[] {
+ const links: Array<{ start: number; end: number; label: string; href: string }> = [];
+ CANDIDATE.lastIndex = 0;
+ let match: RegExpExecArray | null;
+ while ((match = CANDIDATE.exec(text)) !== null) {
+ const start = match.index;
+ if (!hasSafeBoundary(text, start)) continue;
+ const label = trimCandidate(match[0]);
+ const href = normalizeBrowserTarget(label);
+ if (href == null) continue;
+ links.push({ start, end: start + label.length, label, href });
+ }
+ if (links.length === 0) return [{ kind: "text", value: text }];
+
+ const segments: BrowserLinkSegment[] = [];
+ let cursor = 0;
+ for (const link of links) {
+ if (link.start > cursor) segments.push({ kind: "text", value: text.slice(cursor, link.start) });
+ segments.push({ kind: "link", label: link.label, href: link.href });
+ cursor = link.end;
+ }
+ if (cursor < text.length) segments.push({ kind: "text", value: text.slice(cursor) });
+ return segments;
+}