diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 979d1858cafc1..b9eef6ff3d412 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -14,7 +14,11 @@ import { inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; -import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; +import { + isHostPath, + resolveWorkspaceFilePath, + workspaceRelativeFilePath, +} from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { AuthFilesystemReadScope, @@ -264,6 +268,9 @@ interface ChatMarkdownProps { /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ sourceControlMedia?: boolean | undefined; + /** Text written on another machine (a pull request) names paths there: only files inside `cwd` + become file links or load as media, and other paths render as their label or code. */ + workspaceFileLinksOnly?: boolean | undefined; /** The change request's repository, when it can differ from the checkout at `cwd`. */ sourceControlMediaRepository?: string | undefined; headingLevelOffset?: number | undefined; @@ -547,20 +554,31 @@ function fileLinkSourcesKey( return JSON.stringify([[...hrefs], [...spans]]); } +function scopeFileLinkMeta(meta: MarkdownFileLinkMeta | null, workspaceFileLinksOnly: boolean) { + return meta && (!workspaceFileLinksOnly || meta.workspaceRelativePath !== null) ? meta : null; +} + function resolveFileLinkSources( key: string, cwd: string | undefined, imageBaseDir: string | undefined, + workspaceFileLinksOnly: boolean, ) { const [hrefs, spans] = JSON.parse(key) as [string[], string[]]; const markdownFileLinkMetaByHref = new Map(); for (const href of hrefs) { - const meta = resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd); + const meta = scopeFileLinkMeta( + resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd), + workspaceFileLinksOnly, + ); if (meta) markdownFileLinkMetaByHref.set(href, meta); } const inlineCodeFileLinkMetaByText = new Map(); for (const span of spans) { - const meta = resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd); + const meta = scopeFileLinkMeta( + resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), + workspaceFileLinksOnly, + ); if (meta) inlineCodeFileLinkMetaByText.set(span, meta); } const fileLinkParentSuffixByPath = buildFileLinkParentSuffixByPath([ @@ -590,6 +608,7 @@ function useChatMarkdownState( renderContextReference, headingLevelOffset = 0, sourceControlMedia = false, + workspaceFileLinksOnly = false, sourceControlMediaRepository, }: ChatMarkdownProps, streamingBlocks: ReadonlyArray | null, @@ -793,7 +812,7 @@ function useChatMarkdownState( // A template literal marks the key as a string, so the compiler memoizes the maps on its value. const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = - resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); + resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir, workspaceFileLinksOnly); const resolveThreadPullRequest = ( href: string, ): (ThreadPullRequestKey & { readonly url: string }) | null => { @@ -1075,6 +1094,7 @@ function useChatMarkdownState( fileLinkChip, sourceControlMedia, sourceControlMediaRepository, + workspaceFileLinksOnly, renderContextReference, headingLevelOffset, imageBaseDir, @@ -1275,6 +1295,7 @@ const CHAT_MARKDOWN_COMPONENTS = { updateThreadPullRequestLink, fileLinkChip, renderContextReference, + workspaceFileLinksOnly, } = use(ChatMarkdownRendererContext); const text = use(ChatMarkdownTextContext); const citation = href ? parseAssistantCitationHref(href) : null; @@ -1315,6 +1336,10 @@ const CHAT_MARKDOWN_COMPONENTS = { ? (markdownFileLinkMetaByHref.get(normalizedHref) ?? resolveMarkdownFileLinkMeta(normalizedHref, cwd, imageBaseDir ?? cwd)) : null; + // As a web link the path would still open on this machine, so it keeps only its label. + if (fileLinkMeta && !scopeFileLinkMeta(fileLinkMeta, workspaceFileLinksOnly)) { + return {children}; + } if (!fileLinkMeta) { const faviconHost = resolveExternalWebLinkHost(href); const hasText = hastHasText(node); @@ -1576,14 +1601,21 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( - ChatMarkdownRendererContext, - ); + const { + cwd, + imageBaseDir, + inlineCodeFileLinkMetaByText, + fileLinkChip, + workspaceFileLinksOnly, + } = use(ChatMarkdownRendererContext); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? - resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd); + scopeFileLinkMeta( + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd), + workspaceFileLinksOnly, + ); if (fileLinkMeta) { return fileLinkChip( fileLinkMeta, @@ -1616,6 +1648,7 @@ const CHAT_MARKDOWN_COMPONENTS = { renderContextReference, fileLinkChip, resolvedTheme, + workspaceFileLinksOnly, } = use(ChatMarkdownRendererContext); const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia; const contextReference = typeof src === "string" ? parseComposerContextHref(src) : null; @@ -1636,7 +1669,13 @@ const CHAT_MARKDOWN_COMPONENTS = { const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle); const { className, style: _style, width, height, ...imageProps } = props; const authoredSizeStyle = authoredImageSizeStyle(width, height); - const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd); + const classifiedSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd); + const imageSource = + workspaceFileLinksOnly && + classifiedSource._tag === "WorkspaceFile" && + workspaceRelativeFilePath(classifiedSource.path, cwd) === null + ? ({ _tag: "Blocked" } as const) + : classifiedSource; const mediaKind = mediaKindFromPath(classifiedSrc); if (mediaKind === "audio") { const filePath = imageSource._tag === "WorkspaceFile" ? imageSource.path : null; @@ -1944,6 +1983,7 @@ function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslan inlineCodeFileLinkMetaByText, onTaskListChange, skills, + workspaceFileLinksOnly, } = state; const options: MarkdownIslandOptions = { components: CHAT_MARKDOWN_COMPONENTS, @@ -1967,7 +2007,10 @@ function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslan const codeText = hastPlainTextDeep(node); return ( (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? - resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + scopeFileLinkMeta( + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd), + workspaceFileLinksOnly, + )) != null ); } case "p": diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx index f1cd6b6ba6708..4f51505e2348b 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx @@ -1,5 +1,11 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import { type AssetResource, EnvironmentId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + type AssetResource, + EnvironmentId, + type ScopedThreadRef, + ThreadId, +} from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { render } from "../../../test/render"; @@ -20,13 +26,23 @@ function setup() { async function renderBody( host: string, - options: { lineBreaks?: boolean; repository?: string; text?: string } = {}, + options: { + lineBreaks?: boolean; + repository?: string; + text?: string; + threadRef?: ScopedThreadRef; + } = {}, ) { - const { repository = null, text = "first line\nsecond line", ...props } = options; + const { + repository = null, + text = "first line\nsecond line", + threadRef = null, + ...props + } = options; const context = { extensions: {}, lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false, - threadRef: null, + threadRef, repository, }; return render( @@ -62,6 +78,28 @@ it("lets text the host did not write opt out of the host's breaks", async () => expect(screen.container.querySelectorAll("p br")).toHaveLength(0); }); +it("links and loads only paths inside the checkout", async () => { + setup(); + await using screen = await renderBody("github", { + threadRef: scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread")), + text: [ + "See `/etc/hosts`, `../outside.ts`, [key](~/.ssh/id_rsa), [up](file:///etc/hosts),", + "![rc](/home/alice/.bashrc), ![leak](/home/alice/private.png), ![ok](docs/shot.png)", + "and `packages/x/y.ts`.", + ].join(" "), + }); + await expect.element(screen.getByRole("link", { name: "y.ts" })).toBeInTheDocument(); + const links = [...screen.container.querySelectorAll("a")]; + expect(links.map((link) => link.getAttribute("href"))).toEqual(["/repo/packages/x/y.ts"]); + expect([...screen.container.querySelectorAll("code")].map((c) => c.textContent)).toEqual([ + "/etc/hosts", + "../outside.ts", + ]); + expect(requested.map((resource) => resource?._tag === "media-file" && resource.path)).toEqual([ + "/repo/docs/shot.png", + ]); +}); + it("loads the body's host media in the pull request's repository, not the checkout's", async () => { setup(); const image = "https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422"; diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx index 82012eae8f0a7..5b01115a20978 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx @@ -133,6 +133,7 @@ function PullRequestBodySegmentView({ lineBreaks={lineBreaks} sourceControlMedia sourceControlMediaRepository={repository} + workspaceFileLinksOnly onTaskListChange={ onTaskListChange && segment.kind === "markdown" ? ({ markerOffset, checked }) =>