Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<string, MarkdownFileLinkMeta>();
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<string, MarkdownFileLinkMeta>();
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([
Expand Down Expand Up @@ -590,6 +608,7 @@ function useChatMarkdownState(
renderContextReference,
headingLevelOffset = 0,
sourceControlMedia = false,
workspaceFileLinksOnly = false,
sourceControlMediaRepository,
}: ChatMarkdownProps,
streamingBlocks: ReadonlyArray<string> | null,
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -1075,6 +1094,7 @@ function useChatMarkdownState(
fileLinkChip,
sourceControlMedia,
sourceControlMediaRepository,
workspaceFileLinksOnly,
renderContextReference,
headingLevelOffset,
imageBaseDir,
Expand Down Expand Up @@ -1275,6 +1295,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
updateThreadPullRequestLink,
fileLinkChip,
renderContextReference,
workspaceFileLinksOnly,
} = use(ChatMarkdownRendererContext);
const text = use(ChatMarkdownTextContext);
const citation = href ? parseAssistantCitationHref(href) : null;
Expand Down Expand Up @@ -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 <span>{children}</span>;
}
if (!fileLinkMeta) {
const faviconHost = resolveExternalWebLinkHost(href);
const hasText = hastHasText(node);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -1944,6 +1983,7 @@ function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslan
inlineCodeFileLinkMetaByText,
onTaskListChange,
skills,
workspaceFileLinksOnly,
} = state;
const options: MarkdownIslandOptions = {
components: CHAT_MARKDOWN_COMPONENTS,
Expand All @@ -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":
Expand Down
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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(
Expand Down Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ function PullRequestBodySegmentView({
lineBreaks={lineBreaks}
sourceControlMedia
sourceControlMediaRepository={repository}
workspaceFileLinksOnly
onTaskListChange={
onTaskListChange && segment.kind === "markdown"
? ({ markerOffset, checked }) =>
Expand Down
Loading