Skip to content

Commit 5889d9b

Browse files
committed
fix(web): links in HTML renders open like chat links
A pull request opens in the right panel, other links follow the Open links in setting, and Cmd/Ctrl-click goes to the system browser.
1 parent 06620fa commit 5889d9b

7 files changed

Lines changed: 64 additions & 14 deletions

File tree

‎apps/web/src/components/chat/HtmlRenderFrame.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { EnvironmentId } from "@t3tools/contracts";
1+
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
22
import {
33
HTML_RENDER_COLUMN_WIDTH,
44
htmlRenderFileName,
@@ -28,6 +28,7 @@ const MIN_URL_LIFE_MS = 5 * 60_000;
2828
export function HtmlRenderFrame(props: {
2929
readonly environmentId: EnvironmentId;
3030
readonly htmlRender: HtmlRenderReference;
31+
readonly threadRef: ScopedThreadRef | undefined;
3132
readonly onOpen: (attachment: ChatFileAttachment) => void;
3233
}) {
3334
const { attachmentId, title } = props.htmlRender;
@@ -97,6 +98,7 @@ export function HtmlRenderFrame(props: {
9798
<HtmlRenderDocument
9899
src={src}
99100
title={title}
101+
threadRef={props.threadRef}
100102
className="block size-full"
101103
onContentHeight={setContentHeight}
102104
/>

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3052,6 +3052,7 @@ function HtmlRenderTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "htm
30523052
key={row.htmlRender.attachmentId}
30533053
environmentId={ctx.activeThreadEnvironmentId}
30543054
htmlRender={row.htmlRender}
3055+
threadRef={ctx.threadRef ?? undefined}
30553056
onOpen={ctx.onFileOpen}
30563057
/>
30573058
</div>

‎apps/web/src/components/files/AttachmentFilePreview.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
2-
import type { EnvironmentId } from "@t3tools/contracts";
2+
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
33
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
44
import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
55
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
@@ -61,6 +61,8 @@ export function AttachmentFilePreview(props: {
6161
asset?: { environmentId: EnvironmentId; attachmentId: string };
6262
/** An agent's HTML render, shown in the app theme. */
6363
htmlRender?: boolean;
64+
/** The thread an HTML render's links open beside. */
65+
threadRef?: ScopedThreadRef;
6466
/** First crumb: where the file comes from. */
6567
origin?: string;
6668
onRemove?: () => void;
@@ -250,6 +252,7 @@ export function AttachmentFilePreview(props: {
250252
title={props.name}
251253
pdf={kind === "pdf"}
252254
htmlRender={props.htmlRender === true}
255+
threadRef={props.threadRef}
253256
/>
254257
) : kind === "audio" ? (
255258
<AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />

‎apps/web/src/components/files/BrowserDocumentFrame.tsx‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1+
import type { ScopedThreadRef } from "@t3tools/contracts";
12
import {
23
htmlRenderThemeFragment,
34
htmlRenderThemeMessage,
45
htmlRenderResult,
56
readHtmlRenderContentHeight,
67
readHtmlRenderLinkRequest,
78
} from "@t3tools/shared/htmlRender";
8-
import { useEffect, useLayoutEffect, useRef, useState } from "react";
9+
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
910

11+
import { useOpenLink } from "~/browser/useOpenLink";
1012
import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
13+
import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
1114
import { cn } from "~/lib/utils";
1215

1316
/**
@@ -32,6 +35,8 @@ export function BrowserDocumentFrame(props: {
3235
readonly title: string;
3336
readonly pdf: boolean;
3437
readonly htmlRender?: boolean;
38+
/** The thread an HTML render's links open beside. */
39+
readonly threadRef?: ScopedThreadRef | undefined;
3540
}) {
3641
const className = "min-h-0 flex-1 border-0 bg-white";
3742
return props.pdf ? (
@@ -47,6 +52,7 @@ export function BrowserDocumentFrame(props: {
4752
key={props.src}
4853
src={props.src}
4954
title={props.title}
55+
threadRef={props.threadRef}
5056
className="min-h-0 flex-1"
5157
/>
5258
) : (
@@ -70,6 +76,8 @@ export function HtmlRenderDocument(props: {
7076
readonly src: string;
7177
readonly title: string;
7278
readonly className?: string;
79+
/** The thread the page's links open beside, as a chat link would. */
80+
readonly threadRef?: ScopedThreadRef | undefined;
7381
/** Receives the page's content height whenever it changes, so an inline frame can fit it. */
7482
readonly onContentHeight?: (height: number) => void;
7583
}) {
@@ -81,6 +89,25 @@ export function HtmlRenderDocument(props: {
8189
frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
8290
};
8391
useEffect(postTheme, [theme]);
92+
const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
93+
const openLink = useOpenLink(props.threadRef);
94+
// Same rules as a chat link: a pull request opens in the right panel, any
95+
// other link follows "Open links in", and Cmd/Ctrl-click goes to the system
96+
// browser. Without a thread there is no panel, so it goes to the browser.
97+
const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
98+
if (
99+
props.threadRef !== undefined &&
100+
openChangeRequestLink(
101+
{ ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
102+
url,
103+
undefined,
104+
props.threadRef.environmentId,
105+
)
106+
) {
107+
return;
108+
}
109+
void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
110+
});
84111
// The page cannot open windows itself (an inline page runs unopened, and
85112
// desktop sends any window to the browser). It asks the client, which opens
86113
// the link only while this frame has focus and the reader has just used the
@@ -99,7 +126,7 @@ export function HtmlRenderDocument(props: {
99126
) {
100127
return;
101128
}
102-
window.open(request.url, "_blank", "noopener,noreferrer");
129+
open(request.url, request);
103130
frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
104131
};
105132
window.addEventListener("message", openLink);

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,7 @@ export default function FilePreviewPanel({
13521352
sizeBytes={attachment.sizeBytes}
13531353
asset={{ environmentId, attachmentId: attachment.id }}
13541354
htmlRender={attachment.htmlRender === true}
1355+
threadRef={threadRef}
13551356
/>
13561357
) : relativePath && isVideo && absolutePath ? (
13571358
<WorkspaceVideoPreview

‎packages/shared/src/htmlRender.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,21 @@ describe("injectHtmlRenderBootstrap", () => {
7676

7777
describe("readHtmlRenderLinkRequest", () => {
7878
it("accepts only http(s) URLs in an MCP Apps ui/open-link request", () => {
79-
const link = (url: unknown) => ({
79+
const link = (url: unknown, modifiers = {}) => ({
8080
jsonrpc: "2.0",
8181
id: 1,
8282
method: "ui/open-link",
83-
params: { url },
83+
params: { url, ...modifiers },
8484
});
8585
expect(readHtmlRenderLinkRequest(link("https://example.com/a"))).toEqual({
8686
id: 1,
8787
url: "https://example.com/a",
88+
metaKey: false,
89+
ctrlKey: false,
8890
});
91+
expect(
92+
readHtmlRenderLinkRequest(link("https://example.com/a", { metaKey: true, ctrlKey: "yes" })),
93+
).toEqual({ id: 1, url: "https://example.com/a", metaKey: true, ctrlKey: false });
8994
expect(readHtmlRenderLinkRequest(link("javascript:alert(1)"))).toBeUndefined();
9095
expect(readHtmlRenderLinkRequest(link("file:///etc/passwd"))).toBeUndefined();
9196
expect(

‎packages/shared/src/htmlRender.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -287,17 +287,28 @@ export function readHtmlRenderContentHeight(data: unknown): number | undefined {
287287
return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
288288
}
289289

290-
/** A render's `ui/open-link` request, if `data` is one with an http(s) URL. */
291-
export function readHtmlRenderLinkRequest(
292-
data: unknown,
293-
): { readonly id: string | number; readonly url: string } | undefined {
290+
/**
291+
* A render's `ui/open-link` request, if `data` is one with an http(s) URL. The
292+
* bootstrap adds the click's Cmd/Ctrl state, so a modifier click can leave the
293+
* app the way it does from a chat link.
294+
*/
295+
export function readHtmlRenderLinkRequest(data: unknown):
296+
| {
297+
readonly id: string | number;
298+
readonly url: string;
299+
readonly metaKey: boolean;
300+
readonly ctrlKey: boolean;
301+
}
302+
| undefined {
294303
if (typeof data !== "object" || data === null) return undefined;
295304
const { jsonrpc, id, method, params } = data as Record<string, unknown>;
296305
if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
297306
if (typeof id !== "string" && typeof id !== "number") return undefined;
298-
const url =
299-
typeof params === "object" && params !== null ? (params as { url?: unknown }).url : undefined;
300-
return typeof url === "string" && /^https?:\/\//i.test(url) ? { id, url } : undefined;
307+
if (typeof params !== "object" || params === null) return undefined;
308+
const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
309+
return typeof url === "string" && /^https?:\/\//i.test(url)
310+
? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
311+
: undefined;
301312
}
302313

303314
/** The empty result a client sends back for a render's request. */
@@ -345,7 +356,7 @@ function rootRule(theme: HtmlRenderTheme): string {
345356
// opens it as a new window, which the client sends to the browser. A framed
346357
// page also reports its content height, measured as the server measures it,
347358
// so its client can fit the frame to the page.
348-
const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);}})();`;
359+
const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href,metaKey:e.metaKey,ctrlKey:e.ctrlKey}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);}})();`;
349360

350361
function bootstrapMarkup(markup: string): string {
351362
const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");

0 commit comments

Comments
 (0)