Skip to content

Commit 149e2b4

Browse files
fix(web): resolve repository file chips without redirecting explicit paths
1 parent cd0f4f6 commit 149e2b4

6 files changed

Lines changed: 225 additions & 95 deletions

File tree

‎apps/web/src/components/ChatMarkdown.browser.test.tsx‎

Lines changed: 175 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,28 @@
1-
import { EnvironmentId } from "@t3tools/contracts";
1+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
22
import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
33
import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4+
import { AsyncResult } from "effect/reactivity";
45
import { act, type ReactElement } from "react";
56
import { createRoot, type Root } from "react-dom/client";
67
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
78

9+
import { filesystemEnvironment } from "../state/filesystem";
10+
import { useRightPanelStore } from "../rightPanelStore";
811
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
912
import { MarkdownFindContext } from "./chat/markdownFindContext";
1013
import { useThreadFindHighlights } from "./chat/threadFindHighlights";
1114
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
1215

16+
const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
17+
workspaceSearch: vi.fn(),
18+
filesystemMetadata: vi.fn(),
19+
}));
20+
vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
21+
...(await original()),
22+
useAtomQueryRunner: ((family: unknown) =>
23+
family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,
24+
}));
25+
1326
// Atoms derived from the server config run in the real registry over a missing config.
1427
vi.mock(import("../state/server"), async (original) => {
1528
const actual = await original();
@@ -47,6 +60,8 @@ import ChatMarkdown from "./ChatMarkdown";
4760
const roots: Root[] = [];
4861

4962
beforeEach(() => {
63+
workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
64+
filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
5065
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
5166
});
5267

@@ -400,6 +415,165 @@ describe("ChatMarkdown skill chips", () => {
400415
});
401416
});
402417

418+
describe("ChatMarkdown workspace file opens", () => {
419+
const threadRef = {
420+
environmentId: EnvironmentId.make("workspace"),
421+
threadId: ThreadId.make("thread"),
422+
};
423+
424+
it.each([
425+
{
426+
cwd: "/school/courses/physics",
427+
path: "courses/physics/notes/a.md",
428+
indexedPath: "notes/a.md",
429+
},
430+
{
431+
cwd: "C:/school/courses/Physics",
432+
path: "courses/physics/notes/a.md",
433+
indexedPath: "Notes/A.md",
434+
},
435+
])(
436+
"opens a repo-relative chip at its indexed path in $cwd",
437+
async ({ cwd, path, indexedPath }) => {
438+
workspaceSearch.mockResolvedValue(
439+
AsyncResult.success({
440+
entries: [
441+
{ path: indexedPath, kind: "file" },
442+
{ path, kind: "file" },
443+
],
444+
truncated: false,
445+
}),
446+
);
447+
const openFile = vi
448+
.spyOn(useRightPanelStore.getState(), "openFile")
449+
.mockImplementation(() => {});
450+
const container = await renderText(`[Notes](${path}:7)`, { cwd, threadRef });
451+
452+
await act(async () => container.querySelector("a")!.click());
453+
454+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, indexedPath, 7);
455+
},
456+
);
457+
458+
it("prefers an existing literal nested file over the stripped Windows match", async () => {
459+
filesystemMetadata.mockResolvedValue(
460+
AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
461+
);
462+
workspaceSearch.mockResolvedValue(
463+
AsyncResult.success({
464+
entries: [
465+
{ path: "Notes/A.md", kind: "file" },
466+
{ path: "Physics/Notes/A.md", kind: "file" },
467+
],
468+
truncated: false,
469+
}),
470+
);
471+
const openFile = vi
472+
.spyOn(useRightPanelStore.getState(), "openFile")
473+
.mockImplementation(() => {});
474+
const container = await renderText("[Notes](physics/notes/a.md)", {
475+
cwd: "C:/school/Physics",
476+
threadRef,
477+
});
478+
479+
await act(async () => container.querySelector("a")!.click());
480+
481+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", undefined);
482+
});
483+
484+
it("keeps a literal file omitted by a truncated search", async () => {
485+
workspaceSearch.mockResolvedValue(
486+
AsyncResult.success({
487+
entries: [{ path: "notes/a.md", kind: "file" }],
488+
truncated: true,
489+
}),
490+
);
491+
filesystemMetadata.mockResolvedValue(
492+
AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
493+
);
494+
const openFile = vi
495+
.spyOn(useRightPanelStore.getState(), "openFile")
496+
.mockImplementation(() => {});
497+
const container = await renderText("[Notes](physics/notes/a.md:7)", {
498+
cwd: "/school/physics",
499+
threadRef,
500+
});
501+
502+
await act(async () => container.querySelector("a")!.click());
503+
504+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);
505+
expect(filesystemMetadata).toHaveBeenCalledExactlyOnceWith({
506+
environmentId: threadRef.environmentId,
507+
input: { paths: ["/school/physics/physics/notes/a.md"] },
508+
});
509+
});
510+
511+
it.each([
512+
{
513+
kind: "absolute link",
514+
href: "/school/physics/physics/notes/a.md:7",
515+
imageBaseDir: undefined,
516+
},
517+
{ kind: "nested preview", href: "notes/a.md:7", imageBaseDir: "/school/physics/physics" },
518+
])(
519+
"keeps the literal target for a $kind when only its stripped twin exists",
520+
async ({ href, imageBaseDir }) => {
521+
workspaceSearch.mockResolvedValue(
522+
AsyncResult.success({
523+
entries: [{ path: "notes/a.md", kind: "file" }],
524+
truncated: false,
525+
}),
526+
);
527+
const openFile = vi
528+
.spyOn(useRightPanelStore.getState(), "openFile")
529+
.mockImplementation(() => {});
530+
const container = await renderText(`[Notes](${href})`, {
531+
cwd: "/school/physics",
532+
imageBaseDir,
533+
threadRef,
534+
});
535+
536+
await act(async () => container.querySelector("a")!.click());
537+
538+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);
539+
expect(workspaceSearch).not.toHaveBeenCalled();
540+
expect(filesystemMetadata).not.toHaveBeenCalled();
541+
},
542+
);
543+
544+
it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {
545+
const result = AsyncResult.success({
546+
entries: [{ path: "notes/a.md", kind: "file" }],
547+
truncated: false,
548+
});
549+
let resolvePending!: (value: typeof result) => void;
550+
const pending = new Promise<typeof result>((resolve) => {
551+
resolvePending = resolve;
552+
});
553+
workspaceSearch.mockReturnValueOnce(pending);
554+
const openFile = vi
555+
.spyOn(useRightPanelStore.getState(), "openFile")
556+
.mockImplementation(() => {});
557+
const container = await renderText(
558+
"[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",
559+
{
560+
cwd: "/school/physics",
561+
threadRef,
562+
},
563+
);
564+
const [notes, other] = container.querySelectorAll("a");
565+
await act(async () => notes!.click());
566+
expect(workspaceSearch).toHaveBeenCalledOnce();
567+
expect(openFile).not.toHaveBeenCalled();
568+
569+
await act(async () => other!.click());
570+
await act(async () => resolvePending(result));
571+
572+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
573+
expect(workspaceSearch).toHaveBeenCalledOnce();
574+
});
575+
});
576+
403577
describe("ChatMarkdown file citations", () => {
404578
it.each([true, false])(
405579
"renders Codex file citations as file chips with parseRawHtml=%s",

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
extractMarkdownLinkHrefs,
1212
inlineCodeFilePathCandidate,
1313
} from "@t3tools/shared/markdownLinks";
14-
import { isAbsolutePath } from "@t3tools/shared/path";
14+
import { isAbsolutePath, resolveWorkspaceFilePath } from "@t3tools/shared/path";
1515
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
1616
import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
1717
import {
@@ -195,6 +195,7 @@ import { previewEnvironment } from "../state/preview";
195195
import { useAtomCommand } from "../state/use-atom-command";
196196
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
197197
import { projectEnvironment } from "../state/projects";
198+
import { filesystemEnvironment } from "../state/filesystem";
198199
import {
199200
claimWorkspaceBasenameLookup,
200201
needsWorkspaceBasenameLookup,
@@ -2388,6 +2389,10 @@ function useChatMarkdownState({
23882389
const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {
23892390
reportFailure: false,
23902391
});
2392+
const getFilesystemMetadata = useAtomQueryRunner(filesystemEnvironment.getMetadata, {
2393+
reportFailure: false,
2394+
refresh: true,
2395+
});
23912396
const openPreview = useAtomCommand(previewEnvironment.open, {
23922397
reportFailure: false,
23932398
});
@@ -2611,8 +2616,10 @@ function useChatMarkdownState({
26112616
openPreview,
26122617
});
26132618
};
2614-
const findWorkspaceBasenameMatch = async (workspaceRelativePath: string) => {
2619+
const findWorkspaceFileMatch = async (fileLinkMeta: MarkdownFileLinkMeta) => {
2620+
const workspaceRelativePath = fileLinkMeta.workspaceLookupPath;
26152621
if (
2622+
!workspaceRelativePath ||
26162623
!cwd ||
26172624
environmentId === null ||
26182625
!readEnvironmentScope(environmentId, AuthFilesystemReadScope)
@@ -2637,20 +2644,25 @@ function useChatMarkdownState({
26372644
if (strippedPath === null) {
26382645
return pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries);
26392646
}
2640-
return pickStrippedWorkspaceMatch(
2641-
workspaceRelativePath,
2642-
strippedPath,
2643-
cwd,
2644-
result.value.entries,
2645-
);
2647+
const match = pickStrippedWorkspaceMatch(strippedPath, cwd, result.value.entries);
2648+
if (match === null) return null;
2649+
// Search can be truncated or still scanning, so it cannot rule out the
2650+
// literal path. Check the host before redirecting to the stripped match.
2651+
const metadata = await getFilesystemMetadata({
2652+
environmentId,
2653+
input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] },
2654+
});
2655+
return metadata._tag === "Success" && metadata.value.entries[0] === null ? match : null;
26462656
};
2647-
const openFileInPanel = (panelPath: string, line: number | undefined) => {
2657+
const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
26482658
if (!threadRef) return;
26492659
// Claimed on every open so a synchronous one supersedes a lookup already
26502660
// in flight.
26512661
const isLatestLookup = claimWorkspaceBasenameLookup();
2652-
const openAt = (path: string) => useRightPanelStore.getState().openFile(threadRef, path, line);
2662+
const openAt = (path: string) =>
2663+
useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line);
26532664
if (
2665+
fileLinkMeta.workspaceLookupPath === null ||
26542666
!cwd ||
26552667
(!needsWorkspaceBasenameLookup(panelPath) &&
26562668
stripRepeatedWorkspacePrefix(panelPath, cwd) === null)
@@ -2659,16 +2671,13 @@ function useChatMarkdownState({
26592671
return;
26602672
}
26612673
void (async () => {
2662-
const match = await findWorkspaceBasenameMatch(panelPath);
2674+
const match = await findWorkspaceFileMatch(fileLinkMeta);
26632675
if (!isLatestLookup()) return;
26642676
openAt(match ?? panelPath);
26652677
})();
26662678
};
26672679
const revealMarkdownFileInFileManager = async (fileLinkMeta: MarkdownFileLinkMeta) => {
2668-
const workspaceRelativePath = fileLinkMeta.workspaceRelativePath;
2669-
const match = workspaceRelativePath
2670-
? await findWorkspaceBasenameMatch(workspaceRelativePath)
2671-
: null;
2680+
const match = await findWorkspaceFileMatch(fileLinkMeta);
26722681
const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;
26732682
return revealFileInFileManager(filePath);
26742683
};
@@ -2707,7 +2716,7 @@ function useChatMarkdownState({
27072716
theme={resolvedTheme}
27082717
threadRef={threadRef}
27092718
{...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}
2710-
onOpenInPanel={openFileInPanel}
2719+
onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)}
27112720
onOpenMedia={
27122721
threadRef && canPreviewMedia
27132722
? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)

‎apps/web/src/markdown-links.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import { fileBasename, workspaceRelativeFilePath } from "@t3tools/shared/path";
1+
import { fileBasename, isAbsolutePath, workspaceRelativeFilePath } from "@t3tools/shared/path";
22
import {
33
inlineCodeFilePathCandidate,
44
isRelativeFilePath,
55
normalizeMarkdownLinkDestination,
6+
parseMarkdownFileLink,
67
resolveMarkdownFileLinkTarget,
78
} from "@t3tools/shared/markdownLinks";
89
import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";
@@ -12,6 +13,7 @@ import { isTerminalLinkActivation } from "./terminal-links";
1213

1314
export interface MarkdownFileLinkMeta {
1415
filePath: string;
16+
workspaceLookupPath: string | null;
1517
targetPath: string;
1618
displayPath: string;
1719
workspaceRelativePath: string | null;
@@ -70,10 +72,20 @@ export function resolveMarkdownFileLinkMeta(
7072
): MarkdownFileLinkMeta | null {
7173
const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
7274
if (!targetPath) return null;
73-
return buildFileLinkMetaFromTarget(targetPath, cwd);
75+
const source = href ? parseMarkdownFileLink(href) : null;
76+
return {
77+
...buildFileLinkMetaFromTarget(targetPath, cwd),
78+
workspaceLookupPath:
79+
source !== null &&
80+
!isAbsolutePath(source.path) &&
81+
baseDir !== undefined &&
82+
workspaceRelativeFilePath(baseDir, cwd) === "."
83+
? source.path
84+
: null,
85+
};
7486
}
7587

76-
function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
88+
function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) {
7789
const { path, line, column } = splitFilePathPosition(targetPath);
7890
return {
7991
filePath: path,

0 commit comments

Comments
 (0)