diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx
index 76174f9a7..50ceb0d49 100644
--- a/apps/web/src/components/ChatMarkdown.browser.tsx
+++ b/apps/web/src/components/ChatMarkdown.browser.tsx
@@ -393,7 +393,7 @@ describe("ChatMarkdown", () => {
}
});
- it("looks a bare file name up when pointed at, and dims a name the project lacks", async () => {
+ it("looks a bare file name up when pointed at, and leaves a name the project lacks as text", async () => {
const cwd = "/repo/project";
setActiveFileViewerContext({
environmentId: CHAT_MARKDOWN_ENVIRONMENT_ID,
@@ -423,7 +423,10 @@ describe("ChatMarkdown", () => {
// A transcript full of names searches for none of them until one is
// pointed at.
expect(searchEntries).not.toHaveBeenCalled();
- const found = page.getByRole("link", { name: "math.ts · L9" });
+ // A name reads as the code the agent wrote, not as a chip.
+ const found = page.getByRole("link", { name: "math.ts:9" });
+ expect(found.element().closest("code")).not.toBeNull();
+ expect(found.element().classList.contains("chat-markdown-file-link")).toBe(false);
expect(await hoverLabelOf(found.element())).toBe("project/src/lib%20old/math.ts:9");
// Placed, it opens the file the search found without searching again.
@@ -433,15 +436,52 @@ describe("ChatMarkdown", () => {
});
expect(searchEntries).toHaveBeenCalledTimes(1);
+ // A name the project lacks is only words: no link, nothing on hover.
const missing = page.getByRole("link", { name: "ghost.ts" });
await userEvent.unhover(found.element());
await userEvent.hover(missing.element());
- await expect.element(missing).toHaveAttribute("data-missing", "");
+ await expect.element(missing).not.toBeInTheDocument();
+ expect(page.getByText("ghost.ts").element().closest("code")).not.toBeNull();
+ expect(document.querySelector('[data-slot="tooltip-popup"]')).toBeNull();
+ } finally {
+ await screen.unmount();
+ }
+ });
+
+ it("opens a bare name as the file the same message gave the full path of", async () => {
+ const cwd = "/repo/project";
+ setActiveFileViewerContext({
+ environmentId: CHAT_MARKDOWN_ENVIRONMENT_ID,
+ cwd,
+ threadRef: CHAT_MARKDOWN_THREAD_REF,
+ });
+ const searchEntries = vi.fn(async () => ({ entries: [], truncated: false }));
+ installReadFileEnvironment(
+ vi.fn() as unknown as EnvironmentApi["projects"]["readFile"],
+ searchEntries as unknown as EnvironmentApi["projects"]["searchEntries"],
+ );
+ await parkPointer();
+ const screen = await renderWithAppProviders(
+ ,
+ );
+
+ try {
+ const named = page.getByRole("link", { name: "plan.md · L8" });
+ expect(await hoverLabelOf(named.element())).toBe(
+ "/Users/me/notes/plan.md:8Outside this project · opens in the file viewer",
+ );
+ await named.click();
await vi.waitFor(() => {
- expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
- "ghost.tsNot in this project · right-click to copy the name",
- );
+ const state = useFileViewerStore.getState();
+ expect(state.activePath).toBe("/Users/me/notes/plan.md");
+ expect(state.revealLine).toBe(8);
});
+ // The message said where the file is, so nothing searched the project.
+ expect(searchEntries).not.toHaveBeenCalled();
} finally {
await screen.unmount();
}
@@ -1621,7 +1661,7 @@ describe("ChatMarkdown", () => {
}
});
- it("keeps a sentence whole and dims its chips when the images it names are nowhere", async () => {
+ it("leaves image names as text when the images they name are nowhere", async () => {
// The agent named its screenshots but not the folder outside the project
// it saved them to: the search turns up only a lookalike, the root nothing.
const searchEntries = vi.fn(async () => ({
@@ -1650,22 +1690,21 @@ describe("ChatMarkdown", () => {
try {
await vi.waitFor(
() => {
- expect(document.querySelectorAll("a.chat-markdown-file-link[data-missing]")).toHaveLength(
- 3,
- );
+ expect(searchEntries).toHaveBeenCalledTimes(3);
+ expect(document.querySelectorAll(".chat-markdown a")).toHaveLength(0);
},
{ timeout: 5_000 },
);
- expect(readFile.mock.calls.map(([input]) => input.relativePath).toSorted()).toEqual([
+ // Nothing places them, so nothing fetches a picture for a guessed path,
+ // and the names stay the code the agent wrote, on the sentence's one line.
+ expect(readFile).not.toHaveBeenCalled();
+ const names = [...document.querySelectorAll(".chat-markdown code")];
+ expect(names.map((name) => name.textContent)).toEqual([
"1-left.png",
"2-right.png",
"3-bottom.png",
]);
- // With no pictures to show, the chips stay on the sentence's one line.
- const chipTops = [...document.querySelectorAll("a.chat-markdown-file-link")].map(
- (chip) => chip.getBoundingClientRect().top,
- );
- expect(new Set(chipTops).size).toBe(1);
+ expect(new Set(names.map((name) => name.getBoundingClientRect().top)).size).toBe(1);
} finally {
await screen.unmount();
}
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 1611e9ae2..7a18cfee2 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -110,6 +110,8 @@ import {
GITHUB_HTML_REHYPE_PLUGINS,
normalizeMarkdownLinkHrefKey,
pullRequestLinkLabel,
+ collectWrittenFilePaths,
+ isFileNameMention,
resolveMarkdownDocumentFileLinks,
splitMarkdownBlocks,
repairStreamingMarkdownTail,
@@ -165,6 +167,25 @@ interface ChatMarkdownProps {
className?: string | undefined;
}
+/** One block of a message, with what the whole message tells every block. */
+interface ChatMarkdownBlockProps extends ChatMarkdownProps {
+ /** Files the whole message names by full path, see {@link collectWrittenFilePaths}. */
+ writtenFilePaths: readonly string[];
+}
+
+/**
+ * {@link collectWrittenFilePaths} for a whole message, as an array that keeps
+ * its identity while the paths stay the same: a streaming message rescans on
+ * every delta, but its settled blocks re-render only when a new path appears.
+ */
+function useWrittenFilePaths(text: string, cwd: string | undefined): readonly string[] {
+ // A path never holds a line break: every source of one stops at the line.
+ const key = useMemo(() => collectWrittenFilePaths(text, cwd).join("\n"), [cwd, text]);
+ return useMemo(() => (key === "" ? NO_WRITTEN_FILE_PATHS : key.split("\n")), [key]);
+}
+
+const NO_WRITTEN_FILE_PATHS: readonly string[] = [];
+
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray> = [];
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
@@ -247,6 +268,7 @@ interface MarkdownDocumentContextValue {
readonly inlineContext: InlineMarkdownContext;
readonly markdownFileLinkMetaByHref: ReadonlyMap;
readonly inlineCodeFileLinkMetaBySpan: ReadonlyMap;
+ readonly inlineCodeSpansPlacedByDocument: ReadonlySet;
readonly fileLinkParentSuffixByPath: ReadonlyMap;
readonly fileLinkKindByPath: ReadonlyMap;
}
@@ -272,6 +294,7 @@ const MarkdownDocumentContext = createContext({
inlineContext: { skills: EMPTY_MARKDOWN_SKILLS, threadRef: null },
markdownFileLinkMetaByHref: new Map(),
inlineCodeFileLinkMetaBySpan: new Map(),
+ inlineCodeSpansPlacedByDocument: new Set(),
fileLinkParentSuffixByPath: new Map(),
fileLinkKindByPath: new Map(),
});
@@ -598,7 +621,9 @@ function placedFileLinkChip(
* may start inside a subfolder (`shots/home.png`). The text may not say the
* folder, so the picture is the file a click on the chip would open, placed by
* the same lookup. With no such file, the path as written is the one place
- * left to look, which is where the chip already points.
+ * left to look, which is where the chip already points. A bare name is a
+ * mention: it stays the code it was until the lookup finds the picture, and
+ * stays text when it doesn't.
*/
function MarkdownCitedImage({
name,
@@ -611,6 +636,27 @@ function MarkdownCitedImage({
}) {
const { cwd, environmentId } = useContext(MarkdownDocumentContext);
const place = useChatFileReferencePlace({ environmentId, cwd, reference });
+ if (chip.mention) {
+ if (place.status === "found" && cwd) {
+ return (
+
+ );
+ }
+ return (
+
+
+
+ );
+ }
if (place.status === "loading") {
return ;
}
@@ -632,7 +678,9 @@ function MarkdownCitedImage({
* the lookup a click would, so the hover label can say where the file really
* is, a file the project lacks dims before anyone clicks it, and the click or
* right-click that follows opens the found file without searching again. One
- * look places every chip that cites the same file.
+ * look places every chip that cites the same file. A bare name is a mention:
+ * the lookup decides whether it opens anything, and one the project lacks
+ * settles into plain text.
*/
function MarkdownCitedFileLink({
reference,
@@ -852,7 +900,12 @@ function MarkdownCode({
...props
}: MarkdownRendererProps<"code">) {
const documentContext = useContext(MarkdownDocumentContext);
- const { threadRef, searchHighlightQuery, inlineCodeFileLinkMetaBySpan } = documentContext;
+ const {
+ threadRef,
+ searchHighlightQuery,
+ inlineCodeFileLinkMetaBySpan,
+ inlineCodeSpansPlacedByDocument,
+ } = documentContext;
const text = typeof children === "string" ? children : null;
// Inline math (remark-math). Display math is a `pre`, which MarkdownPre draws.
if (text !== null && className && MATH_CODE_CLASS_REGEX.test(className)) {
@@ -888,19 +941,40 @@ function MarkdownCode({
? inlineCodeFileLinkMetaBySpan.get(inlineFileReference)
: undefined;
if (inlineFileReference && inlineFileLinkMeta) {
+ // A name whose full path this message already wrote out is that file. It
+ // stays a chip even for an image: the full path is where its picture goes.
+ if (inlineCodeSpansPlacedByDocument.has(inlineFileReference)) {
+ return ;
+ }
// An absolute path already says where the file is, so it opens like a
// link. Anything else opens through the workspace lookup, since a path
// may start inside a subfolder, and a bare name's hover shows the name as
// written until a look places it: before that, its folder is only a guess.
const isAbsolute = isAbsoluteInlineFilePath(inlineFileReference);
const searchReference = isAbsolute ? null : parseChatFileReference(inlineFileReference);
- const isBareName = searchReference !== null && !searchReference.path.includes("/");
+ // A bare name is a mention: the agent said what the file is called, not
+ // where it is, so it reads as the code it wrote until a lookup finds it.
+ const isMention = isFileNameMention(inlineFileReference, inlineCodeSpansPlacedByDocument);
const chip: MarkdownFileLinkProps = {
...fileLinkChip(inlineFileLinkMeta, documentContext),
- ...(isBareName ? { displayPath: inlineFileReference } : {}),
+ ...(isMention
+ ? { displayPath: inlineFileReference, label: inlineFileReference, mention: true }
+ : {}),
...(isAbsolute ? {} : { chatReference: inlineFileReference }),
};
if (!isImageFilePath(inlineFileLinkMeta.filePath)) {
+ if (isMention) {
+ return (
+
+
+
+ );
+ }
return searchReference !== null ? (
{label}>;
+ }
+ // A mention is placed once its reference is dropped (placedFileLinkChip). Until
+ // then its hover has nothing to say beyond the name already on screen, so the
+ // label opens with the pointer but draws only once the lookup answers.
+ const isPlacedMention = mention === true && chatReference === undefined;
+ const hasHoverLabel = !mention || isPlacedMention || isAmbiguous === true;
return (
-
- {label}
+ {mention ? (
+ label
+ ) : (
+ <>
+
+ {label}
+ >
+ )}
}
/>
-
-
- {displayPath}
-
-
-
+ {hasHoverLabel ? (
+
+
+ {displayPath}
+
+
+
+ ) : null}
);
}, areMarkdownFileLinkPropsEqual);
@@ -1484,7 +1589,8 @@ function areMarkdownFileLinkPropsEqual(
previous.chatReference === next.chatReference &&
previous.isMissing === next.isMissing &&
previous.isAmbiguous === next.isAmbiguous &&
- previous.isInProjectFolder === next.isInProjectFolder
+ previous.isInProjectFolder === next.isInProjectFolder &&
+ previous.mention === next.mention
);
}
@@ -1519,7 +1625,8 @@ function ChatMarkdownDocument({
skills = EMPTY_MARKDOWN_SKILLS,
searchHighlightQuery,
html,
-}: ChatMarkdownProps) {
+ writtenFilePaths,
+}: ChatMarkdownBlockProps) {
const { resolvedTheme } = useTheme();
// Null unless both halves of the identity are here: a transcript rendered
// outside a thread (a plan preview, a subagent excerpt without context) has
@@ -1537,11 +1644,12 @@ function ChatMarkdownDocument({
const {
markdownFileLinkMetaByHref,
inlineCodeFileLinkMetaBySpan,
+ inlineCodeSpansPlacedByDocument,
fileLinkMetaByKey,
fileLinkParentSuffixByPath,
} = useMemo(
- () => resolveMarkdownDocumentFileLinks(text, cwd, { inlineCodeChips }),
- [cwd, inlineCodeChips, text],
+ () => resolveMarkdownDocumentFileLinks(text, cwd, { inlineCodeChips, writtenFilePaths }),
+ [cwd, inlineCodeChips, text, writtenFilePaths],
);
const fileLinkKindByPath = useMarkdownFileLinkKinds(fileLinkMetaByKey, environmentId, cwd);
const streamingText = isStreaming ? text : null;
@@ -1577,6 +1685,7 @@ function ChatMarkdownDocument({
inlineContext,
markdownFileLinkMetaByHref,
inlineCodeFileLinkMetaBySpan,
+ inlineCodeSpansPlacedByDocument,
fileLinkParentSuffixByPath,
fileLinkKindByPath,
}),
@@ -1587,6 +1696,7 @@ function ChatMarkdownDocument({
fileLinkKindByPath,
fileLinkParentSuffixByPath,
inlineCodeFileLinkMetaBySpan,
+ inlineCodeSpansPlacedByDocument,
inlineContext,
isStreaming,
markdownFileLinkMetaByHref,
@@ -1627,7 +1737,8 @@ const MarkdownBlock = memo(function MarkdownBlock({
skills = EMPTY_MARKDOWN_SKILLS,
searchHighlightQuery,
html,
-}: ChatMarkdownProps) {
+ writtenFilePaths,
+}: ChatMarkdownBlockProps) {
// Lets React drop intermediate parses when deltas outpace rendering
// (older CPUs) instead of parsing every 50ms server flush. A settled block's
// text never changes, so deferring it costs nothing.
@@ -1648,6 +1759,7 @@ const MarkdownBlock = memo(function MarkdownBlock({
skills={skills}
searchHighlightQuery={searchHighlightQuery}
html={html}
+ writtenFilePaths={writtenFilePaths}
/>
);
});
@@ -1661,7 +1773,8 @@ function ChatMarkdownBody({
skills = EMPTY_MARKDOWN_SKILLS,
searchHighlightQuery,
html,
-}: ChatMarkdownProps) {
+ writtenFilePaths,
+}: ChatMarkdownBlockProps) {
// Blocks are the unit of rendering whether or not the message is streaming:
// a streaming message re-parses only its growing tail, and when it stops
// streaming nothing changes but the tail's `isStreaming` prop. Index keys are
@@ -1685,6 +1798,7 @@ function ChatMarkdownBody({
skills={skills}
searchHighlightQuery={searchHighlightQuery}
html={html}
+ writtenFilePaths={writtenFilePaths}
/>
))}
>
@@ -1714,6 +1828,7 @@ function ChatMarkdown({
const segments = canRenderVisualizations
? parseCodexInlineVisualizations(text, { isStreaming })
: [{ type: "markdown" as const, key: "markdown:0", text }];
+ const writtenFilePaths = useWrittenFilePaths(text, cwd);
return (
);
})}
diff --git a/apps/web/src/components/chat/chatFind/chatFindText.ts b/apps/web/src/components/chat/chatFind/chatFindText.ts
index c9db1a93f..f6a0f6ed9 100644
--- a/apps/web/src/components/chat/chatFind/chatFindText.ts
+++ b/apps/web/src/components/chat/chatFind/chatFindText.ts
@@ -25,7 +25,9 @@ import {
buildFileLinkLabel,
CHAT_MARKDOWN_REMARK_PLUGINS,
chatMarkdownUrlTransform,
+ collectWrittenFilePaths,
GITHUB_HTML_REHYPE_PLUGINS,
+ isFileNameMention,
type MarkdownDocumentFileLinks,
normalizeMarkdownLinkHrefKey,
placeLinkLabel,
@@ -320,9 +322,13 @@ function walkInlineCode(element: HastElement, context: WalkContext) {
walkChildren(element.children, { ...context, inlinePass: false });
return;
}
- const meta = document.fileLinks.inlineCodeFileLinkMetaBySpan.get(only.value.trim());
- if (meta) document.collector.add(context.block, fileChipLabel(meta, document), "chip");
- else document.collector.add(context.block, only.value);
+ const span = only.value.trim();
+ const meta = document.fileLinks.inlineCodeFileLinkMetaBySpan.get(span);
+ // A bare file name draws as the code it is (ChatMarkdown's mention), unless
+ // a lookup finds a picture for it, which no text pass can know.
+ if (meta && !isFileNameMention(span, document.fileLinks.inlineCodeSpansPlacedByDocument)) {
+ document.collector.add(context.block, fileChipLabel(meta, document), "chip");
+ } else document.collector.add(context.block, only.value);
}
function walkElement(element: HastElement, context: WalkContext) {
@@ -374,6 +380,7 @@ function collectMarkdownDocument(
readonly html: "github" | undefined;
readonly collector: BlockCollector;
readonly root: object;
+ readonly writtenFilePaths: readonly string[];
},
) {
// MarkdownBlock: math normalized, and a streaming tail drawn with its open
@@ -386,7 +393,10 @@ function collectMarkdownDocument(
cwd: options.cwd,
skills: options.skills,
bareImagePaths: !options.isStreaming,
- fileLinks: resolveMarkdownDocumentFileLinks(rendered, options.cwd, { inlineCodeChips: true }),
+ fileLinks: resolveMarkdownDocumentFileLinks(rendered, options.cwd, {
+ inlineCodeChips: true,
+ writtenFilePaths: options.writtenFilePaths,
+ }),
collector: options.collector,
};
walkChildren(tree.children, { block: options.root, inlinePass: false, document });
@@ -403,6 +413,7 @@ export function markdownFirstLine(input: {
readonly cwd: string | undefined;
readonly skills: ReadonlyArray;
}): string {
+ const writtenFilePaths = collectWrittenFilePaths(input.text, input.cwd);
for (const document of splitMarkdownBlocks(input.text)) {
const collector = new BlockCollector();
collectMarkdownDocument(document, {
@@ -412,6 +423,7 @@ export function markdownFirstLine(input: {
html: undefined,
collector,
root: {},
+ writtenFilePaths,
});
const [first] = collector.readable();
const line = first
@@ -430,6 +442,8 @@ export function markdownFirstLine(input: {
export function findableMarkdownBlocks(input: FindableMarkdownInput): string[] {
const collector = new BlockCollector();
const root = {};
+ // ChatMarkdown: a short name is placed by a path written anywhere in the message.
+ const writtenFilePaths = collectWrittenFilePaths(input.text, input.cwd);
const segments = input.visualizations
? parseCodexInlineVisualizations(input.text, { isStreaming: input.isStreaming })
: [{ type: "markdown" as const, key: "markdown:0", text: input.text }];
@@ -445,6 +459,7 @@ export function findableMarkdownBlocks(input: FindableMarkdownInput): string[] {
html: input.html,
collector,
root,
+ writtenFilePaths,
});
});
});
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 92deca584..1b0f9228c 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -1185,13 +1185,26 @@ label:has(> select#reasoning-effort) select {
text-decoration: none;
}
-/* A place chip (PlaceLink) likewise, and its page glyph takes the chip's text
- color rather than the link blue: the chip, not the color, says it opens. */
+/* A place chip (PlaceLink) likewise; it wears the file chip's link blue. */
.chat-markdown a.chat-markdown-place-link {
- color: var(--foreground);
text-decoration: none;
}
+/* A file the agent only named (ChatMarkdown's mention) reads as the code it
+ wrote. Once a lookup finds the file, hover alone says it opens. */
+.chat-markdown a[data-file-mention],
+.chat-markdown a[data-file-mention]:hover {
+ color: inherit;
+ text-decoration: none;
+ opacity: 1;
+}
+
+.chat-markdown a[data-file-mention][data-placed]:hover {
+ color: var(--foreground);
+ text-decoration: underline dotted;
+ text-underline-offset: 2px;
+}
+
.chat-markdown blockquote {
border-left: 2px solid var(--border);
padding-left: 0.8rem;
@@ -1296,15 +1309,19 @@ label:has(> select#reasoning-effort) select {
clear: right;
}
+/* A file or place in a reply is a link, so it wears link blue: a blue tint
+ behind blue text. That keeps it apart from inline code (a grey fill) and from
+ buttons (a solid face with an edge). The edge stays, transparent, so the
+ dashed states below keep the chip's size. */
.chat-markdown-file-link {
display: inline-flex;
align-items: center;
gap: 0.28rem;
- border: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
+ border: 1px solid transparent;
border-radius: var(--radius-md);
- background: color-mix(in srgb, var(--muted) 88%, var(--surface-solid));
+ background: color-mix(in srgb, var(--info-foreground) 14%, transparent);
padding: 0.08rem 0.34rem;
- color: var(--foreground);
+ color: var(--info-foreground);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.75rem;
line-height: 1.15;
@@ -1318,9 +1335,13 @@ label:has(> select#reasoning-effort) select {
.chat-markdown-file-link:hover {
opacity: 1;
- color: var(--foreground);
- border-color: color-mix(in srgb, var(--border) 65%, var(--foreground));
- background: color-mix(in srgb, var(--muted) 72%, var(--surface-solid));
+ color: var(--info-foreground);
+ background: color-mix(in srgb, var(--info-foreground) 22%, transparent);
+}
+
+/* Beats the underline every link in a reply gets: the tint already says link. */
+.chat-markdown a.chat-markdown-file-link {
+ text-decoration: none;
}
.chat-markdown-file-link:focus-visible {
@@ -1333,15 +1354,20 @@ label:has(> select#reasoning-effort) select {
}
.chat-markdown-file-link-label {
- color: color-mix(in srgb, var(--foreground) 88%, transparent);
+ color: inherit;
line-height: 1.1;
}
/* A file that was looked for and is not there. It still names what the agent
- meant, but as an outline, so it does not read as something that will open.
- Hover still shifts it to the normal chip colors. */
+ meant, but as a grey outline without the link blue, so it does not read as
+ something that will open. Hover still shifts it to the normal chip colors. */
.chat-markdown-file-link[data-missing] {
border-style: dashed;
+ border-color: color-mix(in srgb, var(--border) 92%, transparent);
+}
+
+.chat-markdown-file-link[data-missing]:hover {
+ border-color: transparent;
}
.chat-markdown-file-link[data-missing]:not(:hover) {
diff --git a/apps/web/src/lib/chatMarkdownDocument.test.ts b/apps/web/src/lib/chatMarkdownDocument.test.ts
index aa8cd99d6..a96c6e667 100644
--- a/apps/web/src/lib/chatMarkdownDocument.test.ts
+++ b/apps/web/src/lib/chatMarkdownDocument.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
-import { repairStreamingMarkdownTail, splitMarkdownBlocks } from "./chatMarkdownDocument";
+import {
+ collectWrittenFilePaths,
+ repairStreamingMarkdownTail,
+ splitMarkdownBlocks,
+} from "./chatMarkdownDocument";
import { fencedBlockIsClosed } from "./markdownFences";
import {
parseCodexInlineVisualizations,
@@ -103,6 +107,24 @@ describe("fencedBlockIsClosed", () => {
});
});
+describe("collectWrittenFilePaths", () => {
+ it("takes paths the message cites, not paths in commands or examples", () => {
+ const text = [
+ "Saved [the plan](C:\\Users\\me\\notes\\plan.md) and `/Users/me/shots/home.png`.",
+ "The old one is at /tmp/shots/old.png.",
+ "Then run `rm /tmp/shots/stale.png` to clean up.",
+ "```md",
+ "[example](/tmp/example/plan.md)",
+ "```",
+ ].join("\n");
+ expect(collectWrittenFilePaths(text, "/repo/project")).toEqual([
+ "/Users/me/shots/home.png",
+ "/tmp/shots/old.png",
+ "C:\\Users\\me\\notes\\plan.md",
+ ]);
+ });
+});
+
describe("repairStreamingMarkdownTail", () => {
it("closes an emphasis marker still waiting for its partner", () => {
expect(repairStreamingMarkdownTail("This is **bold so f")).toBe("This is **bold so f**");
diff --git a/apps/web/src/lib/chatMarkdownDocument.ts b/apps/web/src/lib/chatMarkdownDocument.ts
index 0f513abdd..cf49334de 100644
--- a/apps/web/src/lib/chatMarkdownDocument.ts
+++ b/apps/web/src/lib/chatMarkdownDocument.ts
@@ -16,6 +16,8 @@ import { type PlaceId, placePathLabel } from "@threadlines/shared/appPlaces";
import { isPlaceLinkHref } from "../appPlaceLinks";
import { parseChatFileReference } from "../fileViewerStore";
import {
+ fileLinkMetaForPath,
+ findBareImagePaths,
isAbsoluteInlineFilePath,
localhostUrlFromText,
type MarkdownFileLinkMeta,
@@ -350,6 +352,98 @@ export function chatMarkdownUrlTransform(href: string, cwd: string | undefined):
}
const EMPTY_FILE_LINK_META_MAP: ReadonlyMap = new Map();
+const EMPTY_SPAN_SET: ReadonlySet = new Set();
+const EMPTY_PATHS: readonly string[] = [];
+
+/**
+ * Every file a message names by a written-out path: a link with a folder in
+ * it, an inline code span that is an absolute path, an image path typed in
+ * prose. Fenced blocks are skipped, and so is a path inside a longer code span:
+ * a path in a command is not a citation. Read over the whole message, since
+ * chat draws each block on its own and a name often sits blocks below the path
+ * that placed it. Sorted, so equal answers compare equal.
+ */
+export function collectWrittenFilePaths(text: string, cwd: string | undefined): readonly string[] {
+ const paths = new Set();
+ const add = (written: string) => {
+ const meta = resolveMarkdownFileLinkMeta(written, cwd);
+ if (meta) paths.add(meta.filePath);
+ };
+ const fence = createFenceTracker();
+ for (const line of text.split("\n")) {
+ if (fence.feed(line) !== "text") continue;
+ for (const href of extractMarkdownLinkHrefs(line)) {
+ if (href.includes("/") || href.includes("\\")) add(normalizeMarkdownLinkHrefKey(href));
+ }
+ for (const match of line.matchAll(INLINE_CODE_RUN_PATTERN)) {
+ const span = match[2]?.trim();
+ if (span && isAbsoluteInlineFilePath(span)) add(span);
+ }
+ const prose = line.replace(INLINE_CODE_RUN_PATTERN, (run) => " ".repeat(run.length));
+ for (const match of findBareImagePaths(prose)) add(match.text);
+ }
+ return paths.size === 0 ? EMPTY_PATHS : [...paths].toSorted();
+}
+
+/**
+ * Agents often write a file's full path once and then call it by name. A bare
+ * name in inline code (`home.png`, `math.ts:12`) that exactly one written-out
+ * path ends in is that file, at the line the name cites. Searching the
+ * workspace for the name instead would miss any file outside the project. A
+ * name two written paths end in is left to the search, and so is a partial
+ * path (`Model/Form.php`): agents are told to cite project files that way, so
+ * it means the project's copy even when another copy's full path is nearby.
+ */
+function placeShortReferencesByWrittenPaths(
+ inlineMetaBySpan: ReadonlyMap,
+ writtenFilePaths: readonly string[],
+ cwd: string | undefined,
+): {
+ readonly metaBySpan: ReadonlyMap;
+ readonly placedSpans: ReadonlySet;
+} {
+ if (writtenFilePaths.length === 0) {
+ return { metaBySpan: inlineMetaBySpan, placedSpans: EMPTY_SPAN_SET };
+ }
+ const written = writtenFilePaths.map((filePath) => ({
+ filePath,
+ slashed: filePath.replaceAll("\\", "/"),
+ }));
+ let metaBySpan: Map | null = null;
+ const placedSpans = new Set();
+ for (const span of inlineMetaBySpan.keys()) {
+ if (isAbsoluteInlineFilePath(span)) continue;
+ const reference = parseChatFileReference(span);
+ if (!reference || reference.path.includes("/")) continue;
+ const suffix = `/${reference.path}`;
+ const matches = written.filter((path) => path.slashed.endsWith(suffix));
+ if (matches.length !== 1) continue;
+ const { filePath } = matches[0]!;
+ metaBySpan ??= new Map(inlineMetaBySpan);
+ metaBySpan.set(
+ span,
+ fileLinkMetaForPath(
+ reference.line !== undefined ? `${filePath}:${reference.line}` : filePath,
+ cwd,
+ ),
+ );
+ placedSpans.add(span);
+ }
+ return metaBySpan === null
+ ? { metaBySpan: inlineMetaBySpan, placedSpans: EMPTY_SPAN_SET }
+ : { metaBySpan, placedSpans };
+}
+
+/**
+ * Whether inline code names a file by its name alone (`math.ts:12`): no folder,
+ * and no full path for it anywhere in the message. Such a name is drawn as the
+ * code the agent wrote, not as a chip, since nothing says where the file is.
+ */
+export function isFileNameMention(span: string, placedByDocument: ReadonlySet): boolean {
+ if (placedByDocument.has(span) || isAbsoluteInlineFilePath(span)) return false;
+ const reference = parseChatFileReference(span);
+ return reference !== null && !reference.path.includes("/");
+}
/** Every file reference one document turns into a chip, and how each is labelled. */
export interface MarkdownDocumentFileLinks {
@@ -357,6 +451,13 @@ export interface MarkdownDocumentFileLinks {
readonly markdownFileLinkMetaByHref: ReadonlyMap;
/** Inline-code file references, keyed by the span as written. */
readonly inlineCodeFileLinkMetaBySpan: ReadonlyMap;
+ /**
+ * Bare file names in inline code (`home.png`, `math.ts:12`) the same
+ * message already placed by writing the file's full path. Their entry in
+ * {@link inlineCodeFileLinkMetaBySpan} is that file, so they open it directly
+ * instead of searching the workspace for the name.
+ */
+ readonly inlineCodeSpansPlacedByDocument: ReadonlySet;
/** Both of the above in one map (links win), for the file-kind lookup. */
readonly fileLinkMetaByKey: ReadonlyMap;
/** The parent-folder suffix that tells a file from its namesakes. */
@@ -368,11 +469,17 @@ export interface MarkdownDocumentFileLinks {
* references share it, so the same file cited both ways gets the same
* parent-suffix disambiguation. `inlineCodeChips` off keeps inline code as
* written (a highlighted search hit must not shorten into a chip).
+ * `writtenFilePaths` is {@link collectWrittenFilePaths} of the whole message
+ * this document is a block of; without it, only this document's own paths
+ * place its short references.
*/
export function resolveMarkdownDocumentFileLinks(
text: string,
cwd: string | undefined,
- options: { readonly inlineCodeChips: boolean },
+ options: {
+ readonly inlineCodeChips: boolean;
+ readonly writtenFilePaths?: readonly string[] | undefined;
+ },
): MarkdownDocumentFileLinks {
const markdownFileLinkMetaByHref = new Map();
for (const href of extractMarkdownLinkHrefs(text)) {
@@ -383,9 +490,14 @@ export function resolveMarkdownDocumentFileLinks(
markdownFileLinkMetaByHref.set(normalizedHref, meta);
}
}
- const inlineCodeFileLinkMetaBySpan = options.inlineCodeChips
- ? buildInlineCodeFileLinkMeta(text, cwd)
- : EMPTY_FILE_LINK_META_MAP;
+ const { metaBySpan: inlineCodeFileLinkMetaBySpan, placedSpans: inlineCodeSpansPlacedByDocument } =
+ options.inlineCodeChips
+ ? placeShortReferencesByWrittenPaths(
+ buildInlineCodeFileLinkMeta(text, cwd),
+ options.writtenFilePaths ?? collectWrittenFilePaths(text, cwd),
+ cwd,
+ )
+ : { metaBySpan: EMPTY_FILE_LINK_META_MAP, placedSpans: EMPTY_SPAN_SET };
let fileLinkMetaByKey: ReadonlyMap = markdownFileLinkMetaByHref;
if (inlineCodeFileLinkMetaBySpan.size > 0) {
const merged = new Map(markdownFileLinkMetaByHref);
@@ -400,6 +512,7 @@ export function resolveMarkdownDocumentFileLinks(
return {
markdownFileLinkMetaByHref,
inlineCodeFileLinkMetaBySpan,
+ inlineCodeSpansPlacedByDocument,
fileLinkMetaByKey,
fileLinkParentSuffixByPath,
};