The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 15:45 UTC
fix(web): Escape and copy work in chat media and markdown widgets, which attach through ref callbacks (#25246)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 20:37 UTC
f279070244b413eb385cfa827dceb6ce51eec621
17 files changed
+536
-387
apps/web/src/appInit.tsx
+23
@@ -1,12 +1,15 @@
1
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
import type { ClientSettings } from "@t3tools/contracts/settings";
3
import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
4
5
import { applyAppearanceContrast } from "./appearanceContrast";
6
import { applyAppearanceFontVariables } from "./appearanceFonts";
7
+import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
8
import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
9
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
10
import { resolveServerBackedAppDisplayName } from "./branding.logic";
11
import { isElectron } from "./env";
12
+import { useComposerDraftStore } from "./composerDraftStore";
13
import { getClientSettings, subscribeClientSettings } from "./hooks/useSettings";
14
import {
15
syncDocumentElectronPlatformClasses,
@@ -16,6 +19,7 @@ import { prepareProviderAuthDelivery } from "./providerAuthDelivery";
19
import { getRouter, type AppRouter } from "./router";
20
import { appAtomRegistry } from "./rpc/atomRegistry";
21
import { primaryServerConfigAtom } from "./state/server";
22
+import { resolveThreadRouteTarget } from "./threadRoutes";
23
24
/** Writes appearance settings onto the document, touching only the groups that changed. */
25
function startClientAppearance(): void {
@@ -84,6 +88,24 @@ function startDocumentTitle(): void {
88
);
89
}
90
91
+/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
92
+function startThreadOverlayRetention(router: AppRouter): void {
93
+ router.subscribe("onResolved", () => {
94
+ const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
95
+ const draftSession =
96
+ target?.kind === "draft"
97
+ ? useComposerDraftStore.getState().getDraftSession(target.draftId)
98
+ : null;
99
+ const threadRef =
100
+ target?.kind === "server"
101
+ ? target.threadRef
102
+ : draftSession
103
+ ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
104
+ : null;
105
+ retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
106
+ });
107
+}
108
+
109
/**
110
* Starts every app-lifetime service once, before the first render, and returns the router.
111
* They run for the life of the page, so their disposers are dropped here.
@@ -103,6 +125,7 @@ export function startAppServices(): AppRouter {
125
startClientAppearance();
126
startDocumentTitle();
127
startAgentOpenedPreviews();
128
+ startThreadOverlayRetention(router);
129
130
return router;
131
}
apps/web/src/components/chat/ChatOverlayHosts.tsx
+14
-10
@@ -7,7 +7,6 @@ import type {
7
} from "@t3tools/contracts";
8
import { useAtomValue } from "@effect/atom-react";
9
import { Atom } from "effect/reactivity";
10
-import { useEffect } from "react";
10
11
import { appAtomRegistry } from "~/rpc/atomRegistry";
12
import { useRightPanelStore } from "~/rightPanelStore";
@@ -25,15 +24,26 @@ import {
24
import { Button } from "../ui/button";
25
import { Dialog } from "../ui/dialog";
26
import { WizardPopup } from "../ui/wizard";
28
-
29
-// Atoms isolate overlay renders. Thread keys prevent overlays following thread switches.
27
+import { registerThreadOverlay } from "./threadOverlayRetention";
28
+
29
+/**
30
+ * Open state for overlays the chat view hosts. It lives in atoms rather than
31
+ * ChatView state so opening or closing one renders only its host, not the
32
+ * whole chat chrome. Each entry carries the thread it was opened for; a host
33
+ * shows only its own thread's entry, and leaving that thread's route drops it.
34
+ */
35
type ThreadOverlayAtom<T> = Atom.Writable<{ readonly threadKey: string; readonly value: T } | null>;
36
37
function makeThreadOverlayAtom<T>(label: string): ThreadOverlayAtom<T> {
33
- return Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
38
+ const atom = Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
39
Atom.keepAlive,
40
Atom.withLabel(`chat:${label}`),
41
);
42
+ registerThreadOverlay((threadKey) => {
43
+ const entry = appAtomRegistry.get(atom);
44
+ if (entry !== null && entry.threadKey !== threadKey) closeThreadOverlay(atom);
45
+ });
46
+ return atom;
47
}
48
49
function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
@@ -42,12 +52,6 @@ function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
52
53
function useThreadOverlay<T>(atom: ThreadOverlayAtom<T>, threadKey: string | null): T | null {
54
const entry = useAtomValue(atom);
45
- useEffect(
46
- () => () => {
47
- if (appAtomRegistry.get(atom)?.threadKey === threadKey) closeThreadOverlay(atom);
48
- },
49
- [atom, threadKey],
50
- );
55
return threadKey !== null && entry?.threadKey === threadKey ? entry.value : null;
56
}
57
apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx
new
+43
@@ -0,0 +1,43 @@
1
+import type { SnapShotSource } from "@t3tools/contracts";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+import { userEvent } from "vite-plus/test/browser";
4
+
5
+import "~/index.css";
6
+import { render } from "../../../test/render";
7
+import { ExpandedImageDialog } from "./ExpandedImageDialog";
8
+
9
+const PIXEL =
10
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
11
+
12
+const snapShotSource: SnapShotSource = {
13
+ kind: "snap-shot",
14
+ capturedAt: "2026-01-01T00:00:00.000Z",
15
+ appName: "Finder",
16
+ windowTitle: "Downloads",
17
+};
18
+
19
+describe("ExpandedImageDialog", () => {
20
+ it("Escape closes a popup opened inside the dialog before the dialog", async () => {
21
+ const onClose = vi.fn();
22
+ await using screen = await render(
23
+ <ExpandedImageDialog
24
+ preview={{ images: [{ src: PIXEL, name: "shot.png", source: snapShotSource }], index: 0 }}
25
+ onClose={onClose}
26
+ />,
27
+ // The dialog renders no links and reads no route.
28
+ { router: false },
29
+ );
30
+
31
+ await userEvent.click(screen.getByRole("button", { name: "No accessibility data" }));
32
+ await expect.element(screen.getByText("Accessibility data")).toBeVisible();
33
+
34
+ await userEvent.keyboard("{Escape}");
35
+ await expect.element(screen.getByText("Accessibility data")).not.toBeInTheDocument();
36
+ expect(onClose).not.toHaveBeenCalled();
37
+
38
+ // Focus returns to the popup's trigger and opens its tooltip; leave it for a plain control.
39
+ (screen.getByRole("button", { name: "Close image preview" }).element() as HTMLElement).focus();
40
+ await userEvent.keyboard("{Escape}");
41
+ await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce());
42
+ });
43
+});
apps/web/src/components/chat/ExpandedImageDialog.tsx
+47
-45
@@ -1,4 +1,5 @@
1
-import { memo, useEffect, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
1
+import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
2
+import { flushSync } from "react-dom";
3
import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
4
import { Image as ImageGlyph, Text as TextGlyph } from "lucide";
5
import { Button } from "../ui/button";
@@ -23,6 +24,7 @@ import { useAtomValue } from "@effect/atom-react";
24
import { Atom } from "effect/reactivity";
25
import { appAtomRegistry } from "~/rpc/atomRegistry";
26
import { expandedImageKey } from "./ExpandedImagePreview";
27
+import { registerThreadOverlay } from "./threadOverlayRetention";
28
29
interface ExpandedImageDialogProps {
30
preview: ExpandedImagePreview;
@@ -76,6 +78,13 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
78
const [returnFocusTarget] = useState(() =>
79
document.activeElement instanceof HTMLElement ? document.activeElement : null,
80
);
81
+ // The host unmounts the dialog outright, so Base UI never runs finalFocus. Without
82
+ // this, focus stays on the removed dialog, and the composer that owned the opener
83
+ // reads that as a blur and rests.
84
+ const close = () => {
85
+ flushSync(onClose);
86
+ if (returnFocusTarget?.isConnected) returnFocusTarget.focus({ preventScroll: true });
87
+ };
88
const closeButtonRef = useRef<HTMLButtonElement>(null);
89
const imageCount = preview.images.length;
90
const index =
@@ -92,7 +101,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
101
...source,
102
onOpenFile: () => {
103
openFile();
95
- onClose();
104
+ close();
105
},
106
}
107
: source;
@@ -101,18 +110,6 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
110
setImageOffset((current) => current + direction);
111
};
112
104
- // Restore opener focus to prevent composer collapse.
105
- const openerRef = useRef<Element | null>(null);
106
- useEffect(() => {
107
- openerRef.current = document.activeElement;
108
- return () => {
109
- const opener = openerRef.current;
110
- if (opener instanceof HTMLElement && opener.isConnected) {
111
- opener.focus({ preventScroll: true });
112
- }
113
- };
114
- }, []);
115
-
113
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
114
if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
115
return;
@@ -134,17 +131,6 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
131
navigateImage(1);
132
};
133
137
- useEffect(() => {
138
- const onEscape = (event: globalThis.KeyboardEvent) => {
139
- if (event.key !== "Escape" || isContextMenuOpen()) return;
140
- event.preventDefault();
141
- event.stopPropagation();
142
- onClose();
143
- };
144
- window.addEventListener("keydown", onEscape, { capture: true });
145
- return () => window.removeEventListener("keydown", onEscape, { capture: true });
146
- }, [onClose]);
147
-
134
if (!item) return null;
135
const mediaLabel = item.type === "video" ? "video" : "image";
136
const openOriginalLink =
@@ -163,8 +149,14 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
149
return (
150
<Dialog
151
open
166
- onOpenChange={(open) => {
167
- if (!open) onClose();
152
+ onOpenChange={(open, eventDetails) => {
153
+ if (open) return;
154
+ // Escape belongs to an open context menu first.
155
+ if (eventDetails.reason === "escape-key" && isContextMenuOpen()) {
156
+ eventDetails.cancel();
157
+ return;
158
+ }
159
+ close();
160
}}
161
>
162
<DialogPopup
@@ -177,7 +169,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
169
initialFocus={closeButtonRef}
170
finalFocus={() => returnFocusTarget}
171
onClick={(event) => {
180
- if (event.target === event.currentTarget) onClose();
172
+ if (event.target === event.currentTarget) close();
173
}}
174
>
175
<DialogTitle className="sr-only">Expanded {mediaLabel} preview</DialogTitle>
@@ -187,7 +179,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
179
size="icon-sm"
180
variant="media-close"
181
className="absolute right-0 top-0 z-20"
190
- onClick={onClose}
182
+ onClick={close}
183
aria-label={`Close ${mediaLabel} preview`}
184
>
185
<XIcon />
@@ -286,35 +278,45 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
278
});
279
280
// Keep preview state outside ChatView to isolate dialog renders.
289
-const expandedImagePreviewAtom = Atom.make<{
281
+type ExpandedImagePreviewState = {
282
readonly threadKey: string;
283
readonly preview: ExpandedImagePreview;
292
-} | null>(null).pipe(Atom.keepAlive, Atom.withLabel("chat:expanded-image-preview"));
284
+} | null;
285
+
286
+const expandedImagePreviewAtom = Atom.make<ExpandedImagePreviewState>(null).pipe(
287
+ Atom.keepAlive,
288
+ Atom.withLabel("chat:expanded-image-preview"),
289
+);
290
+
291
+function ownedSrc(state: ExpandedImagePreviewState): string | null {
292
+ const item = state?.preview.images[state.preview.index];
293
+ return item?.ownsSrc === true ? item.src : null;
294
+}
295
+
296
+// The preview owns a blob URL made for it, so whatever replaces it releases that URL.
297
+function setExpandedImagePreview(next: ExpandedImagePreviewState): void {
298
+ const previous = ownedSrc(appAtomRegistry.get(expandedImagePreviewAtom));
299
+ appAtomRegistry.set(expandedImagePreviewAtom, next);
300
+ if (previous !== null && previous !== ownedSrc(next)) URL.revokeObjectURL(previous);
301
+}
302
303
export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
295
- appAtomRegistry.set(expandedImagePreviewAtom, { threadKey, preview });
304
+ setExpandedImagePreview({ threadKey, preview });
305
}
306
307
function closeExpandedImagePreview(): void {
299
- appAtomRegistry.set(expandedImagePreviewAtom, null);
308
+ setExpandedImagePreview(null);
309
}
310
302
-function closeExpandedImagePreviewFor(threadKey: string): void {
303
- if (appAtomRegistry.get(expandedImagePreviewAtom)?.threadKey === threadKey) {
304
- closeExpandedImagePreview();
305
- }
306
-}
311
+// Leaving the thread's route (or the chat view) drops its preview.
312
+registerThreadOverlay((threadKey) => {
313
+ const current = appAtomRegistry.get(expandedImagePreviewAtom);
314
+ if (current !== null && current.threadKey !== threadKey) closeExpandedImagePreview();
315
+});
316
317
export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
318
const state = useAtomValue(expandedImagePreviewAtom);
319
const preview = state?.threadKey === threadKey ? state.preview : null;
311
- const item = preview?.images[preview.index];
312
- const ownedSrc = item?.ownsSrc === true ? item.src : null;
313
- useEffect(() => {
314
- if (ownedSrc === null) return;
315
- return () => URL.revokeObjectURL(ownedSrc);
316
- }, [ownedSrc]);
317
- useEffect(() => () => closeExpandedImagePreviewFor(threadKey), [threadKey]);
320
if (preview === null) return null;
321
return (
322
<ExpandedImageDialog
apps/web/src/components/chat/HtmlRenderFrame.browser.test.tsx
new
+41
@@ -0,0 +1,41 @@
1
+import { EnvironmentId } from "@t3tools/contracts";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+import { userEvent } from "vite-plus/test/browser";
4
+
5
+import "~/index.css";
6
+import { render } from "../../../test/render";
7
+
8
+vi.mock(import("~/assets/longLivedAssetUrls"), () => ({
9
+ useLongLivedAssetUrl: () => ({
10
+ _tag: "Success",
11
+ url: "about:blank",
12
+ expiresAt: Date.now() + 60 * 60_000,
13
+ }),
14
+}));
15
+vi.mock(import("~/assets/assetUrls"), async (importOriginal) => ({
16
+ ...(await importOriginal()),
17
+ useAssetUrlRefresh: () => async () => "about:blank",
18
+}));
19
+
20
+import { HtmlRenderFrame } from "./HtmlRenderFrame";
21
+
22
+describe("HtmlRenderFrame", () => {
23
+ it("reports leaving full screen when it unmounts while expanded", async () => {
24
+ const onFullscreenChange = vi.fn();
25
+ await using screen = await render(
26
+ <HtmlRenderFrame
27
+ environmentId={EnvironmentId.make("environment")}
28
+ htmlRender={{ attachmentId: "attachment", title: "Report", height: 200 }}
29
+ threadRef={undefined}
30
+ onFullscreenChange={onFullscreenChange}
31
+ />,
32
+ );
33
+
34
+ await userEvent.click(screen.getByRole("button", { name: "Open full screen" }));
35
+ await expect.element(screen.getByRole("dialog")).toBeVisible();
36
+ expect(onFullscreenChange).toHaveBeenLastCalledWith(true);
37
+
38
+ await screen.unmount();
39
+ expect(onFullscreenChange).toHaveBeenLastCalledWith(false);
40
+ });
41
+});
apps/web/src/components/chat/HtmlRenderFrame.tsx
+9
-9
@@ -6,7 +6,7 @@ import {
6
type HtmlRenderReference,
7
} from "@t3tools/shared/htmlRender";
8
import { Maximize2Icon } from "lucide-react";
9
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
9
+import { useEffect, useState } from "react";
10
11
import { useAssetUrlRefresh } from "~/assets/assetUrls";
12
import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls";
@@ -27,16 +27,13 @@ export function HtmlRenderFrame(props: {
27
readonly onFullscreenChange?: (fullscreen: boolean) => void;
28
}) {
29
const { attachmentId, title } = props.htmlRender;
30
- const boxRef = useRef<HTMLDivElement>(null);
30
const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
32
- useLayoutEffect(() => {
33
- const box = boxRef.current;
34
- if (!box) return;
31
+ const observeBox = (box: HTMLDivElement) => {
32
setWidth(box.clientWidth);
33
return observeResize(box, ([entry]) => {
34
if (entry) setWidth(entry.contentRect.width);
35
});
39
- }, []);
36
+ };
37
// Client fonts can exceed the server-measured height and cause nested scrolling.
38
const [contentHeight, setContentHeight] = useState<number>();
39
const height = htmlRenderFrameHeight(props.htmlRender, width, contentHeight);
@@ -59,14 +56,17 @@ export function HtmlRenderFrame(props: {
56
const refresh = useAssetUrlRefresh(props.environmentId, resource);
57
const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
58
const { onFullscreenChange } = props;
59
+ // Tied to the viewer's lifetime: unmounting while expanded must still release
60
+ // the timeline's follow pin, which a close handler alone never reaches.
61
+ const expanded = expandedSrc !== null;
62
useEffect(() => {
63
- if (expandedSrc === null) return;
63
+ if (!expanded) return;
64
onFullscreenChange?.(true);
65
return () => onFullscreenChange?.(false);
66
- }, [expandedSrc, onFullscreenChange]);
66
+ }, [expanded, onFullscreenChange]);
67
68
return (
69
- <div ref={boxRef} className="group/html-render relative" style={{ height }}>
69
+ <div ref={observeBox} className="group/html-render relative" style={{ height }}>
70
{src !== null ? (
71
<>
72
<HtmlRenderDocument
apps/web/src/components/chat/MarkdownCodeBlock.tsx
+35
-59
@@ -1,8 +1,9 @@
1
import { Check, Copy } from "lucide";
2
import { PlayIcon, WrapTextIcon } from "lucide-react";
3
import { toHtml } from "hast-util-to-html";
4
-import React, { use, useEffect, useRef, useState, type ReactNode } from "react";
4
+import React, { use, useEffect, useState, type ReactNode } from "react";
5
6
+import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
7
import { getClientSettings } from "../../hooks/useSettings";
8
import type { DiffThemeName } from "../../lib/diffRendering";
9
import {
@@ -150,9 +151,19 @@ export function MarkdownCodeBlock({
151
diagram?: boolean;
152
children: ReactNode;
153
}) {
153
- const [copied, setCopied] = useState(false);
154
+ const { copyToClipboard, isCopied: copied } = useCopyToClipboard({
155
+ timeout: 1200,
156
+ onError: (cause) =>
157
+ reportMarkdownActionFailure(
158
+ {
159
+ operation: "copy-code-block",
160
+ language,
161
+ ...(fenceTitle ? { fenceTitle } : {}),
162
+ },
163
+ cause,
164
+ ),
165
+ });
166
const [wrapped, setWrapped] = useState(() => getClientSettings().wordWrap);
155
- const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
167
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
168
const copyLabel = copied ? "Copied" : "Copy code";
169
const command = code.trim();
@@ -167,43 +178,7 @@ export function MarkdownCodeBlock({
178
// make the rendered command differ from what the terminal would receive.
179
!/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));
180
170
- const handleCopy = () => {
171
- if (typeof navigator === "undefined" || navigator.clipboard == null) {
172
- return;
173
- }
174
- void navigator.clipboard
175
- .writeText(code)
176
- .then(() => {
177
- if (copiedTimerRef.current != null) {
178
- clearTimeout(copiedTimerRef.current);
179
- }
180
- setCopied(true);
181
- copiedTimerRef.current = setTimeout(() => {
182
- setCopied(false);
183
- copiedTimerRef.current = null;
184
- }, 1200);
185
- })
186
- .catch((cause) => {
187
- reportMarkdownActionFailure(
188
- {
189
- operation: "copy-code-block",
190
- language,
191
- ...(fenceTitle ? { fenceTitle } : {}),
192
- },
193
- cause,
194
- );
195
- });
196
- };
197
-
198
- useEffect(
199
- () => () => {
200
- if (copiedTimerRef.current != null) {
201
- clearTimeout(copiedTimerRef.current);
202
- copiedTimerRef.current = null;
203
- }
204
- },
205
- [],
206
- );
181
+ const handleCopy = () => copyToClipboard(code);
182
183
const copyButton = (
184
<Tooltip>
@@ -358,32 +333,33 @@ function UncachedShikiCodeBlock({
333
: null;
334
useEffect(() => () => incrementalHighlight?.dispose(), [incrementalHighlight]);
335
const highlighted = (() => {
361
- try {
362
- if (incrementalHighlight) return incrementalHighlight(code);
363
- return preserveLines
364
- ? highlightCodeToHast(highlighter, code, language, themeName)
365
- : highlighter.codeToHtml(code, { lang: language, theme: themeName });
366
- } catch (error) {
367
- console.warn(
368
- `Code highlighting failed for language "${language}", falling back to plain text.`,
369
- error instanceof Error ? error.message : error,
370
- );
371
- return preserveLines
372
- ? highlightCodeToHast(highlighter, code, "text", themeName)
373
- : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
374
- }
375
- })();
376
-
377
- useEffect(() => {
336
+ const result = (() => {
337
+ try {
338
+ if (incrementalHighlight) return incrementalHighlight(code);
339
+ return preserveLines
340
+ ? highlightCodeToHast(highlighter, code, language, themeName)
341
+ : highlighter.codeToHtml(code, { lang: language, theme: themeName });
342
+ } catch (error) {
343
+ console.warn(
344
+ `Code highlighting failed for language "${language}", falling back to plain text.`,
345
+ error instanceof Error ? error.message : error,
346
+ );
347
+ return preserveLines
348
+ ? highlightCodeToHast(highlighter, code, "text", themeName)
349
+ : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
350
+ }
351
+ })();
352
+ // A finished block is cached for the next mount; a streaming one is still changing.
353
if (!isStreaming) {
379
- const highlightedHtml = typeof highlighted === "string" ? highlighted : toHtml(highlighted);
354
+ const highlightedHtml = typeof result === "string" ? result : toHtml(result);
355
highlightedCodeCache.set(
356
cacheKey,
357
highlightedHtml,
358
estimateHighlightedSize(highlightedHtml, code),
359
);
360
}
386
- }, [cacheKey, code, highlighted, isStreaming]);
361
+ return result;
362
+ })();
363
364
return typeof highlighted === "string" ? (
365
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
apps/web/src/components/chat/MarkdownCopy.browser.test.tsx
new
+72
@@ -0,0 +1,72 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+import { page, userEvent } from "vite-plus/test/browser";
3
+
4
+import "~/index.css";
5
+import { render } from "../../../test/render";
6
+import { MarkdownCodeBlock } from "./MarkdownCodeBlock";
7
+import { MarkdownTable } from "./MarkdownTable";
8
+
9
+// Insecure origins (a LAN or tailnet address over plain http) have no async clipboard.
10
+function withoutAsyncClipboard() {
11
+ const original = Object.getOwnPropertyDescriptor(Navigator.prototype, "clipboard");
12
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
13
+ const execCommand = vi.spyOn(document, "execCommand").mockReturnValue(true);
14
+ return {
15
+ execCommand,
16
+ [Symbol.dispose]() {
17
+ execCommand.mockRestore();
18
+ Reflect.deleteProperty(navigator, "clipboard");
19
+ if (original) Object.defineProperty(Navigator.prototype, "clipboard", original);
20
+ },
21
+ };
22
+}
23
+
24
+describe("markdown copy without the async clipboard", () => {
25
+ it("copies a code block through the execCommand fallback", async () => {
26
+ await using screen = await render(
27
+ <MarkdownCodeBlock
28
+ code="echo hi"
29
+ language="sh"
30
+ fenceTitle={null}
31
+ theme="light"
32
+ isStreaming={false}
33
+ >
34
+ <pre>
35
+ <code>echo hi</code>
36
+ </pre>
37
+ </MarkdownCodeBlock>,
38
+ // The block renders no links and reads no route.
39
+ { router: false },
40
+ );
41
+ using clipboard = withoutAsyncClipboard();
42
+
43
+ await userEvent.click(screen.getByRole("button", { name: "Copy code" }));
44
+ await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
45
+ expect(clipboard.execCommand).toHaveBeenCalledWith("copy");
46
+ });
47
+
48
+ it("copies a table through the execCommand fallback", async () => {
49
+ await using screen = await render(
50
+ <MarkdownTable>
51
+ <thead>
52
+ <tr>
53
+ <th>Name</th>
54
+ </tr>
55
+ </thead>
56
+ <tbody>
57
+ <tr>
58
+ <td>Ada</td>
59
+ </tr>
60
+ </tbody>
61
+ </MarkdownTable>,
62
+ // The table renders no links and reads no route.
63
+ { router: false },
64
+ );
65
+ using clipboard = withoutAsyncClipboard();
66
+
67
+ await userEvent.click(screen.getByRole("button", { name: "Copy table" }));
68
+ await userEvent.click(page.getByRole("menuitem", { name: "Copy as Markdown" }));
69
+ await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
70
+ expect(clipboard.execCommand).toHaveBeenCalledWith("copy");
71
+ });
72
+});
apps/web/src/components/chat/MarkdownTable.tsx
+30
-53
@@ -1,6 +1,7 @@
1
import { Check, Copy, Maximize2, Minimize2 } from "lucide";
2
-import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
2
+import { useRef, useState, type ComponentProps } from "react";
3
4
+import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
5
import { getClientSettings } from "../../hooks/useSettings";
6
import { observeResize } from "../../lib/observeResize";
7
import {
@@ -41,78 +42,54 @@ function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement):
42
43
export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
44
const containerRef = useRef<HTMLDivElement | null>(null);
44
- const tableRef = useRef<HTMLTableElement | null>(null);
45
const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
46
const [hasClippedCells, setHasClippedCells] = useState(false);
47
- const [copied, setCopied] = useState(false);
48
- const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
47
+ const { copyToClipboard, isCopied: copied } = useCopyToClipboard<"markdown" | "csv">({
48
+ timeout: 1200,
49
+ onError: (cause, format) =>
50
+ reportMarkdownActionFailure({ operation: "copy-table", format }, cause),
51
+ });
52
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
53
const copyLabel = copied ? "Copied" : "Copy table";
54
52
- const measureClippedCells = () => {
53
- const container = containerRef.current;
54
- const table = tableRef.current;
55
+ // React calls this with null when a previous attach returned no cleanup.
56
+ const attachContainer = (container: HTMLDivElement | null) => {
57
+ containerRef.current = container;
58
+ const table = container?.querySelector("table");
59
if (!container || !table) return;
56
- setHasClippedCells(tableHasClippedCells(container, table));
60
+ const measure = () => setHasClippedCells(tableHasClippedCells(container, table));
61
+ measure();
62
+ // A streamed cell can grow until it clips while the table keeps its size, and a
63
+ // narrower column can clip a cell without this component rendering.
64
+ const mutations = new MutationObserver(measure);
65
+ mutations.observe(table, { childList: true, characterData: true, subtree: true });
66
+ const stopResize = observeResize(table, measure);
67
+ return () => {
68
+ mutations.disconnect();
69
+ stopResize();
70
+ containerRef.current = null;
71
+ };
72
};
73
59
- // A streamed cell can grow until it clips while the table keeps its size,
60
- // so remeasure after every render, not only on resize.
61
- useLayoutEffect(measureClippedCells);
62
-
63
- // Column width changes can clip a cell without rendering this table.
64
- useLayoutEffect(() => {
65
- const table = tableRef.current;
66
- if (!table) return;
67
- return observeResize(table, measureClippedCells);
68
- }, [measureClippedCells]);
69
-
74
const handleCopy = (format: "markdown" | "csv") => {
75
const table = containerRef.current?.querySelector("table");
72
- if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
73
- return;
74
- }
75
- const text =
76
+ if (!table) return;
77
+ copyToClipboard(
78
format === "markdown"
79
? serializeTableElementToMarkdown(table)
78
- : serializeTableElementToCsv(table);
79
- void navigator.clipboard
80
- .writeText(text)
81
- .then(() => {
82
- if (copiedTimerRef.current != null) {
83
- clearTimeout(copiedTimerRef.current);
84
- }
85
- setCopied(true);
86
- copiedTimerRef.current = setTimeout(() => {
87
- setCopied(false);
88
- copiedTimerRef.current = null;
89
- }, 1200);
90
- })
91
- .catch((cause) => {
92
- reportMarkdownActionFailure({ operation: "copy-table", format }, cause);
93
- });
80
+ : serializeTableElementToCsv(table),
81
+ format,
82
+ );
83
};
84
96
- useEffect(
97
- () => () => {
98
- if (copiedTimerRef.current != null) {
99
- clearTimeout(copiedTimerRef.current);
100
- copiedTimerRef.current = null;
101
- }
102
- },
103
- [],
104
- );
105
-
85
return (
86
<div
108
- ref={containerRef}
87
+ ref={attachContainer}
88
className="chat-markdown-table-container"
89
data-expanded={expanded ? "true" : "false"}
90
>
91
<ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
113
- <table ref={tableRef} {...props}>
114
- {children}
115
- </table>
92
+ <table {...props}>{children}</table>
93
</ScrollArea>
94
{/* Stays within the row's px-1: the chat lane clips sideways overflow. */}
95
<div className="mt-0.5 -mx-1 flex items-center justify-between select-none">
apps/web/src/components/chat/McpAppFrame.tsx
+97
-120
@@ -19,16 +19,18 @@ import {
19
type McpAppReference,
20
} from "@t3tools/shared/mcpApp";
21
import { Minimize2Icon } from "lucide-react";
22
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
22
+import { useEffect, useRef, useState, type FocusEvent, type ToggleEvent } from "react";
23
import { flushSync } from "react-dom";
24
25
-import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
25
+import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls";
26
import { APP_VERSION } from "~/branding";
27
import { isConfirmDialogActive, requestConfirmDialog } from "~/confirmDialog";
28
import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
29
+import { useStableCallback } from "~/hooks/useStableCallback";
30
import { Button } from "~/components/ui/button";
31
import { isElectron } from "~/env";
32
import { cn } from "~/lib/utils";
33
+import { useEnvironmentQuery } from "~/state/query";
34
import { useTurnItemDetail } from "~/state/queries";
35
import { mcpAppEnvironment } from "~/state/mcpApps";
36
import { useAtomCommand } from "~/state/use-atom-command";
@@ -43,7 +45,6 @@ const commandFailure = (result: {
45
);
46
};
47
46
-const MIN_URL_LIFE_MS = 5 * 60_000;
48
const fullscreenSupported =
49
typeof HTMLElement !== "undefined" && "popover" in HTMLElement.prototype;
50
@@ -51,6 +52,19 @@ const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
52
// Exclude activation left by input elsewhere in T3.
53
const PAGE_ACTIVATION_MS = 5_000;
54
55
+// Frame input does not bubble here. An app can refocus itself, so focus
56
+// alone cannot exclude activation from input elsewhere in T3.
57
+let lastPageInputAt = Number.NEGATIVE_INFINITY;
58
+if (typeof window !== "undefined") {
59
+ const note = () => {
60
+ lastPageInputAt = performance.now();
61
+ };
62
+ if (navigator.userActivation?.isActive) note();
63
+ for (const type of ["pointerdown", "pointerup", "touchend", "keydown"] as const) {
64
+ window.addEventListener(type, note, true);
65
+ }
66
+}
67
+
68
function saveBlob(blob: Blob, name: string) {
69
const url = URL.createObjectURL(blob);
70
const link = document.createElement("a");
@@ -82,15 +96,22 @@ export function McpAppFrame(props: {
96
const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
97
const [closed, setClosed] = useState(false);
98
const [documentGeneration, setDocumentGeneration] = useState(0);
85
- useLayoutEffect(() => {
86
- const box = boxRef.current;
87
- if (!box) return;
99
+ // Closing and reopening replaces the box, which re-attaches this.
100
+ const attachBox = (box: HTMLDivElement) => {
101
+ boxRef.current = box;
102
setWidth(box.clientWidth);
89
- return observeResize(box, ([entry]) => {
103
+ const stopResize = observeResize(box, ([entry]) => {
104
if (entry) setWidth(Math.round(entry.contentRect.width));
105
+ // Full screen reports the viewport, which can change height alone.
106
+ if (fullscreenSupported && box.matches(":popover-open")) {
107
+ hostRef.current?.updateHostContext();
108
+ }
109
});
92
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Closing and reopening replaces the box.
93
- }, [closed]);
110
+ return () => {
111
+ stopResize();
112
+ boxRef.current = null;
113
+ };
114
+ };
115
116
const resource = {
117
_tag: "attachment" as const,
@@ -100,27 +121,10 @@ export function McpAppFrame(props: {
121
disposition: "inline" as const,
122
renderIntent: "mcp-app" as const,
123
};
103
- const asset = useAssetUrlState(props.environmentId, resource);
104
- const refreshAsset = useAssetUrlRefresh(props.environmentId, resource);
105
- // Retain the URL to avoid reloads. Re-mint near expiry; frames cannot report failed loads.
124
+ // The frame keeps its first URL: a re-minted one would reload the app.
125
const [src, setSrc] = useState<string | null>(null);
107
- const [mintFailed, setMintFailed] = useState(false);
108
- const minting = useRef(false);
109
- const cachedUrl = asset._tag === "Success" ? asset.url : null;
110
- const cachedExpiresAt = asset._tag === "Success" ? asset.expiresAt : 0;
111
- useEffect(() => {
112
- if (src !== null || cachedUrl === null || minting.current) return;
113
- if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
114
- // oxlint-disable-next-line react/set-state-in-effect -- Adopts the cached URL once it is known to last.
115
- setSrc(cachedUrl);
116
- return;
117
- }
118
- minting.current = true;
119
- void refreshAsset().then(
120
- (url) => (url === null ? setMintFailed(true) : setSrc(url)),
121
- () => setMintFailed(true),
122
- );
123
- }, [src, cachedUrl, cachedExpiresAt, refreshAsset]);
126
+ const asset = useLongLivedAssetUrl(src === null ? props.environmentId : null, resource);
127
+ if (src === null && asset._tag === "Success") setSrc(asset.url);
128
129
const detail = useTurnItemDetail({
130
environmentId: props.environmentId,
@@ -142,14 +146,19 @@ export function McpAppFrame(props: {
146
147
const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
148
const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
149
+ const toolDefinition = useEnvironmentQuery(
150
+ mcpAppEnvironment.toolInfoQuery({
151
+ environmentId: props.environmentId,
152
+ input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
153
+ }),
154
+ ).data?.tool;
155
const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
156
const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
157
reportFailure: false,
158
});
149
- const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
159
160
// Read live values without rebuilding the host and losing the app session.
152
- const live = {
161
+ const readLive = useStableCallback(() => ({
162
theme,
163
width,
164
props,
@@ -159,80 +168,42 @@ export function McpAppFrame(props: {
168
updateModelContext,
169
displayMode,
170
toolDefinition,
162
- };
171
+ }));
172
const hostRef = useRef<McpAppHost | null>(null);
164
- const latest = useRef(live);
165
- useEffect(() => {
166
- latest.current = live;
167
- });
168
-
169
- // Frame input does not bubble here. An app can refocus itself, so focus
170
- // alone cannot exclude activation from input elsewhere in T3.
171
- const lastPageInputAt = useRef(Number.NEGATIVE_INFINITY);
172
- useEffect(() => {
173
- const note = () => {
174
- lastPageInputAt.current = performance.now();
175
- };
176
- if (navigator.userActivation?.isActive) note();
177
- const types = ["pointerdown", "pointerup", "touchend", "keydown"] as const;
178
- for (const type of types) window.addEventListener(type, note, true);
179
- return () => {
180
- for (const type of types) window.removeEventListener(type, note, true);
181
- };
182
- }, []);
173
184
- useEffect(() => {
185
- const box = boxRef.current;
186
- if (box === null || !fullscreenSupported) return;
187
- const shown = box.matches(":popover-open");
188
- if (displayMode === "fullscreen" && !shown) box.showPopover();
189
- if (displayMode !== "fullscreen" && shown) box.hidePopover();
190
- if (displayMode === "fullscreen") {
191
- latest.current.props.onFullscreenChange?.(true);
192
- return () => latest.current.props.onFullscreenChange?.(false);
193
- }
194
- }, [displayMode]);
174
const [stepAsideFor, setStepAsideFor] = useState(props.awaitingUser);
175
if (stepAsideFor !== props.awaitingUser) {
176
setStepAsideFor(props.awaitingUser);
177
if (props.awaitingUser === true) setDisplayMode("inline");
178
}
200
- useEffect(() => {
201
- if (displayMode !== "fullscreen") return;
202
- const leave = () => setDisplayMode("inline");
203
- const onFocus = (event: FocusEvent) => {
204
- if (event.target instanceof Node && !boxRef.current?.contains(event.target)) leave();
205
- };
206
- const onKey = (event: KeyboardEvent) => {
207
- if (event.key === "Escape") leave();
208
- };
209
- const onResize = () => hostRef.current?.updateHostContext();
210
- document.addEventListener("focusin", onFocus);
211
- window.addEventListener("keydown", onKey);
212
- window.addEventListener("resize", onResize);
179
+ // The box is in the top layer exactly while its full-screen chrome is
180
+ // mounted, so every way out of full screen (including the step-aside above,
181
+ // decided during render) closes the popover and releases the timeline pin.
182
+ const attachFullscreenChrome = (chrome: HTMLDivElement) => {
183
+ const box = chrome.parentElement;
184
+ if (box === null) return;
185
+ if (!box.matches(":popover-open")) box.showPopover();
186
+ readLive().props.onFullscreenChange?.(true);
187
return () => {
214
- document.removeEventListener("focusin", onFocus);
215
- window.removeEventListener("keydown", onKey);
216
- window.removeEventListener("resize", onResize);
188
+ if (box.matches(":popover-open")) box.hidePopover();
189
+ readLive().props.onFullscreenChange?.(false);
190
};
218
- }, [displayMode]);
191
+ };
192
+ // Light dismiss (Escape) closes the popover without React.
193
+ const onBoxToggle = (event: ToggleEvent<HTMLDivElement>) => {
194
+ if (event.newState === "closed") setDisplayMode("inline");
195
+ };
196
+ const onBoxBlur = (event: FocusEvent<HTMLDivElement>) => {
197
+ const next = event.relatedTarget;
198
+ if (
199
+ displayMode === "fullscreen" &&
200
+ next instanceof Node &&
201
+ !event.currentTarget.contains(next)
202
+ ) {
203
+ setDisplayMode("inline");
204
+ }
205
+ };
206
220
- useEffect(() => {
221
- let cancelled = false;
222
- void latest.current
223
- .toolInfo({
224
- environmentId: props.environmentId,
225
- input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
226
- })
227
- .then((info) => {
228
- if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
229
- setToolDefinition(info.value.tool);
230
- }
231
- });
232
- return () => {
233
- cancelled = true;
234
- };
235
- }, [props.environmentId, props.threadId, props.itemId, app.tool]);
207
// Navigation retains the frame window; reject second loads to prevent impersonation.
208
const loads = useRef({ generation: 0, count: 0 });
209
const onFrameLoad = () => {
@@ -246,10 +217,11 @@ export function McpAppFrame(props: {
217
}
218
};
219
249
- useEffect(() => {
250
- if (src === null) return;
220
+ // The host belongs to this frame element, which is replaced when the document is reopened.
221
+ const attachFrame = (frame: HTMLIFrameElement) => {
222
+ frameRef.current = frame;
223
const hostContext = (): McpAppHostContext => {
252
- const current = latest.current;
224
+ const current = readLive();
225
return {
226
theme: current.theme.appearance,
227
styles: { variables: mcpAppStyleVariables(current.theme.variables) },
@@ -287,7 +259,7 @@ export function McpAppFrame(props: {
259
};
260
const target = () => frameRef.current?.contentWindow ?? null;
261
const scope = () => {
290
- const { environmentId, threadId, itemId } = latest.current.props;
262
+ const { environmentId, threadId, itemId } = readLive().props;
263
return { environmentId, input: { threadId, itemId } };
264
};
265
const host = makeMcpAppHost({
@@ -298,7 +270,7 @@ export function McpAppFrame(props: {
270
hostContext,
271
callTool: async ({ name, arguments: args }) => {
272
const { environmentId, input } = scope();
301
- const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
273
+ const info = await readLive().toolInfo({ environmentId, input: { ...input, name } });
274
if (info._tag !== "Success") throw commandFailure(info);
275
if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
276
if (!info.value.readOnly) {
@@ -307,7 +279,7 @@ export function McpAppFrame(props: {
279
);
280
if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
281
}
310
- const result = await latest.current.callTool({
282
+ const result = await readLive().callTool({
283
environmentId,
284
input: { ...input, name, arguments: args },
285
});
@@ -316,7 +288,7 @@ export function McpAppFrame(props: {
288
},
289
readResource: async ({ uri }) => {
290
const { environmentId, input } = scope();
319
- const result = await latest.current.readResource({
291
+ const result = await readLive().readResource({
292
environmentId,
293
input: { ...input, uri },
294
});
@@ -330,7 +302,7 @@ export function McpAppFrame(props: {
302
window.open(url, "_blank", "noopener,noreferrer");
303
},
304
sendMessage: async (text) => {
333
- const send = latest.current.props.onSendMessage;
305
+ const send = readLive().props.onSendMessage;
306
if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");
307
const approved = await ask(`Send this message from ${app.server}?\n${text}`);
308
if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
@@ -338,12 +310,12 @@ export function McpAppFrame(props: {
310
},
311
updateModelContext: async (context) => {
312
const { environmentId, input } = scope();
341
- const result = await latest.current.updateModelContext({
313
+ const result = await readLive().updateModelContext({
314
environmentId,
315
input: {
316
...input,
317
...context,
346
- conversationThreadId: latest.current.props.conversationThreadId,
318
+ conversationThreadId: readLive().props.conversationThreadId,
319
},
320
});
321
if (result._tag !== "Success") throw commandFailure(result);
@@ -352,14 +324,15 @@ export function McpAppFrame(props: {
324
const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");
325
if (
326
mode === "fullscreen" &&
355
- (document.activeElement !== frameRef.current ||
327
+ (!fullscreenSupported ||
328
+ document.activeElement !== frameRef.current ||
329
!navigator.userActivation?.isActive ||
357
- performance.now() - lastPageInputAt.current < PAGE_ACTIVATION_MS ||
358
- latest.current.props.awaitingUser === true ||
330
+ performance.now() - lastPageInputAt < PAGE_ACTIVATION_MS ||
331
+ readLive().props.awaitingUser === true ||
332
isConfirmDialogActive() ||
333
(otherFullscreen !== null && otherFullscreen !== boxRef.current))
334
) {
362
- return latest.current.displayMode;
335
+ return readLive().displayMode;
336
}
337
setDisplayMode(mode);
338
return mode;
@@ -375,7 +348,7 @@ export function McpAppFrame(props: {
348
bytes = file.bytes;
349
} else {
350
const { environmentId, input } = scope();
378
- const read = await latest.current.readResource({
351
+ const read = await readLive().readResource({
352
environmentId,
353
input: { ...input, uri: file.uri },
354
});
@@ -393,7 +366,7 @@ export function McpAppFrame(props: {
366
}
367
},
368
onRequestTeardown: () => {
396
- if (latest.current.displayMode === "fullscreen") {
369
+ if (readLive().displayMode === "fullscreen") {
370
setDisplayMode("inline");
371
return;
372
}
@@ -401,7 +374,7 @@ export function McpAppFrame(props: {
374
},
375
onSizeChanged: (size) => {
376
// Ignore fullscreen height when restoring inline sizing.
404
- if (latest.current.displayMode === "fullscreen") return;
377
+ if (readLive().displayMode === "fullscreen") return;
378
if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
379
},
380
});
@@ -414,9 +387,9 @@ export function McpAppFrame(props: {
387
window.removeEventListener("message", receive);
388
void host.teardown();
389
hostRef.current = null;
390
+ frameRef.current = null;
391
};
418
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A reopened document needs a new host.
419
- }, [src, app, documentGeneration]);
392
+ };
393
394
useEffect(() => {
395
hostRef.current?.updateHostContext();
@@ -436,7 +409,6 @@ export function McpAppFrame(props: {
409
size="xs"
410
variant="ghost"
411
onClick={() => {
439
- minting.current = false;
412
setSrc(null);
413
setDocumentGeneration((value) => value + 1);
414
setClosed(false);
@@ -453,9 +425,11 @@ export function McpAppFrame(props: {
425
// Preserve inline row height during fullscreen to prevent timeline jumps.
426
<div style={{ height }}>
427
<div
456
- ref={boxRef}
428
+ ref={attachBox}
429
// Preserve the frame's parent to avoid reloads; the top layer escapes timeline containment.
458
- {...(fullscreenSupported ? { popover: "manual" as const } : {})}
430
+ {...(fullscreenSupported
431
+ ? { popover: "auto" as const, onToggle: onBoxToggle, onBlur: onBoxBlur }
432
+ : {})}
433
data-mcp-app-fullscreen={fullscreen ? "" : undefined}
434
className={cn(
435
"relative size-full overflow-hidden",
@@ -466,7 +440,10 @@ export function McpAppFrame(props: {
440
)}
441
>
442
{fullscreen ? (
469
- <div className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm">
443
+ <div
444
+ ref={attachFullscreenChrome}
445
+ className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm"
446
+ >
447
<span className="truncate">{app.server}</span>
448
<Button
449
aria-label="Exit full screen"
@@ -484,7 +461,7 @@ export function McpAppFrame(props: {
461
</p>
462
) : src !== null ? (
463
<iframe
487
- ref={frameRef}
464
+ ref={attachFrame}
465
src={src}
466
title={`${app.server} app`}
467
// Omitting allow-same-origin isolates the app from the session.
@@ -494,7 +471,7 @@ export function McpAppFrame(props: {
471
className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
472
style={{ colorScheme: theme.appearance }}
473
/>
497
- ) : asset._tag === "Failure" || mintFailed ? (
474
+ ) : asset._tag === "Failure" ? (
475
<p className="flex size-full items-center justify-center text-muted-foreground text-xs">
476
Unable to load the {app.server} app
477
</p>
apps/web/src/components/chat/MermaidDiagram.tsx
+8
-9
@@ -1,6 +1,6 @@
1
import DOMPurify from "dompurify";
2
import type { DiagramType, MathResolver } from "pele/lazy";
3
-import { use, useLayoutEffect, useRef, useState } from "react";
3
+import { use, useState } from "react";
4
5
import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
6
import { Button } from "../ui/button";
@@ -228,16 +228,15 @@ export function MermaidDiagram({
228
}) {
229
const [, setAttempt] = useState(0);
230
const [renderError, setRenderError] = useState<string | null>(null);
231
- const containerRef = useRef<HTMLSpanElement>(null);
231
const trimmedSource = source.trim();
232
const core = use(loadCore());
233
const type = core.status === "loaded" ? detectDiagramType(core.pele, trimmedSource) : null;
234
const load = core.status === "loaded" && type ? use(loadDiagramType(core.pele, type)) : core;
235
const math = trimmedSource.includes("$$") ? use(loadMath()) : null;
236
238
- useLayoutEffect(() => {
239
- const container = containerRef.current;
240
- if (load.status !== "loaded" || !container) return;
237
+ // Re-created, and so remounted, whenever the renderer, math support or source changes.
238
+ const mountDiagram = (container: HTMLSpanElement) => {
239
+ if (load.status !== "loaded") return;
240
const mounted = load.pele.mount(container, trimmedSource, {
241
links: false,
242
images: false,
@@ -252,7 +251,7 @@ export function MermaidDiagram({
251
),
252
});
253
return () => mounted.destroy();
255
- }, [load, math, trimmedSource]);
254
+ };
255
256
if (load.status === "failed") {
257
return (
@@ -280,12 +279,12 @@ export function MermaidDiagram({
279
aria-label="Expand diagram"
280
hidden={renderError !== null}
281
className="block w-full cursor-zoom-in rounded-md focus-visible:outline-2 focus-visible:outline-ring"
283
- onClick={() => {
284
- const svg = containerRef.current?.querySelector("svg");
282
+ onClick={(event) => {
283
+ const svg = event.currentTarget.querySelector("svg");
284
if (svg) onExpand(diagramImageUrl(svg));
285
}}
286
>
288
- <span ref={containerRef} className="flex w-full justify-center" />
287
+ <span ref={mountDiagram} className="flex w-full justify-center" />
288
</button>
289
</div>
290
);
apps/web/src/components/chat/PierreEntryIcon.tsx
+4
-2
@@ -1,5 +1,5 @@
1
import { FileIcon, FolderIcon } from "lucide-react";
2
-import { memo, useInsertionEffect } from "react";
2
+import { memo } from "react";
3
4
import { ensurePierreIconSprite, resolvePierreIconForEntry } from "../../pierre-icons";
5
import { cn } from "~/lib/utils";
@@ -59,6 +59,9 @@ const ICON_COLORS: Record<string, readonly [light: string, dark: string]> = {
59
zip: ["#d47628", "#ffa359"],
60
};
61
62
+// Every icon references the one shared sprite, so it is in the document before any renders.
63
+ensurePierreIconSprite();
64
+
65
export const PierreEntryIcon = memo(function PierreEntryIcon(props: {
66
pathValue: string;
67
kind: "file" | "directory";
@@ -66,7 +69,6 @@ export const PierreEntryIcon = memo(function PierreEntryIcon(props: {
69
theme: "light" | "dark";
70
className?: string;
71
}) {
69
- useInsertionEffect(ensurePierreIconSprite, []);
72
const icon = resolvePierreIconForEntry(props.pathValue, props.kind, props.mimeType);
73
74
if (!icon) {
apps/web/src/components/chat/ZoomableImage.tsx
+55
-52
@@ -1,4 +1,5 @@
1
-import { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type Ref } from "react";
1
+import { useImperativeHandle, useRef, useState, useSyncExternalStore, type Ref } from "react";
2
+import { flushSync } from "react-dom";
3
4
import {
5
onWindowControlsOverlayGeometryChange,
@@ -14,6 +15,25 @@ function readViewerSize() {
15
return { width: window.innerWidth, height: window.innerHeight - windowControlsOverlayHeight() };
16
}
17
18
+let viewerSize: ReturnType<typeof readViewerSize> | null = null;
19
+
20
+// Cached so an unchanged size keeps its identity: a new one resets the zoom.
21
+function getViewerSize() {
22
+ const next = readViewerSize();
23
+ if (next.width !== viewerSize?.width || next.height !== viewerSize.height) viewerSize = next;
24
+ return viewerSize;
25
+}
26
+
27
+function subscribeViewerSize(onChange: () => void) {
28
+ window.addEventListener("resize", onChange);
29
+ // Fullscreen caption-strip changes may not emit resize.
30
+ const stopOverlayListener = onWindowControlsOverlayGeometryChange(onChange);
31
+ return () => {
32
+ window.removeEventListener("resize", onChange);
33
+ stopOverlayListener();
34
+ };
35
+}
36
+
37
export interface ZoomableImageHandle {
38
pan: (key: string) => boolean;
39
}
@@ -33,10 +53,14 @@ export function ZoomableImage({
53
}) {
54
const viewportRef = useRef<HTMLDivElement>(null);
55
const [naturalSize, setNaturalSize] = useState({ width: 0, height: 0 });
36
- const [viewerSize, setViewerSize] = useState(readViewerSize);
56
+ const viewerSize = useSyncExternalStore(subscribeViewerSize, getViewerSize);
57
const [zoom, setZoom] = useState(1);
38
- const zoomRef = useRef(1);
39
- const anchorRef = useRef<{ x: number; y: number; clientX: number; clientY: number } | null>(null);
58
+ // A resized viewer refits the image.
59
+ const [zoomViewerSize, setZoomViewerSize] = useState(viewerSize);
60
+ if (zoomViewerSize !== viewerSize) {
61
+ setZoomViewerSize(viewerSize);
62
+ setZoom(1);
63
+ }
64
const dragRef = useRef<{
65
pointerId: number;
66
x: number;
@@ -60,7 +84,7 @@ export function ZoomableImage({
84
() => ({
85
pan(key) {
86
const viewport = viewportRef.current;
63
- if (!viewport || zoomRef.current <= 1) return false;
87
+ if (!viewport || zoom <= 1) return false;
88
// A vertical scrollbar alone must not swallow gallery navigation.
89
if (
90
(key === "ArrowLeft" || key === "ArrowRight") &&
@@ -86,73 +110,52 @@ export function ZoomableImage({
110
return true;
111
},
112
}),
89
- [],
113
+ [zoom],
114
);
115
116
const changeZoom = (next: number, point?: { x: number; y: number }) => {
117
const viewport = viewportRef.current;
94
- const previous = zoomRef.current;
118
const clamped = Math.min(MAX_ZOOM, Math.max(1, next));
96
- if (!viewport || previous === clamped) return;
119
+ if (!viewport || zoom === clamped) return;
120
const bounds = viewport.getBoundingClientRect();
121
const x = point ? point.x - bounds.left : viewport.clientWidth / 2;
122
const y = point ? point.y - bounds.top : viewport.clientHeight / 2;
100
- anchorRef.current = {
101
- x: (viewport.scrollLeft + x) / previous,
102
- y: (viewport.scrollTop + y) / previous,
103
- clientX: bounds.left + x,
104
- clientY: bounds.top + y,
105
- };
106
- zoomRef.current = clamped;
107
- setZoom(clamped);
123
+ const anchorX = (viewport.scrollLeft + x) / zoom;
124
+ const anchorY = (viewport.scrollTop + y) / zoom;
125
+ const clientX = bounds.left + x;
126
+ const clientY = bounds.top + y;
127
+ // The new size must be laid out before the scroll position can keep the anchor in place.
128
+ flushSync(() => setZoom(clamped));
129
+ const resized = viewport.getBoundingClientRect();
130
+ viewport.scrollLeft = anchorX * clamped - (clientX - resized.left);
131
+ viewport.scrollTop = anchorY * clamped - (clientY - resized.top);
132
};
133
110
- useLayoutEffect(() => {
111
- const viewport = viewportRef.current;
112
- const anchor = anchorRef.current;
113
- if (!viewport || !anchor) return;
114
- const bounds = viewport.getBoundingClientRect();
115
- viewport.scrollLeft = anchor.x * zoom - (anchor.clientX - bounds.left);
116
- viewport.scrollTop = anchor.y * zoom - (anchor.clientY - bounds.top);
117
- anchorRef.current = null;
118
- }, [zoom]);
119
-
120
- useEffect(() => {
121
- const resize = () => {
122
- setViewerSize(readViewerSize());
123
- changeZoom(1);
124
- };
125
- window.addEventListener("resize", resize);
126
- // Fullscreen caption-strip changes may not emit resize.
127
- const stopOverlayListener = onWindowControlsOverlayGeometryChange(resize);
128
- return () => {
129
- window.removeEventListener("resize", resize);
130
- stopOverlayListener();
131
- };
132
- }, [changeZoom]);
133
-
134
- useEffect(() => {
135
- const viewport = viewportRef.current;
136
- if (!viewport) return;
134
+ const attachViewport = (viewport: HTMLDivElement) => {
135
+ viewportRef.current = viewport;
136
+ // React's onWheel is passive and cannot stop the page from scrolling.
137
const wheel = (event: WheelEvent) => {
138
if (event.deltaY === 0) return;
139
event.preventDefault();
140
const delta =
141
event.deltaY *
142
(event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? viewport.clientHeight : 1);
143
- changeZoom(zoomRef.current * Math.exp(-delta * (event.ctrlKey ? 0.01 : 0.002)), {
143
+ changeZoom(zoom * Math.exp(-delta * (event.ctrlKey ? 0.01 : 0.002)), {
144
x: event.clientX,
145
y: event.clientY,
146
});
147
};
148
viewport.addEventListener("wheel", wheel, { passive: false });
149
- return () => viewport.removeEventListener("wheel", wheel);
150
- }, [changeZoom]);
149
+ return () => {
150
+ viewport.removeEventListener("wheel", wheel);
151
+ viewportRef.current = null;
152
+ };
153
+ };
154
155
return (
156
<div className="min-w-0">
157
<div
155
- ref={viewportRef}
158
+ ref={attachViewport}
159
role="region"
160
aria-label={`${name}, zoomable image`}
161
aria-description="Click to zoom in or return to fit. Scroll to zoom, drag to pan. Use Enter to toggle zoom, plus or minus to zoom, and 0 to fit."
@@ -167,19 +170,19 @@ export function ZoomableImage({
170
onClick={(event) => {
171
// Pointer capture emits a click after dragging; preserve zoom.
172
if (suppressClickRef.current || event.detail > 1) return;
170
- changeZoom(zoomRef.current > 1 ? 1 : 2, { x: event.clientX, y: event.clientY });
173
+ changeZoom(zoom > 1 ? 1 : 2, { x: event.clientX, y: event.clientY });
174
}}
175
onKeyDown={(event) => {
176
if (event.ctrlKey || event.metaKey || event.altKey) return;
177
if (event.key === "Enter" || event.key === " ") {
178
event.preventDefault();
176
- if (!event.repeat) changeZoom(zoomRef.current > 1 ? 1 : 2);
179
+ if (!event.repeat) changeZoom(zoom > 1 ? 1 : 2);
180
} else if (event.key === "+" || event.key === "=") {
181
event.preventDefault();
179
- changeZoom(zoomRef.current * 1.5);
182
+ changeZoom(zoom * 1.5);
183
} else if (event.key === "-") {
184
event.preventDefault();
182
- changeZoom(zoomRef.current / 1.5);
185
+ changeZoom(zoom / 1.5);
186
} else if (event.key === "0") {
187
event.preventDefault();
188
changeZoom(1);
@@ -188,7 +191,7 @@ export function ZoomableImage({
191
onPointerDown={(event) => {
192
if (dragRef.current) return;
193
suppressClickRef.current = false;
191
- if (event.pointerType !== "mouse" || event.button !== 0 || zoomRef.current <= 1) return;
194
+ if (event.pointerType !== "mouse" || event.button !== 0 || zoom <= 1) return;
195
const viewport = event.currentTarget;
196
const bounds = viewport.getBoundingClientRect();
197
if (
apps/web/src/components/chat/threadOverlayRetention.ts
new
+15
@@ -0,0 +1,15 @@
1
+/**
2
+ * Chat overlays (dialogs, media previews) are opened for one thread and must not
3
+ * outlive its route. Overlay modules register here when they load, so the route
4
+ * listener can drop them without importing the overlays themselves.
5
+ */
6
+const retainers: Array<(threadKey: string | null) => void> = [];
7
+
8
+export function registerThreadOverlay(retain: (threadKey: string | null) => void): void {
9
+ retainers.push(retain);
10
+}
11
+
12
+/** Drops every overlay opened for a thread other than `threadKey`. */
13
+export function retainThreadOverlaysForThread(threadKey: string | null): void {
14
+ for (const retain of retainers) retain(threadKey);
15
+}
apps/web/src/components/media/AttachmentImage.tsx
+31
-26
@@ -1,10 +1,4 @@
1
-import {
2
- useEffect,
3
- useEffectEvent,
4
- useState,
5
- type ComponentProps,
6
- type SyntheticEvent,
7
-} from "react";
1
+import { useEffect, useRef, useState, type ComponentProps, type SyntheticEvent } from "react";
2
import { isHeicImageFile } from "../../lib/imageCompression";
3
4
type AttachmentImageProps = ComponentProps<"img"> & { name: string; mimeType?: string | undefined };
@@ -24,35 +18,46 @@ export function AttachmentImage({ name, mimeType, ...props }: AttachmentImagePro
18
);
19
}
20
21
+type DecodeAttempt = { readonly controller: AbortController; objectUrl?: string };
22
+
23
function DecodedImage({ name, mimeType, src, onError, ...props }: AttachmentImageProps) {
28
- const [decodeError, setDecodeError] = useState<SyntheticEvent<HTMLImageElement> | null>(null);
24
const [previewUrl, setPreviewUrl] = useState<string>();
30
- const reportError = useEffectEvent((event: SyntheticEvent<HTMLImageElement>) => onError?.(event));
31
- useEffect(() => {
32
- if (!decodeError || !src) return;
33
- const controller = new AbortController();
34
- let objectUrl: string | undefined;
25
+ // One decode per mount; the parent keys this component by src.
26
+ const decodeRef = useRef<DecodeAttempt | null>(null);
27
+
28
+ // The browser cannot show HEIC or TIFF itself, so its load error starts the decode.
29
+ const decode = (event: SyntheticEvent<HTMLImageElement>) => {
30
+ if (decodeRef.current !== null || !src) return onError?.(event);
31
+ const attempt: DecodeAttempt = { controller: new AbortController() };
32
+ decodeRef.current = attempt;
33
+ const { signal } = attempt.controller;
34
void loadImageDecoder()
35
.then(async ({ decodeImagePreview }) => {
37
- if (controller.signal.aborted) return;
36
+ if (signal.aborted) return;
37
const blob = await decodeImagePreview(
38
src,
39
/\.hei[cf]$/i.test(name) || /^image\/hei[cf]$/i.test(mimeType ?? ""),
41
- controller.signal,
40
+ signal,
41
);
43
- if (controller.signal.aborted) return;
44
- objectUrl = URL.createObjectURL(blob);
45
- setPreviewUrl(objectUrl);
42
+ if (signal.aborted) return;
43
+ attempt.objectUrl = URL.createObjectURL(blob);
44
+ setPreviewUrl(attempt.objectUrl);
45
})
46
.catch(() => {
48
- if (!controller.signal.aborted) reportError(decodeError);
47
+ if (!signal.aborted) onError?.(event);
48
});
50
- return () => {
51
- controller.abort();
52
- if (objectUrl) URL.revokeObjectURL(objectUrl);
53
- };
54
- }, [decodeError, name, src, mimeType]);
55
- return (
56
- <img {...props} src={previewUrl ?? src} onError={decodeError ? onError : setDecodeError} />
49
+ };
50
+
51
+ // oxlint-disable-next-line t3code/react-effect-budget -- the async decode and its blob URL live as long as this component
52
+ useEffect(
53
+ () => () => {
54
+ const attempt = decodeRef.current;
55
+ if (attempt === null) return;
56
+ attempt.controller.abort();
57
+ if (attempt.objectUrl) URL.revokeObjectURL(attempt.objectUrl);
58
+ },
59
+ [],
60
);
61
+
62
+ return <img {...props} src={previewUrl ?? src} onError={decode} />;
63
}
apps/web/src/pierre-icons.ts
+6
-1
@@ -254,7 +254,12 @@ export function hasSpecificPierreIconForFileName(fileName: string): boolean {
254
}
255
256
export function ensurePierreIconSprite(): void {
257
- if (typeof document === "undefined" || document.getElementById(PIERRE_ICON_SPRITE_ID)) return;
257
+ if (
258
+ typeof document === "undefined" ||
259
+ !document.body ||
260
+ document.getElementById(PIERRE_ICON_SPRITE_ID)
261
+ )
262
+ return;
263
const container = document.createElement("div");
264
container.id = PIERRE_ICON_SPRITE_ID;
265
container.setAttribute("aria-hidden", "true");
packages/client-runtime/src/state/mcpApps.ts
+6
-1
@@ -2,7 +2,7 @@ import { WS_METHODS } from "@t3tools/contracts";
2
import type { Atom } from "effect/reactivity";
3
4
import type { EnvironmentRegistry } from "../connection/registry.ts";
5
-import { createEnvironmentRpcCommand } from "./runtime.ts";
5
+import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
6
7
export function createMcpAppEnvironmentAtoms<R, E>(
8
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
@@ -16,6 +16,11 @@ export function createMcpAppEnvironmentAtoms<R, E>(
16
label: "environment-command:mcp-apps:tool-info",
17
tag: WS_METHODS.mcpAppsToolInfo,
18
}),
19
+ /** The tool definition an app reads from its host context. */
20
+ toolInfoQuery: createEnvironmentRpcQueryAtomFamily(runtime, {
21
+ label: "environment-data:mcp-apps:tool-info",
22
+ tag: WS_METHODS.mcpAppsToolInfo,
23
+ }),
24
readResource: createEnvironmentRpcCommand(runtime, {
25
label: "environment-command:mcp-apps:read-resource",
26
tag: WS_METHODS.mcpAppsReadResource,