Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type KeybindingCommand,
4 type KeybindingShortcut,
5 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
6 type ScopedThreadRef,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8} from "@t3tools/contracts";
9import {
10 type HtmlRenderShortcut,
11 htmlRenderShortcutsMessage,
12 htmlRenderThemeFragment,
13 htmlRenderThemeMessage,
14 htmlRenderResult,
15 readHtmlRenderContentHeight,
16 readHtmlRenderImageRequest,
17 readHtmlRenderKeyDown,
18 readHtmlRenderLinkRequest,
19} from "@t3tools/shared/htmlRender";
20import {
21 isMacPlatform,
22 matchesKeybindingShortcut,
23 normalizeEventKey,
24} from "@t3tools/shared/keybindings";
25import { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react";
26
27import { useOpenLink } from "~/browser/useOpenLink";
28import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
29import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
30import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
31import { shortcutConflictKey } from "~/keybindings";
32import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
33import { readLocalApi } from "~/localApi";
34import { cn } from "~/lib/utils";
35import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
36
37/**
38 * Chromium's viewer opens with its own toolbar, a thumbnail rail and a small
39 * zoom. The panel header is the only chrome we want, so ask for the page
40 * alone, fitted to the panel width. Pinch and keyboard zoom, scrolling, text
41 * selection and find still work inside the frame.
42 */
43const PDF_VIEWER_FRAGMENT = "#toolbar=0&view=FitH";
44
45/**
46 * Shortcuts that still work while a focused HTML render holds the keyboard.
47 * The page reports the keys, and a page script can report any key it likes,
48 * so only commands that change what the reader sees are here, never one that
49 * changes a thread.
50 */
51const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
52 "commandPalette.toggle",
53 "filePicker.toggle",
54 "projectSearch.toggle",
55 "chat.find",
56 "sidebar.toggle",
57 "rightPanel.toggle",
58 "rightPanel.toggleMaximized",
59 "threadPanel.toggle",
60 "terminal.toggle",
61 "preview.toggle",
62 "navigation.back",
63 "navigation.forward",
64 "thread.previous",
65 "thread.next",
66 ...THREAD_JUMP_KEYBINDING_COMMANDS,
67 // Share Cmd/Ctrl+digit with thread jumps, and act only while the picker is open.
68 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
69]);
70
71export const isPdfPreviewFile = (path: string): boolean =>
72 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
73
74/**
75 * Renders an HTML or PDF document from its URL. HTML runs in a sandboxed frame
76 * with an opaque origin, so a page cannot reach the app's session or storage.
77 * The built-in PDF viewer needs an unsandboxed frame; a PDF runs no scripts.
78 * An agent's HTML render also wears the app theme.
79 */
80export function BrowserDocumentFrame(props: {
81 readonly src: string;
82 readonly title: string;
83 readonly pdf: boolean;
84 readonly htmlRender?: boolean;
85 /** The thread an HTML render's links open beside. */
86 readonly threadRef?: ScopedThreadRef | undefined;
87}) {
88 const className = "min-h-0 flex-1 border-0 bg-white";
89 return props.pdf ? (
90 // oxlint-disable-next-line react/iframe-missing-sandbox -- the built-in PDF viewer needs an unsandboxed frame.
91 <iframe
92 key={props.src}
93 src={`${props.src}${PDF_VIEWER_FRAGMENT}`}
94 title={props.title}
95 className={className}
96 />
97 ) : props.htmlRender ? (
98 <HtmlRenderDocument
99 key={props.src}
100 src={props.src}
101 title={props.title}
102 threadRef={props.threadRef}
103 className="min-h-0 flex-1"
104 />
105 ) : (
106 <iframe
107 key={props.src}
108 src={props.src}
109 title={props.title}
110 className={className}
111 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
112 />
113 );
114}
115
116/**
117 * A sandboxed agent HTML render in the app theme. The page reads the theme from
118 * its URL fragment before first paint, then follows changes posted to its
119 * bootstrap. The first URL is kept for the frame's lifetime: signed asset URLs
120 * re-mint while it stays mounted, and a new src would reload the page.
121 */
122export function HtmlRenderDocument(props: {
123 readonly src: string;
124 readonly title: string;
125 readonly className?: string;
126 /** The thread the page's links open beside, as a chat link would. */
127 readonly threadRef?: ScopedThreadRef | undefined;
128 /** Receives the page's content height whenever it changes, so an inline frame can fit it. */
129 readonly onContentHeight?: (height: number) => void;
130 /** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */
131 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
132 /** Called when the page has loaded. */
133 readonly onLoad?: () => void;
134}) {
135 const theme = useHtmlRenderTheme();
136 const frameRef = useRef<HTMLIFrameElement>(null);
137 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
138 const [loaded, setLoaded] = useState(false);
139 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
140 const postTheme = () => {
141 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
142 };
143 useEffect(postTheme, [theme]);
144 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
145 // Chat also resolves project scripts from the thread's own environment.
146 const environmentKeybindings = useAtomValue(
147 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
148 )?.keybindings;
149 // The app resolves a replayed key in its live context, so every allowed
150 // binding counts whatever its `when`, and a key that any binding gives to
151 // another command stays with the page. Only Cmd/Ctrl chords: a printable key
152 // would type into the composer instead.
153 const { shortcuts, blocked } = useMemo(() => {
154 const mac = isMacPlatform(navigator.platform);
155 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
156 key: shortcut.key,
157 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
158 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
159 shiftKey: shortcut.shiftKey,
160 altKey: shortcut.altKey,
161 });
162 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
163 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
164 .map((binding) => resolve(binding.shortcut));
165 const shortcuts = new Map<string, HtmlRenderShortcut>();
166 for (const { command, shortcut } of keybindings) {
167 if (
168 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
169 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
170 ) {
171 shortcuts.set(shortcutConflictKey(shortcut), resolve(shortcut));
172 }
173 }
174 return { shortcuts: [...shortcuts.values()], blocked };
175 }, [environmentKeybindings, keybindings]);
176 const postShortcuts = () => {
177 frameRef.current?.contentWindow?.postMessage(
178 htmlRenderShortcutsMessage(shortcuts, blocked),
179 "*",
180 );
181 };
182 useEffect(postShortcuts, [blocked, shortcuts]);
183 // The page reports the key and code, and a page script can report any pair,
184 // so a key that could match another command's binding is never replayed. A
185 // named key (Backspace, Enter) must be the shortcut's own, since some app
186 // handlers read `event.key` directly. A dead key matches by its code.
187 const isShortcut = useEffectEvent(
188 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
189 const matches = (shortcut: HtmlRenderShortcut) =>
190 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
191 const allowed = shortcuts.filter(matches);
192 return (
193 allowed.length > 0 &&
194 !blocked.some(matches) &&
195 (key.key.length === 1 ||
196 key.key === "Dead" ||
197 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
198 );
199 },
200 );
201 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
202 const openLink = useOpenLink(props.threadRef);
203 // Same rules as a chat link: a pull request opens in the right panel, any
204 // other link follows "Open links in", and Cmd/Ctrl-click goes to the system
205 // browser. Without a thread there is no panel, so it goes to the browser.
206 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
207 // The modifier's destination needs no saved setting, so it never waits on one.
208 if (modifiers.metaKey || modifiers.ctrlKey) {
209 void readLocalApi()
210 ?.shell.openExternal(url)
211 .catch((cause: unknown) => console.error(cause));
212 return;
213 }
214 if (
215 props.threadRef !== undefined &&
216 openChangeRequestLink(
217 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
218 url,
219 undefined,
220 props.threadRef.environmentId,
221 )
222 ) {
223 return;
224 }
225 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
226 });
227 // The page cannot open windows itself (an inline page runs unopened, and
228 // desktop sends any window to the browser). It asks the client, which opens
229 // the link only while this frame has focus and the reader has just used the
230 // app. A page can take focus by script, so this stops opens on load, not a
231 // page that waits for the reader's next click or key.
232 useEffect(() => {
233 const openLink = (event: MessageEvent) => {
234 const frame = frameRef.current;
235 const request = readHtmlRenderLinkRequest(event.data);
236 if (
237 request === undefined ||
238 frame === null ||
239 event.source !== frame.contentWindow ||
240 document.activeElement !== frame ||
241 navigator.userActivation?.isActive === false
242 ) {
243 return;
244 }
245 open(request.url, request);
246 frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
247 };
248 window.addEventListener("message", openLink);
249 return () => window.removeEventListener("message", openLink);
250 }, []);
251 // A focused frame takes every key, so app shortcuts would stop until the
252 // reader clicked out. The page passes on the chords posted to it, which replay
253 // on the frame element and bubble to the app's window listeners. A report is
254 // gated like a link and must be one of those chords.
255 useEffect(() => {
256 const replayKey = (event: MessageEvent) => {
257 const frame = frameRef.current;
258 const key = readHtmlRenderKeyDown(event.data);
259 if (
260 key === undefined ||
261 frame === null ||
262 event.source !== frame.contentWindow ||
263 document.activeElement !== frame ||
264 navigator.userActivation?.isActive === false
265 ) {
266 return;
267 }
268 if (!isShortcut(key)) return;
269 frame.dispatchEvent(
270 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
271 );
272 };
273 window.addEventListener("message", replayKey);
274 return () => window.removeEventListener("message", replayKey);
275 }, []);
276 // A clicked page image opens in the same viewer as chat images, gated like a link.
277 useEffect(() => {
278 const openImage = (event: MessageEvent) => {
279 const frame = frameRef.current;
280 const request = readHtmlRenderImageRequest(event.data);
281 if (
282 request === undefined ||
283 frame === null ||
284 event.source !== frame.contentWindow ||
285 document.activeElement !== frame ||
286 navigator.userActivation?.isActive === false
287 ) {
288 return;
289 }
290 setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
291 };
292 window.addEventListener("message", openImage);
293 return () => window.removeEventListener("message", openImage);
294 }, []);
295 const { onFullscreenChange } = props;
296 useEffect(() => {
297 if (expandedImage === null) return;
298 onFullscreenChange?.(true);
299 return () => onFullscreenChange?.(false);
300 }, [expandedImage, onFullscreenChange]);
301 const { onContentHeight } = props;
302 // A page posts its height once per change, so listen from the commit that
303 // inserts the frame; a passive effect could run after a fast page's first post.
304 useLayoutEffect(() => {
305 if (onContentHeight === undefined) return;
306 const resize = (event: MessageEvent) => {
307 const height = readHtmlRenderContentHeight(event.data);
308 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
309 onContentHeight(height);
310 }
311 };
312 window.addEventListener("message", resize);
313 return () => window.removeEventListener("message", resize);
314 }, [onContentHeight]);
315 return (
316 <>
317 <iframe
318 ref={frameRef}
319 src={src}
320 title={props.title}
321 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
322 sandbox="allow-scripts allow-forms"
323 loading="lazy"
324 onLoad={() => {
325 setLoaded(true);
326 // Covers a theme change that landed while the page was loading.
327 postTheme();
328 postShortcuts();
329 props.onLoad?.();
330 }}
331 // A frame whose color scheme differs from its document's paints an opaque
332 // canvas, so the blank document a frame starts with would flash white in
333 // dark mode. Once the page is in, its prefers-color-scheme follows the app.
334 className={cn("border-0 scheme-light", props.className)}
335 style={loaded ? { colorScheme: theme.appearance } : undefined}
336 />
337 {expandedImage !== null ? (
338 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
339 ) : null}
340 </>
341 );
342}