TypeScript
perf(web): chat markdown compiles with the React Compiler (#20715)
Julius Marmingefcda161afb90
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 94a3f0e0fa5..d1b810ed56f 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -87,10 +87,9 @@ import React, {type MouseEvent as ReactMouseEvent,isValidElement,use,- useCallback,memo,useEffect,- useMemo,+ useLayoutEffect,useRef,useState,type ReactNode,@@ -109,7 +108,6 @@ import { parseComposerContextHref } from "@t3tools/shared/composerContextReferenimport { parseThreadLinkHref } from "@t3tools/shared/threadLinks";import { AssistantCitationChip } from "./chat/AssistantCitationChip";import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";-import { isWindowsAbsolutePath } from "@t3tools/shared/path";import {artifactTemplateFromHastProperties,renderCodexInlineDirectivesAsMarkdown,@@ -479,16 +477,6 @@ function isClosedCodeFence(node: ReactMarkdownExtraProps["node"], text: string):);}-type MarkdownAstNode = {- type?: string;- meta?: unknown;- url?: string;- data?: {- hProperties?: Record<string, unknown>;- };- children?: MarkdownAstNode[];-};-function nodeToPlainText(node: ReactNode): string {if (typeof node === "string" || typeof node === "number") {return String(node);@@ -575,7 +563,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {setExpanded((value) => !value);}- const handleCopy = useCallback((format: "markdown" | "csv") => {+ const handleCopy = (format: "markdown" | "csv") => {const table = containerRef.current?.querySelector("table");if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {return;@@ -599,7 +587,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {.catch((cause) => {reportMarkdownActionFailure({ operation: "copy-table", format }, cause);});- }, []);+ };useEffect(() => () => {@@ -677,7 +665,7 @@ function MarkdownDetails({const [isOpen, setIsOpen] = useState(open);const searching = use(MarkdownFindContext);const expanded = isOpen;- const revealForFind = useCallback(() => setIsOpen(true), []);+ const revealForFind = () => setIsOpen(true);// Base UI only listens for `beforematch` on a panel mounted at its first// render; a closed panel mounts later, when find starts, so listen here.const findRevealRef = useFindRevealRef(revealForFind);@@ -853,7 +841,7 @@ function MarkdownCodeBlock({// make the rendered command differ from what the terminal would receive.!/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));- const handleCopy = useCallback(() => {+ const handleCopy = () => {if (typeof navigator === "undefined" || navigator.clipboard == null) {return;}@@ -879,7 +867,7 @@ function MarkdownCodeBlock({cause,);});- }, [code, fenceTitle, language]);+ };useEffect(() => () => {@@ -995,7 +983,7 @@ function MarkdownMermaidCodeBlock({}) {const [showCode, setShowCode] = useState(false);const searching = use(MarkdownFindContext);- const revealSource = useCallback(() => setShowCode(true), []);+ const revealSource = () => setShowCode(true);const sourceRevealRef = useFindRevealRef(revealSource);const showDiagram = !showCode && !isStreaming && code.trim().length > 0;const toggleLabel = showCode ? "Show diagram" : "Show code";@@ -1114,12 +1102,10 @@ function UncachedShikiCodeBlock({preserveLines,}: UncachedShikiCodeBlockProps) {const highlighter = use(getSyntaxHighlighterPromise(language));- const incrementalHighlight = useMemo(- () =>- preserveLines ? createIncrementalHighlightedDocument(highlighter, language, themeName) : null,- [highlighter, preserveLines, language, themeName],- );- const highlighted = useMemo(() => {+ const incrementalHighlight = preserveLines+ ? createIncrementalHighlightedDocument(highlighter, language, themeName)+ : null;+ const highlighted = (() => {try {if (incrementalHighlight) return incrementalHighlight(code);return preserveLines@@ -1134,7 +1120,7 @@ function UncachedShikiCodeBlock({? highlighter.codeToHast(code, { lang: "text", theme: themeName }): highlighter.codeToHtml(code, { lang: "text", theme: themeName });}- }, [code, highlighter, incrementalHighlight, language, preserveLines, themeName]);+ })();useEffect(() => {if (!isStreaming) {@@ -1191,23 +1177,22 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";const failedFaviconHosts = new Set<string>();-function brandLinkIcon(host: string): typeof GitHubIcon | null {+function isGitHubHost(host: string): boolean {const hostname = host.toLowerCase();- if (hostname === "github.com" || hostname.endsWith(".github.com")) return GitHubIcon;- return null;+ return hostname === "github.com" || hostname.endsWith(".github.com");}const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {const [failedHost, setFailedHost] = useState<string | null>(null);- const BrandIcon = brandLinkIcon(host);- const faviconUrl = BrandIcon ? null : faviconUrlForOrigin(`https://${host}`);+ const brandIcon = isGitHubHost(host);+ const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);return (<spanclassName="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"aria-hidden>- {BrandIcon ? (- <BrandIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />+ {brandIcon ? (+ <GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />) : (@@ -1375,19 +1360,16 @@ function ChatMarkdownImage(props: {const failed = props.sourceFailed === true || (src !== null && failedSrc === src);const settled = src !== null && !failed && (!props.standalone || loadedSrc !== null);// Cached images are complete before `onLoad` can fire.- const markLoadedIfComplete = useCallback(- (image: HTMLImageElement | null) => {- if (!image) return;- if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src);- markdownImageItems.set(image, {- src,- name: props.alt.trim() || "image",- actionsSource: props.actionsSource,- ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),- });- },- [props.actionsSource, props.alt, props.originalUrl, src],- );+ const markLoadedIfComplete = (image: HTMLImageElement | null) => {+ if (!image) return;+ if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src);+ markdownImageItems.set(image, {+ src,+ name: props.alt.trim() || "image",+ actionsSource: props.actionsSource,+ ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),+ });+ };const imageEvents = (loadingSrc: string) => ({onLoad: () => {setLoadedSrc(loadingSrc);@@ -1881,7 +1863,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({onReveal,revealLabel,}: MarkdownFileLinkProps) {- const handleOpenInEditor = useCallback(() => {+ const handleOpenInEditor = () => {if (!onOpen) {return;}@@ -1917,9 +1899,9 @@ const MarkdownFileLink = memo(function MarkdownFileLink({);}})();- }, [onOpen, targetPath]);+ };- const handleOpenInFilePreview = useCallback(() => {+ const handleOpenInFilePreview = () => {if (threadRef && panelPath) {onOpenInPanel(panelPath, line);return;@@ -1929,9 +1911,9 @@ const MarkdownFileLink = memo(function MarkdownFileLink({return;}handleOpenInEditor();- }, [handleOpenInEditor, line, onOpenInPanel, onOpenMedia, panelPath, threadRef]);+ };- const handleOpenInBrowser = useCallback(() => {+ const handleOpenInBrowser = () => {if (!onOpenInBrowser) {return;}@@ -1967,9 +1949,9 @@ const MarkdownFileLink = memo(function MarkdownFileLink({);}})();- }, [onOpenInBrowser, targetPath]);+ };- const handleRevealInFileManager = useCallback(() => {+ const handleRevealInFileManager = () => {if (!onReveal) {return;}@@ -2005,128 +1987,106 @@ const MarkdownFileLink = memo(function MarkdownFileLink({);}})();- }, [onReveal, targetPath]);+ };- const handleCopy = useCallback(- (value: string, title: string) => {- if (typeof window === "undefined" || !navigator.clipboard?.writeText) {+ const handleCopy = (value: string, title: string) => {+ if (typeof window === "undefined" || !navigator.clipboard?.writeText) {+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: `Failed to copy ${title.toLowerCase()}`,+ description: "Clipboard API unavailable.",+ }),+ );+ return;+ }++ void navigator.clipboard.writeText(value).then(+ () => {+ toastManager.add({+ type: "success",+ title: `${title} copied`,+ description: value,+ });+ },+ (error) => {+ reportMarkdownActionFailure(+ { operation: "copy-file-path", target: targetPath, copyTarget: title },+ error,+ );toastManager.add(stackedThreadToast({type: "error",title: `Failed to copy ${title.toLowerCase()}`,- description: "Clipboard API unavailable.",+ description: error instanceof Error ? error.message : "An error occurred.",}),);- return;- }-- void navigator.clipboard.writeText(value).then(- () => {- toastManager.add({- type: "success",- title: `${title} copied`,- description: value,- });- },- (error) => {- reportMarkdownActionFailure(- { operation: "copy-file-path", target: targetPath, copyTarget: title },- error,- );- toastManager.add(- stackedThreadToast({- type: "error",- title: `Failed to copy ${title.toLowerCase()}`,- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- },- );- },- [targetPath],- );+ },+ );+ };- const showFileContextMenu = useCallback(- async (position: { x: number; y: number }) => {- const api = readLocalApi();- if (!api) return;+ const showFileContextMenu = async (position: { x: number; y: number }) => {+ const api = readLocalApi();+ if (!api) return;- try {- const clicked = await api.contextMenu.show(- [- ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),- ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),- ...(onOpenInBrowser- ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)- : []),- ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),- { id: "copy-relative", label: "Copy relative path" },- { id: "copy-full", label: "Copy full path" },- ] as const,- position,- );+ try {+ const clicked = await api.contextMenu.show(+ [+ ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),+ ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),+ ...(onOpenInBrowser+ ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)+ : []),+ ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),+ { id: "copy-relative", label: "Copy relative path" },+ { id: "copy-full", label: "Copy full path" },+ ] as const,+ position,+ );- if (clicked === "preview-media") {- onOpenMedia?.();- return;- }- if (clicked === "open") {- handleOpenInEditor();- return;- }- if (clicked === "open-in-browser") {- handleOpenInBrowser();- return;- }- if (clicked === "reveal") {- handleRevealInFileManager();- return;- }- if (clicked === "copy-relative") {- handleCopy(displayPath, "Relative path");- return;- }- if (clicked === "copy-full") {- handleCopy(targetPath, "Full path");- }- } catch (cause) {- reportMarkdownActionFailure(- { operation: "show-file-context-menu", target: targetPath },- cause,- );+ if (clicked === "preview-media") {+ onOpenMedia?.();+ return;}- },- [- displayPath,- handleCopy,- handleOpenInBrowser,- handleOpenInEditor,- handleRevealInFileManager,- onOpenInBrowser,- onOpenMedia,- onOpen,- onReveal,- openInEditorMenuLabel,- revealLabel,- targetPath,- ],- );+ if (clicked === "open") {+ handleOpenInEditor();+ return;+ }+ if (clicked === "open-in-browser") {+ handleOpenInBrowser();+ return;+ }+ if (clicked === "reveal") {+ handleRevealInFileManager();+ return;+ }+ if (clicked === "copy-relative") {+ handleCopy(displayPath, "Relative path");+ return;+ }+ if (clicked === "copy-full") {+ handleCopy(targetPath, "Full path");+ }+ } catch (cause) {+ reportMarkdownActionFailure(+ { operation: "show-file-context-menu", target: targetPath },+ cause,+ );+ }+ };- const handleContextMenu = useCallback(- (event: ReactMouseEvent<HTMLElement>) => {- event.preventDefault();- event.stopPropagation();- const position =- event.clientX === 0 && event.clientY === 0- ? (() => {- const bounds = event.currentTarget.getBoundingClientRect();- return { x: bounds.left, y: bounds.bottom };- })()- : { x: event.clientX, y: event.clientY };- void showFileContextMenu(position);- },- [showFileContextMenu],- );+ const handleContextMenu = (event: ReactMouseEvent<HTMLElement>) => {+ event.preventDefault();+ event.stopPropagation();+ const position =+ event.clientX === 0 && event.clientY === 0+ ? (() => {+ const bounds = event.currentTarget.getBoundingClientRect();+ return { x: bounds.left, y: bounds.bottom };+ })()+ : { x: event.clientX, y: event.clientY };+ void showFileContextMenu(position);+ };const canOpenInEditor = onOpen !== undefined;const canOpenInBrowser = onOpenInBrowser !== undefined;@@ -2266,16 +2226,41 @@ function useChatMarkdownState({githubMedia = false,}: ChatMarkdownProps) {const { resolvedTheme } = useTheme();- const [localMediaPreview, setLocalMediaPreview] = useState<ExpandedImagePreview | null>(null);const markdownRef = useRef<HTMLDivElement>(null);- const expandMedia = onImageExpand ?? setLocalMediaPreview;const mediaRequestId = useRef(0);- useEffect(() => {- setLocalMediaPreview(null);- return () => {+ // A preview opened from another thread or workspace never carries over.+ const mediaScopeKey = [+ threadRef?.environmentId,+ threadRef?.threadId,+ explicitEnvironmentId,+ cwd,+ imageBaseDir,+ ].join("\u0000");+ // Tagged with the scope it was opened in: a request from the previous scope can+ // resolve before the effect cleanup below invalidates it, and must stay hidden.+ const [localMedia, setLocalMedia] = useState<{+ scope: string;+ preview: ExpandedImagePreview;+ } | null>(null);+ const localMediaPreview = localMedia?.scope === mediaScopeKey ? localMedia.preview : null;+ const closeLocalMediaPreview = () => setLocalMedia(null);+ const expandMedia =+ onImageExpand ??+ ((preview: ExpandedImagePreview) => setLocalMedia({ scope: mediaScopeKey, preview }));+ const [mediaScope, setMediaScope] = useState(mediaScopeKey);+ if (mediaScope !== mediaScopeKey) {+ setMediaScope(mediaScopeKey);+ setLocalMedia(null);+ }+ // A layout cleanup runs in the commit that changes scope, so a request resolving+ // before paint cannot reach a parent onImageExpand either.+ useLayoutEffect(+ () => () => {mediaRequestId.current += 1;- };- }, [threadRef?.environmentId, threadRef?.threadId, explicitEnvironmentId, cwd, imageBaseDir]);+ },+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Leaving the scope invalidates media requests still loading for it.+ [mediaScopeKey],+ );const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {reportFailure: false,refresh: true,@@ -2295,48 +2280,49 @@ function useChatMarkdownState({canOperateHost &&canUseMarkdownFileShellActions(environmentId, remoteOpen.state.mode, remoteOpen.isResolved);const preparedConnection = usePreparedConnection(environmentId);- const openMarkdownMedia = useCallback(- (source: string, resolvedFilePath?: string, clickedImage?: HTMLImageElement | null) => {- const requestId = ++mediaRequestId.current;- void resolveMarkdownMediaPreview({- source,- resolvedFilePath,- cwd,- threadRef,- httpBaseUrl:- preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : undefined,- createAssetUrl,- onOpenFile: threadRef- ? (path) => useRightPanelStore.getState().openFile(threadRef, path)- : undefined,- }).then(- (preview) => {- if (preview && mediaRequestId.current === requestId) {- const selected = preview.images[preview.index];- expandMedia(- selected && selected.type !== "video" && markdownRef.current- ? markdownImageGallery(clickedImage ?? markdownRef.current, selected)- : preview,- );- }- },- (error: unknown) => {- if (mediaRequestId.current !== requestId) return;- toastManager.add(- stackedThreadToast({- type: "error",- title: "Media unavailable",- description:- error instanceof Error- ? error.message- : "The file could not be loaded. It may have been moved or deleted.",- }),+ const openMarkdownMedia = (+ source: string,+ resolvedFilePath?: string,+ clickedImage?: HTMLImageElement | null,+ ) => {+ const requestId = ++mediaRequestId.current;+ void resolveMarkdownMediaPreview({+ source,+ resolvedFilePath,+ cwd,+ threadRef,+ httpBaseUrl:+ preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : undefined,+ createAssetUrl,+ onOpenFile: threadRef+ ? (path) => useRightPanelStore.getState().openFile(threadRef, path)+ : undefined,+ }).then(+ (preview) => {+ if (preview && mediaRequestId.current === requestId) {+ const selected = preview.images[preview.index];+ expandMedia(+ selected && selected.type !== "video" && markdownRef.current+ ? markdownImageGallery(clickedImage ?? markdownRef.current, selected)+ : preview,);- },- );- },- [createAssetUrl, cwd, expandMedia, preparedConnection, threadRef],- );+ }+ },+ (error: unknown) => {+ if (mediaRequestId.current !== requestId) return;+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Media unavailable",+ description:+ error instanceof Error+ ? error.message+ : "The file could not be loaded. It may have been moved or deleted.",+ }),+ );+ },+ );+ };// Only the parts of the server config markdown reads. The config object itself// changes with every provider status push, which would re-render every// visible reply.@@ -2358,31 +2344,28 @@ function useChatMarkdownState({const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {reportFailure: false,});- const revealFileInFileManager = useCallback(- (filePath: string) => {- if (environmentId === null) {- return Promise.resolve(- AsyncResult.failure<void, PreferredEditorEnvironmentRequiredError>(- Cause.fail(new PreferredEditorEnvironmentRequiredError({ targetPath: filePath })),- ),- );- }- if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {- return Promise.resolve(- AsyncResult.failure<void, Error>(- Cause.fail(new Error("This connection cannot reveal files on this environment.")),- ),- );- }- return openInEditor({- environmentId,- input: { cwd: filePath, editor: "file-manager", reveal: true },- });- },- [environmentId, openInEditor],- );+ const revealFileInFileManager = (filePath: string) => {+ if (environmentId === null) {+ return Promise.resolve(+ AsyncResult.failure<void, PreferredEditorEnvironmentRequiredError>(+ Cause.fail(new PreferredEditorEnvironmentRequiredError({ targetPath: filePath })),+ ),+ );+ }+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {+ return Promise.resolve(+ AsyncResult.failure<void, Error>(+ Cause.fail(new Error("This connection cannot reveal files on this environment.")),+ ),+ );+ }+ return openInEditor({+ environmentId,+ input: { cwd: filePath, editor: "file-manager", reveal: true },+ });+ };const diffThemeName = resolveDiffThemeName(resolvedTheme);- const markdownFileLinkMetaByHref = useMemo(() => {+ const markdownFileLinkMetaByHref = (() => {const metaByHref = new Map<string,NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>@@ -2397,8 +2380,8 @@ function useChatMarkdownState({}}return metaByHref;- }, [cwd, imageBaseDir, text]);- const inlineCodeFileLinkMetaByText = useMemo(() => {+ })();+ const inlineCodeFileLinkMetaByText = (() => {const metaByText = new Map<string, MarkdownFileLinkMeta>();for (const span of extractInlineCodeSpans(text)) {if (metaByText.has(span)) continue;@@ -2408,22 +2391,22 @@ function useChatMarkdownState({}}return metaByText;- }, [cwd, imageBaseDir, text]);- const fileLinkParentSuffixByPath = useMemo(() => {+ })();+ const fileLinkParentSuffixByPath = (() => {const filePaths = [...[...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath),...[...inlineCodeFileLinkMetaByText.values()].map((meta) => meta.filePath),];return buildFileLinkParentSuffixByPath(filePaths);- }, [inlineCodeFileLinkMetaByText, markdownFileLinkMetaByHref]);- const markdownUrlTransform = useCallback((href: string) => {+ })();+ const markdownUrlTransform = (href: string) => {if (parseAssistantCitationHref(href)) return href;if (parseComposerContextHref(href)) return href;if (parseThreadLinkHref(href)) return href;if (isWindowsDrivePathHref(href)) return href;return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);- }, []);- const handleCopy = useCallback((event: ReactClipboardEvent<HTMLDivElement>) => {+ };+ const handleCopy = (event: ReactClipboardEvent<HTMLDivElement>) => {const selection = window.getSelection();if (!selection || selection.isCollapsed || !event.clipboardData) return;const payload = chatMarkdownClipboardPayload(selection);@@ -2437,301 +2420,231 @@ function useChatMarkdownState({? encodeComposerContextClipboardHtml(payload.text, fragment, payload.html): payload.html,);- }, []);+ };const openChangeRequestLink = useOpenChangeRequestLink(threadRef, pullRequestPanelRef);const openDeferredMarkdownLink = useOpenLink(threadRef);// Subscribed rather than read at click time: the anchor has to decide// synchronously whether to intercept its `_blank`, and a subscription is what// makes a persisted "app" apply once settings hydrate after launch.const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);- const resolveThreadPullRequest = useCallback(- (href: string): (ThreadPullRequestKey & { readonly url: string }) | null => {- if (- threadRef === undefined ||- readThreadShell(threadRef) === null ||- !pullRequestLinking.canLink(href)- )- return null;- const parsed = parseChangeRequestUrl(href);- return parsed === null ? null : { ...parsed, url: href };- },- [pullRequestLinking, threadRef],- );- const linkedThreadPullRequestFor = useCallback(- (href: string) => {- if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href))- return null;- const parsed = parseChangeRequestUrl(href);- return parsed === null ? null : { ...parsed, url: href };- },- [pullRequestLinking, threadRef],- );- const updateThreadPullRequestLink = useCallback(- async (href: string, linked: boolean) => {- if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return;- if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;- await pullRequestLinking.changeLink(threadRef, href, linked);- },- [linkedThreadPullRequestFor, pullRequestLinking, threadRef],- );- const openExternalLinkInPreview = useCallback(- (url: string) => {- if (!threadRef || !canOperatePreview) {- return Promise.resolve(- AsyncResult.failure<void, BrowserPreviewUnavailableError>(- Cause.fail(- new BrowserPreviewUnavailableError({- message: "Preview access is unavailable for this client.",- }),- ),+ const resolveThreadPullRequest = (+ href: string,+ ): (ThreadPullRequestKey & { readonly url: string }) | null => {+ if (+ threadRef === undefined ||+ readThreadShell(threadRef) === null ||+ !pullRequestLinking.canLink(href)+ )+ return null;+ const parsed = parseChangeRequestUrl(href);+ return parsed === null ? null : { ...parsed, url: href };+ };+ const linkedThreadPullRequestFor = (href: string) => {+ if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href))+ return null;+ const parsed = parseChangeRequestUrl(href);+ return parsed === null ? null : { ...parsed, url: href };+ };+ const updateThreadPullRequestLink = async (href: string, linked: boolean) => {+ if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return;+ if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;+ await pullRequestLinking.changeLink(threadRef, href, linked);+ };+ const openExternalLinkInPreview = (url: string) => {+ if (!threadRef || !canOperatePreview) {+ return Promise.resolve(+ AsyncResult.failure<void, BrowserPreviewUnavailableError>(+ Cause.fail(+ new BrowserPreviewUnavailableError({+ message: "Preview access is unavailable for this client.",+ }),),- );- }- return openUrlInPreview({ threadRef, url, openPreview }).then((result) => {- if (result._tag === "Success") recordVisitForThread(threadRef, url);- else if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- if (error instanceof BrowserSettingsReadError) {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Unable to open link in browser",- description: error.message,- }),- );- }+ ),+ );+ }+ return openUrlInPreview({ threadRef, url, openPreview }).then((result) => {+ if (result._tag === "Success") recordVisitForThread(threadRef, url);+ else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ if (error instanceof BrowserSettingsReadError) {+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Unable to open link in browser",+ description: error.message,+ }),+ );}- return result;- });- },- [canOperatePreview, openPreview, threadRef],- );- const openMarkdownFileInPreview = useCallback(- (path: string) => {- if (!threadRef || !canOperatePreview || preparedConnection._tag === "None") {- return Promise.resolve(- AsyncResult.failure<void, BrowserPreviewUnavailableError>(- Cause.fail(- new BrowserPreviewUnavailableError({- message: "Environment is not connected.",- }),- ),- ),- );- }- return openFileInPreview({- threadRef,- filePath: path,- workspaceRoot: cwd,- httpBaseUrl: preparedConnection.value.httpBaseUrl,- createAssetUrl,- openPreview,- });- },- [canOperatePreview, createAssetUrl, cwd, openPreview, preparedConnection, threadRef],- );- const findWorkspaceBasenameMatch = useCallback(- async (workspaceRelativePath: string) => {- if (- !cwd ||- environmentId === null ||- !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||- !needsWorkspaceBasenameLookup(workspaceRelativePath)- ) {- return null;- }- const result = await searchProjectEntries({- environmentId,- input: {- cwd,- query: workspaceRelativePath,- limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,- kind: "file",- },- });- return result._tag === "Success"- ? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)- : null;- },- [cwd, environmentId, searchProjectEntries],- );- const openFileInPanel = useCallback(- (panelPath: string, line: number | undefined) => {- if (!threadRef) return;- // Claimed on every open so a synchronous one supersedes a lookup already- // in flight.- const isLatestLookup = claimWorkspaceBasenameLookup();- const openAt = (path: string) =>- useRightPanelStore.getState().openFile(threadRef, path, line);- if (!cwd || !needsWorkspaceBasenameLookup(panelPath)) {- openAt(panelPath);- return;}- void (async () => {- const match = await findWorkspaceBasenameMatch(panelPath);- if (!isLatestLookup()) return;- openAt(match ?? panelPath);- })();- },- [cwd, findWorkspaceBasenameMatch, threadRef],- );- const revealMarkdownFileInFileManager = useCallback(- async (fileLinkMeta: MarkdownFileLinkMeta) => {- const workspaceRelativePath = fileLinkMeta.workspaceRelativePath;- const match = workspaceRelativePath- ? await findWorkspaceBasenameMatch(workspaceRelativePath)- : null;- const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;- return revealFileInFileManager(filePath);- },- [cwd, findWorkspaceBasenameMatch, revealFileInFileManager],- );- const fileLinkChip = useCallback(- (fileLinkMeta: MarkdownFileLinkMeta, copyMarkdown: string, mediaSource?: string) => {- const mediaPath = mediaSource ?? fileLinkMeta.filePath;- const canPreviewMedia =- mediaMimeTypeFromExtension(- fileLinkMeta.basename.slice(fileLinkMeta.basename.lastIndexOf(".")),- ) !== null;- const panelPath =- fileLinkMeta.workspaceRelativePath ??- (!canPreviewMedia && isAbsolutePath(fileLinkMeta.filePath) ? fileLinkMeta.filePath : null);-- return (- <MarkdownFileLink- environmentId={environmentId}- href={fileLinkMeta.targetPath}- targetPath={fileLinkMeta.targetPath}- iconPath={fileLinkMeta.filePath}- displayPath={fileLinkMeta.displayPath}- panelPath={panelPath}- line={fileLinkMeta.line}- label={fileLinkLabel(- {- path: fileLinkMeta.filePath,- ...(fileLinkMeta.line !== undefined ? { line: fileLinkMeta.line } : {}),- ...(fileLinkMeta.column !== undefined ? { column: fileLinkMeta.column } : {}),- },- fileLinkParentSuffixByPath,- )}- copyMarkdown={copyMarkdown}- theme={resolvedTheme}- threadRef={threadRef}- {...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}- onOpenInPanel={openFileInPanel}- onOpenMedia={- threadRef && canPreviewMedia- ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)- : undefined- }- openInEditorMenuLabel={preferredEditorMenuLabel}- onReveal={- canUseShellActions && revealInFileManagerLabel !== undefined- ? () => revealMarkdownFileInFileManager(fileLinkMeta)- : undefined- }- revealLabel={revealInFileManagerLabel}- onOpenInBrowser={- threadRef &&- canOperatePreview &&- isPreviewAvailableFor(threadRef.environmentId) &&- isBrowserPreviewFile(fileLinkMeta.filePath)- ? () => openMarkdownFileInPreview(fileLinkMeta.filePath)- : undefined- }- />+ return result;+ });+ };+ const openMarkdownFileInPreview = (path: string) => {+ if (!threadRef || !canOperatePreview || preparedConnection._tag === "None") {+ return Promise.resolve(+ AsyncResult.failure<void, BrowserPreviewUnavailableError>(+ Cause.fail(+ new BrowserPreviewUnavailableError({+ message: "Environment is not connected.",+ }),+ ),+ ),);- },- [- canUseShellActions,- canOperatePreview,- environmentId,- fileLinkParentSuffixByPath,- openFileInPanel,- openInPreferredEditor,- openMarkdownFileInPreview,- openMarkdownMedia,- preferredEditorMenuLabel,- resolvedTheme,- revealInFileManagerLabel,- revealMarkdownFileInFileManager,- threadRef,- ],- );-- const componentState = useMemo(- () => ({- canOperateHost,- canOperatePreview,- cwd,- diffThemeName,- environmentId,- expandMedia,- fileLinkChip,- githubMedia,- renderContextReference,- headingLevelOffset,- imageBaseDir,- inlineCodeFileLinkMetaByText,- isStreaming,- linkTargetPreference,- markdownFileLinkMetaByHref,- onTaskListChange,- onUseArtifactTemplate,- onRunShellCommand,- openChangeRequestLink,- openDeferredMarkdownLink,- openExternalLinkInPreview,- openMarkdownMedia,- projects,- linkedThreadPullRequestFor,- resolveThreadPullRequest,- resolvedTheme,- pullRequestsEnabled,- skills,+ }+ return openFileInPreview({threadRef,- updateThreadPullRequestLink,- }),- [- canOperateHost,- canOperatePreview,- cwd,- diffThemeName,+ filePath: path,+ workspaceRoot: cwd,+ httpBaseUrl: preparedConnection.value.httpBaseUrl,+ createAssetUrl,+ openPreview,+ });+ };+ const findWorkspaceBasenameMatch = async (workspaceRelativePath: string) => {+ if (+ !cwd ||+ environmentId === null ||+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||+ !needsWorkspaceBasenameLookup(workspaceRelativePath)+ ) {+ return null;+ }+ const result = await searchProjectEntries({environmentId,- expandMedia,- fileLinkChip,- githubMedia,- renderContextReference,- headingLevelOffset,- imageBaseDir,- inlineCodeFileLinkMetaByText,- isStreaming,- linkTargetPreference,- markdownFileLinkMetaByHref,- onTaskListChange,- onUseArtifactTemplate,- onRunShellCommand,- openChangeRequestLink,- openDeferredMarkdownLink,- openExternalLinkInPreview,- openMarkdownMedia,- projects,- linkedThreadPullRequestFor,- resolveThreadPullRequest,- resolvedTheme,- pullRequestsEnabled,- skills,- threadRef,- updateThreadPullRequestLink,- ],- );+ input: {+ cwd,+ query: workspaceRelativePath,+ limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,+ kind: "file",+ },+ });+ return result._tag === "Success"+ ? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)+ : null;+ };+ const openFileInPanel = (panelPath: string, line: number | undefined) => {+ if (!threadRef) return;+ // Claimed on every open so a synchronous one supersedes a lookup already+ // in flight.+ const isLatestLookup = claimWorkspaceBasenameLookup();+ const openAt = (path: string) => useRightPanelStore.getState().openFile(threadRef, path, line);+ if (!cwd || !needsWorkspaceBasenameLookup(panelPath)) {+ openAt(panelPath);+ return;+ }+ void (async () => {+ const match = await findWorkspaceBasenameMatch(panelPath);+ if (!isLatestLookup()) return;+ openAt(match ?? panelPath);+ })();+ };+ const revealMarkdownFileInFileManager = async (fileLinkMeta: MarkdownFileLinkMeta) => {+ const workspaceRelativePath = fileLinkMeta.workspaceRelativePath;+ const match = workspaceRelativePath+ ? await findWorkspaceBasenameMatch(workspaceRelativePath)+ : null;+ const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;+ return revealFileInFileManager(filePath);+ };+ const fileLinkChip = (+ fileLinkMeta: MarkdownFileLinkMeta,+ copyMarkdown: string,+ mediaSource?: string,+ ) => {+ const mediaPath = mediaSource ?? fileLinkMeta.filePath;+ const canPreviewMedia =+ mediaMimeTypeFromExtension(+ fileLinkMeta.basename.slice(fileLinkMeta.basename.lastIndexOf(".")),+ ) !== null;+ const panelPath =+ fileLinkMeta.workspaceRelativePath ??+ (!canPreviewMedia && isAbsolutePath(fileLinkMeta.filePath) ? fileLinkMeta.filePath : null);++ return (+ <MarkdownFileLink+ environmentId={environmentId}+ href={fileLinkMeta.targetPath}+ targetPath={fileLinkMeta.targetPath}+ iconPath={fileLinkMeta.filePath}+ displayPath={fileLinkMeta.displayPath}+ panelPath={panelPath}+ line={fileLinkMeta.line}+ label={fileLinkLabel(+ {+ path: fileLinkMeta.filePath,+ ...(fileLinkMeta.line !== undefined ? { line: fileLinkMeta.line } : {}),+ ...(fileLinkMeta.column !== undefined ? { column: fileLinkMeta.column } : {}),+ },+ fileLinkParentSuffixByPath,+ )}+ copyMarkdown={copyMarkdown}+ theme={resolvedTheme}+ threadRef={threadRef}+ {...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}+ onOpenInPanel={openFileInPanel}+ onOpenMedia={+ threadRef && canPreviewMedia+ ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)+ : undefined+ }+ openInEditorMenuLabel={preferredEditorMenuLabel}+ onReveal={+ canUseShellActions && revealInFileManagerLabel !== undefined+ ? () => revealMarkdownFileInFileManager(fileLinkMeta)+ : undefined+ }+ revealLabel={revealInFileManagerLabel}+ onOpenInBrowser={+ threadRef &&+ canOperatePreview &&+ isPreviewAvailableFor(threadRef.environmentId) &&+ isBrowserPreviewFile(fileLinkMeta.filePath)+ ? () => openMarkdownFileInPreview(fileLinkMeta.filePath)+ : undefined+ }+ />+ );+ };++ const componentState = {+ canOperateHost,+ canOperatePreview,+ cwd,+ diffThemeName,+ environmentId,+ expandMedia,+ fileLinkChip,+ githubMedia,+ renderContextReference,+ headingLevelOffset,+ imageBaseDir,+ inlineCodeFileLinkMetaByText,+ isStreaming,+ linkTargetPreference,+ markdownFileLinkMetaByHref,+ onTaskListChange,+ onUseArtifactTemplate,+ onRunShellCommand,+ openChangeRequestLink,+ openDeferredMarkdownLink,+ openExternalLinkInPreview,+ openMarkdownMedia,+ projects,+ linkedThreadPullRequestFor,+ resolveThreadPullRequest,+ resolvedTheme,+ pullRequestsEnabled,+ skills,+ threadRef,+ updateThreadPullRequestLink,+ };return {componentState,handleCopy,markdownRef,markdownUrlTransform,localMediaPreview,- setLocalMediaPreview,+ closeLocalMediaPreview,};}@@ -3355,20 +3268,17 @@ function ChatMarkdown({markdownRef,markdownUrlTransform,localMediaPreview,- setLocalMediaPreview,+ closeLocalMediaPreview,} = useChatMarkdownState({ text, ...props });const incrementalParsing =props.isStreaming === true &&extraRemarkPlugins.length === 0 &&/(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text);- const remarkPlugins = useMemo(- () => [- ...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),- ...extraRemarkPlugins,- ...(incrementalParsing ? [createIncrementalMarkdownPlugin()] : []),- ],- [extraRemarkPlugins, incrementalParsing, lineBreaks],- );+ const remarkPlugins = [+ ...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),+ ...extraRemarkPlugins,+ ...(incrementalParsing ? [createIncrementalMarkdownPlugin()] : []),+ ];return (<div@@ -3398,10 +3308,7 @@ function ChatMarkdown({</ChatMarkdownTextContext></ChatMarkdownRendererContext>{localMediaPreview ? (- <ExpandedImageDialog- preview={localMediaPreview}- onClose={() => setLocalMediaPreview(null)}- />+ <ExpandedImageDialog preview={localMediaPreview} onClose={closeLocalMediaPreview} />) : null}</div>);