fix(web): open the file a bare filename reference names (#6297)

Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-08-15 12:44:51 +02:00
1 parent b277cc65e0
commit 2cb1a26f06
3 files changed
+192 -2

No files matched your search

+51 -2
View File
@@ -90,6 +90,13 @@ import { usePreparedConnection } from "../state/session";
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 {
claimWorkspaceBasenameLookup,
needsWorkspaceBasenameLookup,
pickWorkspaceBasenameMatch,
WORKSPACE_BASENAME_LOOKUP_LIMIT,
} from "../workspaceBasenameLookup";
import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
@@ -811,6 +818,7 @@ interface MarkdownFileLinkProps {
theme: "light" | "dark";
threadRef?: ScopedThreadRef | undefined;
onOpen: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
onOpenInPanel: (workspaceRelativePath: string, line: number | undefined) => void;
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
className?: string | undefined;
}
@@ -1116,6 +1124,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
theme,
threadRef,
onOpen,
onOpenInPanel,
onOpenInBrowser,
className,
}: MarkdownFileLinkProps) {
@@ -1159,8 +1168,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
handleOpenInEditor();
return;
}
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line);
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
onOpenInPanel(workspaceRelativePath, line);
}, [handleOpenInEditor, line, onOpenInPanel, threadRef, workspaceRelativePath]);
const handleOpenInBrowser = useCallback(() => {
if (!onOpenInBrowser) {
@@ -1336,6 +1345,7 @@ function areMarkdownFileLinkPropsEqual(
previous.theme === next.theme &&
previous.threadRef === next.threadRef &&
previous.onOpen === next.onOpen &&
previous.onOpenInPanel === next.onOpenInPanel &&
previous.onOpenInBrowser === next.onOpenInBrowser &&
previous.className === next.className
);
@@ -1355,6 +1365,9 @@ function ChatMarkdown({
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
@@ -1457,6 +1470,40 @@ function ChatMarkdown({
},
[createAssetUrl, openPreview, preparedConnection, threadRef],
);
// A bare filename resolves to the workspace root, which is rarely where the
// file is, so ask the index before opening.
const openFileInPanel = useCallback(
(workspaceRelativePath: string, line: number | undefined) => {
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(workspaceRelativePath)) {
openAt(workspaceRelativePath);
return;
}
void (async () => {
const result = await searchProjectEntries({
environmentId: threadRef.environmentId,
input: {
cwd,
query: workspaceRelativePath,
limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,
kind: "file",
},
});
const match =
result._tag === "Success"
? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)
: null;
if (!isLatestLookup()) return;
openAt(match ?? workspaceRelativePath);
})();
},
[cwd, searchProjectEntries, threadRef],
);
/* eslint-disable react/no-unstable-nested-components -- ReactMarkdown requires component
* renderers that close over this message's metadata. useMemo keeps them stable until that
* metadata changes. */
@@ -1490,6 +1537,7 @@ function ChatMarkdown({
theme={resolvedTheme}
threadRef={threadRef}
onOpen={openInPreferredEditor}
onOpenInPanel={openFileInPanel}
onOpenInBrowser={
threadRef &&
isPreviewSupportedInRuntime() &&
@@ -1718,6 +1766,7 @@ function ChatMarkdown({
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
openFileInPanel,
openInPreferredEditor,
openExternalLinkInPreview,
openMarkdownFileInPreview,
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vite-plus/test";
import {
claimWorkspaceBasenameLookup,
needsWorkspaceBasenameLookup,
pickWorkspaceBasenameMatch,
} from "./workspaceBasenameLookup";
describe("needsWorkspaceBasenameLookup", () => {
it("flags bare filenames", () => {
expect(needsWorkspaceBasenameLookup("ChatView.tsx")).toBe(true);
expect(needsWorkspaceBasenameLookup("Makefile")).toBe(true);
});
it("leaves anything with a directory alone", () => {
expect(needsWorkspaceBasenameLookup("apps/web/src/components/ChatView.tsx")).toBe(false);
expect(needsWorkspaceBasenameLookup("apps\\web\\ChatView.tsx")).toBe(false);
expect(needsWorkspaceBasenameLookup(" ")).toBe(false);
});
});
describe("pickWorkspaceBasenameMatch", () => {
const entries = [
{ path: "apps/web/src/components/ChatView.test.tsx", kind: "file" as const },
{ path: "apps/web/src/components/ChatView.tsx", kind: "file" as const },
];
it("takes the first exact filename match, not the closest fuzzy one", () => {
expect(pickWorkspaceBasenameMatch("ChatView.tsx", entries)).toBe(
"apps/web/src/components/ChatView.tsx",
);
});
it("ignores directories", () => {
expect(
pickWorkspaceBasenameMatch("components", [
{ path: "apps/web/src/components", kind: "directory" },
{ path: "apps/web/src/components/components", kind: "file" },
]),
).toBe("apps/web/src/components/components");
});
it("prefers the exactly-cased file over a case-only twin", () => {
expect(
pickWorkspaceBasenameMatch("foo.ts", [
{ path: "src/Foo.ts", kind: "file" },
{ path: "src/foo.ts", kind: "file" },
]),
).toBe("src/foo.ts");
});
it("falls back to case-insensitive when only the casing differs", () => {
expect(pickWorkspaceBasenameMatch("chatview.tsx", entries)).toBe(
"apps/web/src/components/ChatView.tsx",
);
});
it("returns null when the case-insensitive fallback is ambiguous", () => {
expect(
pickWorkspaceBasenameMatch("FOO.ts", [
{ path: "src/Foo.ts", kind: "file" },
{ path: "src/foo.ts", kind: "file" },
]),
).toBeNull();
});
it("returns null when nothing matches the name", () => {
expect(pickWorkspaceBasenameMatch("ChatView.tsx", [])).toBeNull();
expect(
pickWorkspaceBasenameMatch("ChatView.tsx", [
{ path: "apps/web/src/components/ChatHeader.tsx", kind: "file" },
]),
).toBeNull();
});
});
describe("claimWorkspaceBasenameLookup", () => {
it("keeps only the newest claim, whatever order the lookups settle in", () => {
const first = claimWorkspaceBasenameLookup();
const second = claimWorkspaceBasenameLookup();
// The older lookup answering last must not reopen the panel behind the
// newer one.
expect(second()).toBe(true);
expect(first()).toBe(false);
});
it("stays valid while it is the only claim", () => {
const only = claimWorkspaceBasenameLookup();
expect(only()).toBe(true);
expect(only()).toBe(true);
});
});
+48
View File
@@ -0,0 +1,48 @@
// Enough hits to look past same-named neighbours (`ChatView.test.tsx`) without
// asking for a full listing on a single click.
export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;
// One counter for every caller: they all open the same panel, so the newest
// click wins regardless of which one started the lookup.
let latestLookupSequence = 0;
/** Call the returned predicate when the search settles; false means a later click superseded it. */
export function claimWorkspaceBasenameLookup(): () => boolean {
latestLookupSequence += 1;
const claimed = latestLookupSequence;
return () => claimed === latestLookupSequence;
}
export interface WorkspaceEntryCandidate {
readonly path: string;
readonly kind: "file" | "directory";
}
function basenameOfPath(path: string): string {
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
}
export function needsWorkspaceBasenameLookup(relativePath: string): boolean {
const trimmed = relativePath.trim();
return trimmed.length > 0 && !trimmed.includes("/") && !trimmed.includes("\\");
}
export function pickWorkspaceBasenameMatch(
basename: string,
entries: ReadonlyArray<WorkspaceEntryCandidate>,
): string | null {
const target = basename.trim();
if (!target) return null;
const files = entries.filter((entry) => entry.kind === "file");
const exact = files.find((entry) => basenameOfPath(entry.path) === target);
if (exact) return exact.path;
// Folded matching covers casing that drifted from disk, but `FOO.ts` against
// both `Foo.ts` and `foo.ts` has no right answer, so it resolves to nothing
// rather than opening whichever the index ranked first.
const folded = target.toLowerCase();
const foldedMatches = files.filter(
(entry) => basenameOfPath(entry.path).toLowerCase() === folded,
);
return foldedMatches.length === 1 ? (foldedMatches[0]?.path ?? null) : null;
}