The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 465 lines 17.1 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 type KeybindingCommand,
4 type KeybindingShortcut,
5 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
6 type ScopedThreadRef,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8 } from "@t3tools/contracts";
9 import {
10 type FilePreviewScroll,
11 filePreviewRestoreScrollMessage,
12 isFilePreviewScrollRestored,
13 readFilePreviewScroll,
14 type HtmlRenderShortcut,
15 htmlRenderShortcutsMessage,
16 HTML_RENDER_CONTAIN_SCROLL_FRAGMENT,
17 htmlRenderThemeFragment,
18 htmlRenderThemeMessage,
19 htmlRenderResult,
20 readHtmlRenderContentHeight,
21 readHtmlRenderImageRequest,
22 readHtmlRenderKeyDown,
23 readHtmlRenderLinkRequest,
24 } from "@t3tools/shared/htmlRender";
25 import {
26 isMacPlatform,
27 matchesKeybindingShortcut,
28 normalizeEventKey,
29 } from "@t3tools/shared/keybindings";
30 import {
31 lazy,
32 type ReactNode,
33 Suspense,
34 useEffect,
35 useEffectEvent,
36 useLayoutEffect,
37 useRef,
38 useState,
39 } from "react";
40 import { isElectron } from "~/env";
41 import { FileSurfaceLoading } from "./fileSurfaceChrome";
42 import type { PdfViewState } from "./PdfViewer";
43
44 import { useOpenLink } from "~/browser/useOpenLink";
45 import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
46 import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
47 import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
48 import { shortcutConflictKey } from "~/keybindings";
49 import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
50 import { readLocalApi } from "~/localApi";
51 import { cn } from "~/lib/utils";
52 import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
53
54 /**
55 * The page reports the keys, and a page script can report any key it likes,
56 * so only commands that change what the reader sees are here, never one that
57 * changes a thread.
58 */
59 const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
60 "commandPalette.toggle",
61 "filePicker.toggle",
62 "projectSearch.toggle",
63 "chat.find",
64 "sidebar.toggle",
65 "rightPanel.toggle",
66 "rightPanel.toggleMaximized",
67 "threadPanel.toggle",
68 "terminal.toggle",
69 "preview.toggle",
70 "navigation.back",
71 "navigation.forward",
72 "thread.previous",
73 "thread.next",
74 ...THREAD_JUMP_KEYBINDING_COMMANDS,
75 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
76 ]);
77
78 export const isPdfPreviewFile = (path: string): boolean =>
79 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
80
81 const PdfViewer = lazy(() => import("./PdfViewer"));
82
83 // The document stays mounted while each revision gets a fresh PDF.js document.
84 function PdfDocument(props: {
85 src: string;
86 title: string;
87 documentKey: string;
88 actions?: ReactNode;
89 }) {
90 const [view, setView] = useState<PdfViewState>({ page: 0, offset: 0, zoom: null, left: 0 });
91 return (
92 <PdfDocumentRevision
93 key={props.documentKey}
94 src={props.src}
95 title={props.title}
96 positionKey={props.documentKey}
97 initialView={view}
98 onViewChange={setView}
99 actions={props.actions}
100 />
101 );
102 }
103
104 // Keep signed URL renewals from reloading the same revision.
105 function PdfDocumentRevision(props: {
106 src: string;
107 title: string;
108 positionKey: string;
109 initialView: PdfViewState;
110 onViewChange: (view: PdfViewState) => void;
111 actions?: ReactNode;
112 }) {
113 const [src] = useState(props.src);
114 // The Electron shell does not enable PDF plugins. WebKit embeds on iOS
115 // expose only the first page, even when pdfViewerEnabled reports support.
116 const native =
117 !isElectron &&
118 navigator.pdfViewerEnabled &&
119 !/iPad|iPhone|iPod/.test(navigator.userAgent) &&
120 !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
121 return native ? (
122 // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.
123 <iframe
124 src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}
125 title={props.title}
126 className="block h-full min-h-0 w-full flex-1 border-0 bg-white"
127 />
128 ) : (
129 <Suspense fallback={<FileSurfaceLoading />}>
130 <PdfViewer
131 src={src}
132 title={props.title}
133 positionKey={props.positionKey}
134 initialView={props.initialView}
135 onViewChange={props.onViewChange}
136 actions={props.actions}
137 />
138 </Suspense>
139 );
140 }
141
142 /**
143 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
144 * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.
145 */
146 export function BrowserDocumentFrame(props: {
147 readonly src: string;
148 readonly title: string;
149 readonly pdf: boolean;
150 readonly htmlRender?: boolean;
151 readonly threadRef?: ScopedThreadRef | undefined;
152 /** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
153 readonly documentKey?: string | undefined;
154 /** Resource identity without its revision, so PDF reloads can retain the reading position. */
155 readonly documentId?: string | undefined;
156 /** Toolbar actions for the in-app PDF viewer; Chromium's own viewer brings its own. */
157 readonly pdfActions?: ReactNode;
158 }) {
159 const key = props.documentKey ?? props.src;
160 return props.pdf ? (
161 <PdfDocument
162 key={props.documentId ?? key}
163 documentKey={key}
164 src={props.src}
165 title={props.title}
166 actions={props.pdfActions}
167 />
168 ) : props.htmlRender ? (
169 <HtmlRenderDocument
170 key={key}
171 src={props.src}
172 title={props.title}
173 threadRef={props.threadRef}
174 className="min-h-0 flex-1"
175 />
176 ) : (
177 <FileDocument
178 key={props.documentId ?? key}
179 documentKey={key}
180 src={props.src}
181 title={props.title}
182 />
183 );
184 }
185
186 interface FileDocumentRevision {
187 readonly key: string;
188 readonly src: string;
189 }
190
191 interface FileDocumentFrames {
192 readonly shown: FileDocumentRevision;
193 readonly next: FileDocumentRevision | null;
194 }
195
196 // Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one.
197 const showRevision =
198 (next: FileDocumentRevision) =>
199 (current: FileDocumentFrames): FileDocumentFrames =>
200 current.next === next ? { shown: next, next: null } : current;
201
202 // A page whose load never fires (a stalled subresource) must not pin the previous revision.
203 const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000;
204
205 // URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new
206 // revision loads beneath the page on screen, takes its scroll position and replaces it once
207 // painted, so no blank frame shows and the reader keeps their place.
208 function FileDocument(props: {
209 readonly documentKey: string;
210 readonly src: string;
211 readonly title: string;
212 }) {
213 const [frames, setFrames] = useState<FileDocumentFrames>(() => ({
214 shown: { key: props.documentKey, src: props.src },
215 next: null,
216 }));
217 if ((frames.next ?? frames.shown).key !== props.documentKey) {
218 setFrames({
219 shown: frames.shown,
220 next:
221 frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src },
222 });
223 }
224 const { next } = frames;
225 const shownFrame = useRef<HTMLIFrameElement>(null);
226 const nextFrame = useRef<HTMLIFrameElement>(null);
227 // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision
228 // scrolls there before it is uncovered.
229 const scroll = useRef<FilePreviewScroll | null>(null);
230 // Two frames let the browser paint the incoming page before it is uncovered.
231 const reveal = (revision: FileDocumentRevision) =>
232 requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision))));
233 const onFrameMessage = useEffectEvent((event: MessageEvent) => {
234 const position = readFilePreviewScroll(event.data);
235 if (position !== undefined) {
236 if (event.source === shownFrame.current?.contentWindow) scroll.current = position;
237 } else if (
238 next !== null &&
239 event.source === nextFrame.current?.contentWindow &&
240 isFilePreviewScrollRestored(event.data)
241 ) {
242 reveal(next);
243 }
244 });
245 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports
246 useEffect(() => {
247 const onMessage = (event: MessageEvent) => onFrameMessage(event);
248 window.addEventListener("message", onMessage);
249 return () => window.removeEventListener("message", onMessage);
250 }, []);
251 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives
252 useEffect(() => {
253 if (next === null) return;
254 const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS);
255 return () => clearTimeout(timer);
256 }, [next]);
257 // The shown frame stays last so it paints on top and is never moved, which would reload it.
258 return (
259 <div className="relative min-h-0 flex-1">
260 {[next, frames.shown].map((revision) =>
261 revision === null ? null : (
262 <iframe
263 key={revision.key}
264 ref={revision === next ? nextFrame : shownFrame}
265 src={revision.src}
266 title={props.title}
267 className="absolute inset-0 size-full border-0"
268 style={{ backgroundColor: "Canvas" }}
269 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
270 inert={revision === next}
271 aria-hidden={revision === next ? true : undefined}
272 onLoad={
273 revision === next
274 ? (event) => {
275 if (scroll.current === null) {
276 reveal(revision);
277 return;
278 }
279 event.currentTarget.contentWindow?.postMessage(
280 filePreviewRestoreScrollMessage(scroll.current),
281 "*",
282 );
283 }
284 : undefined
285 }
286 />
287 ),
288 )}
289 </div>
290 );
291 }
292
293 /** Keep the initial URL while mounted; re-signing must not reload the page. */
294 export function HtmlRenderDocument(props: {
295 readonly src: string;
296 readonly title: string;
297 readonly className?: string;
298 readonly threadRef?: ScopedThreadRef | undefined;
299 readonly onContentHeight?: (height: number) => void;
300 /** Keeps the page's scrollIntoView calls from scrolling the host, for frames inline in the chat. */
301 readonly containScroll?: boolean | undefined;
302 /** Reports fullscreen changes so virtualized rows can stay mounted. */
303 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
304 }) {
305 const theme = useHtmlRenderTheme();
306 const frameRef = useRef<HTMLIFrameElement>(null);
307 const [src] = useState(
308 () =>
309 `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}${props.containScroll ? HTML_RENDER_CONTAIN_SCROLL_FRAGMENT : ""}`,
310 );
311 const [loaded, setLoaded] = useState(false);
312 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
313 const postTheme = () => {
314 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
315 };
316 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts the current theme to the sandboxed iframe's window
317 useEffect(postTheme, [theme]);
318 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
319 const environmentKeybindings = useAtomValue(
320 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
321 )?.keybindings;
322 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
323 // otherwise type in the composer.
324 const mac = isMacPlatform(navigator.platform);
325 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
326 key: shortcut.key,
327 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
328 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
329 shiftKey: shortcut.shiftKey,
330 altKey: shortcut.altKey,
331 });
332 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
333 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
334 .map((binding) => resolve(binding.shortcut));
335 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
336 for (const { command, shortcut } of keybindings) {
337 if (
338 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
339 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
340 ) {
341 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
342 }
343 }
344 const shortcuts = [...shortcutsByKey.values()];
345 const postShortcuts = () => {
346 frameRef.current?.contentWindow?.postMessage(
347 htmlRenderShortcutsMessage(shortcuts, blocked),
348 "*",
349 );
350 };
351 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts allowed and blocked shortcuts to the sandboxed iframe's window
352 useEffect(postShortcuts, [blocked, shortcuts]);
353 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
354 // shortcut.
355 const isShortcut = useEffectEvent(
356 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
357 const matches = (shortcut: HtmlRenderShortcut) =>
358 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
359 const allowed = shortcuts.filter(matches);
360 return (
361 allowed.length > 0 &&
362 !blocked.some(matches) &&
363 (key.key.length === 1 ||
364 key.key === "Dead" ||
365 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
366 );
367 },
368 );
369 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
370 const openLink = useOpenLink(props.threadRef);
371 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
372 if (modifiers.metaKey || modifiers.ctrlKey) {
373 void readLocalApi()
374 ?.shell.openExternal(url)
375 .catch((cause: unknown) => console.error(cause));
376 return;
377 }
378 if (
379 props.threadRef !== undefined &&
380 openChangeRequestLink(
381 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
382 url,
383 undefined,
384 props.threadRef.environmentId,
385 )
386 ) {
387 return;
388 }
389 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
390 });
391 const { onFullscreenChange } = props;
392 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports fullscreen to the parent while the image viewer is open, and clears it on unmount
393 useEffect(() => {
394 if (expandedImage === null) return;
395 onFullscreenChange?.(true);
396 return () => onFullscreenChange?.(false);
397 }, [expandedImage, onFullscreenChange]);
398 // Links, keys and images require frame focus and recent reader activity: a page can take
399 // focus by script, so this blocks opens on load, though not a page that waits for the
400 // reader's next input.
401 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
402 const height = readHtmlRenderContentHeight(event.data);
403 if (height !== undefined) {
404 props.onContentHeight?.(height);
405 return;
406 }
407 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
408 const linkRequest = readHtmlRenderLinkRequest(event.data);
409 if (linkRequest !== undefined) {
410 open(linkRequest.url, linkRequest);
411 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
412 return;
413 }
414 const key = readHtmlRenderKeyDown(event.data);
415 if (key !== undefined) {
416 if (isShortcut(key)) {
417 frame.dispatchEvent(
418 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
419 );
420 }
421 return;
422 }
423 const imageRequest = readHtmlRenderImageRequest(event.data);
424 if (imageRequest !== undefined) {
425 setExpandedImage({ images: [...imageRequest.images], index: imageRequest.index });
426 }
427 });
428 // Attach at commit because a fast page may post its initial height before passive effects run.
429 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a window message listener for the iframe at commit, before its first height post
430 useLayoutEffect(() => {
431 const frame = frameRef.current;
432 if (frame === null) return;
433 const onMessage = (event: MessageEvent) => {
434 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
435 };
436 window.addEventListener("message", onMessage);
437 return () => window.removeEventListener("message", onMessage);
438 }, []);
439 return (
440 <>
441 <iframe
442 ref={frameRef}
443 src={src}
444 title={props.title}
445 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
446 sandbox="allow-scripts allow-forms"
447 // Lets a page's video or image viewer take the screen.
448 allow="fullscreen"
449 loading="lazy"
450 onLoad={() => {
451 setLoaded(true);
452 // Covers a theme change that landed while the page was loading.
453 postTheme();
454 postShortcuts();
455 }}
456 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
457 className={cn("border-0 scheme-light", props.className)}
458 style={loaded ? { colorScheme: theme.appearance } : undefined}
459 />
460 {expandedImage !== null ? (
461 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
462 ) : null}
463 </>
464 );
465 }