TypeScript
fix(web): repo-root-relative file chips open in subfolder projects (#14510)
Guillermo Casanova10b6779a2d4b
diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsxindex eac41c7eb0b..6e9b8bdf161 100644--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx@@ -1,15 +1,28 @@-import { EnvironmentId } from "@t3tools/contracts";+import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { searchableMessageSegments } from "@t3tools/shared/threadFindText";import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";+import { AsyncResult } from "effect/reactivity";import { act, type ReactElement } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { filesystemEnvironment } from "../state/filesystem";+import { useRightPanelStore } from "../rightPanelStore";import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";import { MarkdownFindContext } from "./chat/markdownFindContext";import { useThreadFindHighlights } from "./chat/threadFindHighlights";import { setMarkdownTaskChecked } from "./files/filePreviewMode";+const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({+ workspaceSearch: vi.fn(),+ filesystemMetadata: vi.fn(),+}));+vi.mock(import("../state/use-atom-query-runner"), async (original) => ({+ ...(await original()),+ useAtomQueryRunner: ((family: unknown) =>+ family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never,+}));+// Atoms derived from the server config run in the real registry over a missing config.vi.mock(import("../state/server"), async (original) => {const actual = await original();@@ -47,6 +60,8 @@ import ChatMarkdown from "./ChatMarkdown";const roots: Root[] = [];beforeEach(() => {+ workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));+ filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);});@@ -400,6 +415,165 @@ describe("ChatMarkdown skill chips", () => {});});+describe("ChatMarkdown workspace file opens", () => {+ const threadRef = {+ environmentId: EnvironmentId.make("workspace"),+ threadId: ThreadId.make("thread"),+ };++ it.each([+ {+ cwd: "/school/courses/physics",+ path: "courses/physics/notes/a.md",+ indexedPath: "notes/a.md",+ },+ {+ cwd: "C:/school/courses/Physics",+ path: "courses/physics/notes/a.md",+ indexedPath: "Notes/A.md",+ },+ ])(+ "opens a repo-relative chip at its indexed path in $cwd",+ async ({ cwd, path, indexedPath }) => {+ workspaceSearch.mockResolvedValue(+ AsyncResult.success({+ entries: [+ { path: indexedPath, kind: "file" },+ { path, kind: "file" },+ ],+ truncated: false,+ }),+ );+ const openFile = vi+ .spyOn(useRightPanelStore.getState(), "openFile")+ .mockImplementation(() => {});+ const container = await renderText(`[Notes](${path}:7)`, { cwd, threadRef });++ await act(async () => container.querySelector("a")!.click());++ expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, indexedPath, 7);+ },+ );++ it("prefers an existing literal nested file over the stripped Windows match", async () => {+ filesystemMetadata.mockResolvedValue(+ AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),+ );+ workspaceSearch.mockResolvedValue(+ AsyncResult.success({+ entries: [+ { path: "Notes/A.md", kind: "file" },+ { path: "Physics/Notes/A.md", kind: "file" },+ ],+ truncated: false,+ }),+ );+ const openFile = vi+ .spyOn(useRightPanelStore.getState(), "openFile")+ .mockImplementation(() => {});+ const container = await renderText("[Notes](physics/notes/a.md)", {+ cwd: "C:/school/Physics",+ threadRef,+ });++ await act(async () => container.querySelector("a")!.click());++ expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", undefined);+ });++ it("keeps a literal file omitted by a truncated search", async () => {+ workspaceSearch.mockResolvedValue(+ AsyncResult.success({+ entries: [{ path: "notes/a.md", kind: "file" }],+ truncated: true,+ }),+ );+ filesystemMetadata.mockResolvedValue(+ AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),+ );+ const openFile = vi+ .spyOn(useRightPanelStore.getState(), "openFile")+ .mockImplementation(() => {});+ const container = await renderText("[Notes](physics/notes/a.md:7)", {+ cwd: "/school/physics",+ threadRef,+ });++ await act(async () => container.querySelector("a")!.click());++ expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);+ expect(filesystemMetadata).toHaveBeenCalledExactlyOnceWith({+ environmentId: threadRef.environmentId,+ input: { paths: ["/school/physics/physics/notes/a.md"] },+ });+ });++ it.each([+ {+ kind: "absolute link",+ href: "/school/physics/physics/notes/a.md:7",+ imageBaseDir: undefined,+ },+ { kind: "nested preview", href: "notes/a.md:7", imageBaseDir: "/school/physics/physics" },+ ])(+ "keeps the literal target for a $kind when only its stripped twin exists",+ async ({ href, imageBaseDir }) => {+ workspaceSearch.mockResolvedValue(+ AsyncResult.success({+ entries: [{ path: "notes/a.md", kind: "file" }],+ truncated: false,+ }),+ );+ const openFile = vi+ .spyOn(useRightPanelStore.getState(), "openFile")+ .mockImplementation(() => {});+ const container = await renderText(`[Notes](${href})`, {+ cwd: "/school/physics",+ imageBaseDir,+ threadRef,+ });++ await act(async () => container.querySelector("a")!.click());++ expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "physics/notes/a.md", 7);+ expect(workspaceSearch).not.toHaveBeenCalled();+ expect(filesystemMetadata).not.toHaveBeenCalled();+ },+ );++ it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => {+ const result = AsyncResult.success({+ entries: [{ path: "notes/a.md", kind: "file" }],+ truncated: false,+ });+ let resolvePending!: (value: typeof result) => void;+ const pending = new Promise<typeof result>((resolve) => {+ resolvePending = resolve;+ });+ workspaceSearch.mockReturnValueOnce(pending);+ const openFile = vi+ .spyOn(useRightPanelStore.getState(), "openFile")+ .mockImplementation(() => {});+ const container = await renderText(+ "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)",+ {+ cwd: "/school/physics",+ threadRef,+ },+ );+ const [notes, other] = container.querySelectorAll("a");+ await act(async () => notes!.click());+ expect(workspaceSearch).toHaveBeenCalledOnce();+ expect(openFile).not.toHaveBeenCalled();++ await act(async () => other!.click());+ await act(async () => resolvePending(result));++ expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);+ expect(workspaceSearch).toHaveBeenCalledOnce();+ });+});+describe("ChatMarkdown file citations", () => {it.each([true, false])("renders Codex file citations as file chips with parseRawHtml=%s",diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 9ec6ec2db05..d637b25e1e5 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -11,7 +11,7 @@ import {extractMarkdownLinkHrefs,inlineCodeFilePathCandidate,} from "@t3tools/shared/markdownLinks";-import { isAbsolutePath } from "@t3tools/shared/path";+import { isAbsolutePath, resolveWorkspaceFilePath } from "@t3tools/shared/path";import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";import {@@ -195,10 +195,13 @@ import { previewEnvironment } from "../state/preview";import { useAtomCommand } from "../state/use-atom-command";import { useAtomQueryRunner } from "../state/use-atom-query-runner";import { projectEnvironment } from "../state/projects";+import { filesystemEnvironment } from "../state/filesystem";import {claimWorkspaceBasenameLookup,needsWorkspaceBasenameLookup,+ pickStrippedWorkspaceMatch,pickWorkspaceBasenameMatch,+ stripRepeatedWorkspacePrefix,WORKSPACE_BASENAME_LOOKUP_LIMIT,} from "../workspaceBasenameLookup";import {@@ -2386,6 +2389,10 @@ function useChatMarkdownState({const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {reportFailure: false,});+ const getFilesystemMetadata = useAtomQueryRunner(filesystemEnvironment.getMetadata, {+ reportFailure: false,+ refresh: true,+ });const openPreview = useAtomCommand(previewEnvironment.open, {reportFailure: false,});@@ -2609,49 +2616,68 @@ function useChatMarkdownState({openPreview,});};- const findWorkspaceBasenameMatch = async (workspaceRelativePath: string) => {+ const findWorkspaceFileMatch = async (fileLinkMeta: MarkdownFileLinkMeta) => {+ const workspaceRelativePath = fileLinkMeta.workspaceLookupPath;if (+ !workspaceRelativePath ||!cwd ||environmentId === null ||- !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||- !needsWorkspaceBasenameLookup(workspaceRelativePath)+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope)) {return null;}+ const isBasename = needsWorkspaceBasenameLookup(workspaceRelativePath);+ const strippedPath = isBasename+ ? null+ : stripRepeatedWorkspacePrefix(workspaceRelativePath, cwd);+ if (!isBasename && strippedPath === null) return null;const result = await searchProjectEntries({environmentId,input: {cwd,- query: workspaceRelativePath,+ query: strippedPath ?? workspaceRelativePath,limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,kind: "file",},});- return result._tag === "Success"- ? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)- : null;+ if (result._tag !== "Success") return null;+ if (strippedPath === null) {+ return pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries);+ }+ const match = pickStrippedWorkspaceMatch(strippedPath, cwd, result.value.entries);+ if (match === null) return null;+ // Search can be truncated or still scanning, so it cannot rule out the+ // literal path. Check the host before redirecting to the stripped match.+ const metadata = await getFilesystemMetadata({+ environmentId,+ input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] },+ });+ return metadata._tag === "Success" && metadata.value.entries[0] === null ? match : null;};- const openFileInPanel = (panelPath: string, line: number | undefined) => {+ const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {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)) {+ const openAt = (path: string) =>+ useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line);+ if (+ fileLinkMeta.workspaceLookupPath === null ||+ !cwd ||+ (!needsWorkspaceBasenameLookup(panelPath) &&+ stripRepeatedWorkspacePrefix(panelPath, cwd) === null)+ ) {openAt(panelPath);return;}void (async () => {- const match = await findWorkspaceBasenameMatch(panelPath);+ const match = await findWorkspaceFileMatch(fileLinkMeta);if (!isLatestLookup()) return;openAt(match ?? panelPath);})();};const revealMarkdownFileInFileManager = async (fileLinkMeta: MarkdownFileLinkMeta) => {- const workspaceRelativePath = fileLinkMeta.workspaceRelativePath;- const match = workspaceRelativePath- ? await findWorkspaceBasenameMatch(workspaceRelativePath)- : null;+ const match = await findWorkspaceFileMatch(fileLinkMeta);const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;return revealFileInFileManager(filePath);};@@ -2690,7 +2716,7 @@ function useChatMarkdownState({theme={resolvedTheme}threadRef={threadRef}{...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}- onOpenInPanel={openFileInPanel}+ onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)}onOpenMedia={threadRef && canPreviewMedia? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.tsindex 72120997fd8..de5b7d3efad 100644--- a/apps/web/src/markdown-links.ts+++ b/apps/web/src/markdown-links.ts@@ -1,8 +1,9 @@-import { fileBasename, workspaceRelativeFilePath } from "@t3tools/shared/path";+import { fileBasename, isAbsolutePath, workspaceRelativeFilePath } from "@t3tools/shared/path";import {inlineCodeFilePathCandidate,isRelativeFilePath,normalizeMarkdownLinkDestination,+ parseMarkdownFileLink,resolveMarkdownFileLinkTarget,} from "@t3tools/shared/markdownLinks";import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";@@ -12,6 +13,7 @@ import { isTerminalLinkActivation } from "./terminal-links";export interface MarkdownFileLinkMeta {filePath: string;+ workspaceLookupPath: string | null;targetPath: string;displayPath: string;workspaceRelativePath: string | null;@@ -70,10 +72,20 @@ export function resolveMarkdownFileLinkMeta(): MarkdownFileLinkMeta | null {const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);if (!targetPath) return null;- return buildFileLinkMetaFromTarget(targetPath, cwd);+ const source = href ? parseMarkdownFileLink(href) : null;+ return {+ ...buildFileLinkMetaFromTarget(targetPath, cwd),+ workspaceLookupPath:+ source !== null &&+ !isAbsolutePath(source.path) &&+ baseDir !== undefined &&+ workspaceRelativeFilePath(baseDir, cwd) === "."+ ? source.path+ : null,+ };}-function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {+function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) {const { path, line, column } = splitFilePathPosition(targetPath);return {filePath: path,diff --git a/apps/web/src/workspaceBasenameLookup.ts b/apps/web/src/workspaceBasenameLookup.tsindex 2d007992319..710998dfd08 100644--- a/apps/web/src/workspaceBasenameLookup.ts+++ b/apps/web/src/workspaceBasenameLookup.ts@@ -1,3 +1,5 @@+import { isAbsolutePath, isWindowsAbsolutePath } from "@t3tools/shared/path";+export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;// One counter for every caller: they all open the same panel, so the newest@@ -46,3 +48,34 @@ export function pickWorkspaceBasenameMatch();return foldedMatches.length === 1 ? (foldedMatches[0]?.path ?? null) : null;}++// Repository-relative paths can repeat the project's suffix in subfolder projects.+export function stripRepeatedWorkspacePrefix(relativePath: string, cwd: string): string | null {+ if (isAbsolutePath(relativePath)) return null;+ const pathSegments = relativePath.split(/[\\/]+/);+ const cwdSegments = cwd.split(/[\\/]+/).filter(Boolean);+ const fold = isWindowsAbsolutePath(cwd)+ ? (segment: string | undefined) => segment?.toLowerCase()+ : (segment: string | undefined) => segment;+ for (let count = Math.min(cwdSegments.length, pathSegments.length - 1); count > 0; count--) {+ const prefix = cwdSegments.slice(-count);+ if (prefix.every((segment, index) => fold(segment) === fold(pathSegments[index]))) {+ return pathSegments.slice(count).join("/") || null;+ }+ }+ return null;+}++export function pickStrippedWorkspaceMatch(+ strippedPath: string,+ cwd: string,+ entries: ReadonlyArray<WorkspaceEntryCandidate>,+): string | null {+ const caseInsensitive = isWindowsAbsolutePath(cwd);+ const key = (path: string) => {+ const normalized = path.replaceAll("\\", "/");+ return caseInsensitive ? normalized.toLowerCase() : normalized;+ };+ const files = entries.filter((entry) => entry.kind === "file");+ return files.find((entry) => key(entry.path) === key(strippedPath))?.path ?? null;+}diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.tsindex b9ceb665d9a..619fd20b9b7 100644--- a/packages/client-runtime/src/state/filesystem.ts+++ b/packages/client-runtime/src/state/filesystem.ts@@ -115,6 +115,10 @@ export function createFilesystemEnvironmentAtoms<R, E>(runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,) {return {+ getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:filesystem:get-metadata",+ tag: WS_METHODS.filesystemGetMetadata,+ }),browse: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:filesystem:browse",tag: WS_METHODS.filesystemBrowse,