Skip to content

Commit 21e9148

Browse files
committed
fix(web): resolve slashed file-chip paths through the workspace index
A slashed chip like `docs/PLAN.md` that does not exist at the project root opened a dead path unless it repeated the project folder's name, so links broke in monorepos and subfolder projects. Slashed chips now check the host first: a literal file always opens as written. Otherwise the workspace index resolves the path when exactly one file ends with it on a folder boundary, including truncated results. Editor, reveal and browser opens share the panel's newest-click-wins claim, and browser opens recheck preview permission after the lookup. Co-authored-by: Julius Marminge <[email protected]> Claude Opus 5.5 via Claude Code in T3 Code
1 parent 210b2e7 commit 21e9148

5 files changed

Lines changed: 282 additions & 49 deletions

File tree

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,57 @@ describe("ChatMarkdown workspace file opens", () => {
258258
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9);
259259
expect(workspaceSearch).toHaveBeenCalledOnce();
260260
});
261+
262+
// regression: #18358 a missing slashed path opens the one indexed file ending with it
263+
it("opens a missing slashed path at its unique indexed suffix", async () => {
264+
setup();
265+
workspaceSearch.mockResolvedValue(
266+
AsyncResult.success({
267+
entries: [
268+
{ path: "other/GROUPS_PLAN.md", kind: "file" },
269+
{ path: "BudgetLens/mydocs/GROUPS_PLAN.md", kind: "file" },
270+
{ path: "BudgetLens/docs/GROUPS_PLAN.md", kind: "file" },
271+
],
272+
truncated: true,
273+
}),
274+
);
275+
using openFile = vi
276+
.spyOn(useRightPanelStore.getState(), "openFile")
277+
.mockImplementation(() => {});
278+
await using screen = await renderText("[Plan](docs/GROUPS_PLAN.md:12)", {
279+
cwd: "/work",
280+
threadRef,
281+
});
282+
await act(async () => screen.container.querySelector("a")!.click());
283+
284+
expect(filesystemMetadata).toHaveBeenCalledExactlyOnceWith({
285+
environmentId: threadRef.environmentId,
286+
input: { paths: ["/work/docs/GROUPS_PLAN.md"] },
287+
});
288+
expect(openFile).toHaveBeenCalledExactlyOnceWith(
289+
threadRef,
290+
"BudgetLens/docs/GROUPS_PLAN.md",
291+
12,
292+
);
293+
});
294+
295+
it("opens an existing slashed path without searching the workspace", async () => {
296+
setup();
297+
filesystemMetadata.mockResolvedValue(
298+
AsyncResult.success({ entries: [{ kind: "file", byteLength: 10 }] }),
299+
);
300+
using openFile = vi
301+
.spyOn(useRightPanelStore.getState(), "openFile")
302+
.mockImplementation(() => {});
303+
await using screen = await renderText("[Plan](docs/GROUPS_PLAN.md:12)", {
304+
cwd: "/work",
305+
threadRef,
306+
});
307+
await act(async () => screen.container.querySelector("a")!.click());
308+
309+
expect(workspaceSearch).not.toHaveBeenCalled();
310+
expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "docs/GROUPS_PLAN.md", 12);
311+
});
261312
});
262313

263314
describe("ChatMarkdown headings", () => {

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

Lines changed: 125 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
AuthOrchestrationOperateScope,
3+
AuthPreviewOperateScope,
34
EnvironmentId,
45
ProjectId,
56
ThreadId,
@@ -19,17 +20,23 @@ const state = vi.hoisted(() => ({
1920
openEditor: vi.fn(),
2021
updateMetadata: vi.fn(),
2122
search: vi.fn(),
23+
metadata: vi.fn(),
24+
openBrowser: vi.fn(),
2225
choose: vi.fn(),
2326
openFile: vi.fn(),
2427
openExternal: vi.fn(),
2528
copy: vi.fn(),
2629
linkedPullRequest: null as ThreadLinkedPullRequest | null,
2730
}));
2831

29-
vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
30-
...(await original()),
31-
useAtomQueryRunner: (() => state.search) as never,
32-
}));
32+
vi.mock(import("../state/use-atom-query-runner"), async (original) => {
33+
const { filesystemEnvironment } = await import("../state/filesystem");
34+
return {
35+
...(await original()),
36+
useAtomQueryRunner: ((query: unknown) =>
37+
query === filesystemEnvironment.getMetadata ? state.metadata : state.search) as never,
38+
};
39+
});
3340
vi.mock(import("../state/use-atom-command"), async (original) => {
3441
const { threadEnvironment } = await import("../state/threads");
3542
return {
@@ -44,10 +51,13 @@ vi.mock(import("../state/session"), async (original) => {
4451
const { useSyncExternalStore } = await import("react");
4552
const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
4653
id !== null &&
47-
(scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
54+
((scope !== AuthOrchestrationOperateScope && scope !== AuthPreviewOperateScope) ||
55+
id !== threadRef.environmentId ||
56+
state.allowed);
4857
return {
4958
...(await original()),
5059
readEnvironmentScope,
60+
readPreparedConnection: (() => ({ httpBaseUrl: "https://host.test" })) as never,
5161
useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
5262
useSyncExternalStore(
5363
(listener) => {
@@ -94,6 +104,14 @@ vi.mock(import("../localApi"), async (original) => ({
94104
shell: { openExternal: state.openExternal },
95105
}) as never,
96106
}));
107+
vi.mock(import("../browser/previewRuntime"), async (original) => ({
108+
...(await original()),
109+
isPreviewAvailableFor: () => true,
110+
}));
111+
vi.mock(import("../browser/openFileInPreview"), async (original) => ({
112+
...(await original()),
113+
openFileInPreview: state.openBrowser,
114+
}));
97115
vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({
98116
...(await original()),
99117
resolvePullRequestPreviewTarget: () => null,
@@ -127,6 +145,8 @@ function setup() {
127145
state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
128146
state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
129147
state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
148+
state.metadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
149+
state.openBrowser.mockReset().mockResolvedValue(AsyncResult.success(undefined));
130150
state.choose.mockReset().mockResolvedValue(null);
131151
state.openFile.mockReset();
132152
state.openExternal.mockReset().mockResolvedValue(undefined);
@@ -269,3 +289,103 @@ it.each(["link-to-thread", "unlink-from-thread"])(
269289
);
270290
},
271291
);
292+
293+
function deferSearch() {
294+
let finish: (paths: readonly string[]) => void = () => {
295+
throw new Error("Lookup not started");
296+
};
297+
state.search.mockImplementationOnce(
298+
() =>
299+
new Promise((resolve) => {
300+
finish = (paths) =>
301+
resolve(
302+
AsyncResult.success({
303+
entries: paths.map((path) => ({ path, kind: "file" })),
304+
truncated: false,
305+
}),
306+
);
307+
}),
308+
);
309+
return (paths: readonly string[]) => act(async () => finish(paths));
310+
}
311+
312+
const indexedPlan = "BudgetLens/docs/plan.html";
313+
314+
it.each([
315+
[
316+
"open",
317+
() => [
318+
expect.objectContaining({
319+
input: expect.objectContaining({ cwd: `/work/${indexedPlan}:12:3` }),
320+
}),
321+
],
322+
],
323+
[
324+
"reveal",
325+
() => [
326+
expect.objectContaining({
327+
input: expect.objectContaining({ cwd: `/work/${indexedPlan}`, reveal: true }),
328+
}),
329+
],
330+
],
331+
] as const)(
332+
"resolves a missing slashed path through the workspace index for %s",
333+
async (action, expected) => {
334+
using _setup = setup();
335+
state.search.mockResolvedValue(
336+
AsyncResult.success({ entries: [{ path: indexedPlan, kind: "file" }], truncated: true }),
337+
);
338+
state.choose.mockResolvedValue(action);
339+
await using screen = await renderMarkdown("[Plan](docs/plan.html:12:3)");
340+
await screen.openContextMenu();
341+
await vi.waitFor(() => expect(state.openEditor).toHaveBeenCalledWith(...expected()));
342+
},
343+
);
344+
345+
it("opens a missing slashed path in the browser at its indexed match", async () => {
346+
using _setup = setup();
347+
state.search.mockResolvedValue(
348+
AsyncResult.success({ entries: [{ path: indexedPlan, kind: "file" }], truncated: false }),
349+
);
350+
state.choose.mockResolvedValue("open-in-browser");
351+
await using screen = await renderMarkdown("[Plan](docs/plan.html:12:3)");
352+
await screen.openContextMenu();
353+
await vi.waitFor(() =>
354+
expect(state.openBrowser).toHaveBeenCalledWith(
355+
expect.objectContaining({ filePath: `/work/${indexedPlan}` }),
356+
),
357+
);
358+
});
359+
360+
it.each(["open", "open-in-browser", "reveal"])(
361+
"discards a pending %s lookup after a newer panel open",
362+
async (action) => {
363+
using _setup = setup();
364+
const finishLookup = deferSearch();
365+
state.choose.mockResolvedValue(action);
366+
await using screen = await renderMarkdown(
367+
"[Plan](docs/plan.html:12:3) and [Other](/outside/newer.ts:8)",
368+
);
369+
await screen.openContextMenu();
370+
expect(state.search).toHaveBeenCalledOnce();
371+
await act(async () => screen.container.querySelectorAll("a")[1]!.click());
372+
await finishLookup([indexedPlan]);
373+
374+
expect(state.openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/outside/newer.ts", 8);
375+
expect(state.openEditor).not.toHaveBeenCalled();
376+
expect(state.openBrowser).not.toHaveBeenCalled();
377+
},
378+
);
379+
380+
it("rechecks browser permission after the file lookup", async () => {
381+
using _setup = setup();
382+
const finishLookup = deferSearch();
383+
state.choose.mockResolvedValue("open-in-browser");
384+
await using screen = await renderMarkdown("[Plan](docs/plan.html:12:3)");
385+
await screen.openContextMenu();
386+
expect(state.search).toHaveBeenCalledOnce();
387+
await setAllowed(false);
388+
await finishLookup([indexedPlan]);
389+
390+
expect(state.openBrowser).not.toHaveBeenCalled();
391+
});

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

Lines changed: 53 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
type ThreadPullRequestKey,
5151
} from "@t3tools/contracts";
5252
import {
53+
type AtomCommandResult,
5354
isAtomCommandInterrupted,
5455
squashAtomCommandFailure,
5556
} from "@t3tools/client-runtime/state/runtime";
@@ -715,9 +716,13 @@ function useChatMarkdownState({
715716
return result;
716717
});
717718
};
718-
const openMarkdownFileInPreview = (path: string) => {
719+
const openMarkdownFileInPreview = (path: string, isLatestLookup: () => boolean) => {
719720
const preparedConnection = threadRef ? readPreparedConnection(threadRef.environmentId) : null;
720-
if (!threadRef || !canOperatePreview || preparedConnection === null) {
721+
if (
722+
!threadRef ||
723+
!readEnvironmentScope(threadRef.environmentId, AuthPreviewOperateScope) ||
724+
preparedConnection === null
725+
) {
721726
return Promise.resolve(
722727
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
723728
Cause.fail(
@@ -734,7 +739,12 @@ function useChatMarkdownState({
734739
workspaceRoot: cwd,
735740
httpBaseUrl: preparedConnection.httpBaseUrl,
736741
createAssetUrl,
737-
openPreview,
742+
// Creating the asset URL is async, so a newer file action can land first.
743+
openPreview: async (input) => {
744+
if (!isLatestLookup()) return AsyncResult.failure(Cause.interrupt());
745+
const result = await openPreview(input);
746+
return isLatestLookup() ? result : AsyncResult.failure(Cause.interrupt());
747+
},
738748
});
739749
};
740750
const findWorkspaceFileMatch = async (fileLinkMeta: MarkdownFileLinkMeta) => {
@@ -748,10 +758,24 @@ function useChatMarkdownState({
748758
return null;
749759
}
750760
const isBasename = needsWorkspaceBasenameLookup(workspaceRelativePath);
761+
if (!isBasename) {
762+
// Search can be truncated, still scanning, or skip ignored files, so it
763+
// cannot rule out the literal path. A literal file always wins.
764+
const metadata = await getFilesystemMetadata({
765+
environmentId,
766+
input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] },
767+
});
768+
if (
769+
metadata._tag !== "Success" ||
770+
metadata.value.entries[0]?.kind === "file" ||
771+
!readEnvironmentScope(environmentId, AuthFilesystemReadScope)
772+
) {
773+
return null;
774+
}
775+
}
751776
const strippedPath = isBasename
752777
? null
753778
: stripRepeatedWorkspacePrefix(workspaceRelativePath, cwd);
754-
if (!isBasename && strippedPath === null) return null;
755779
const result = await searchProjectEntries({
756780
environmentId,
757781
input: {
@@ -762,31 +786,17 @@ function useChatMarkdownState({
762786
},
763787
});
764788
if (result._tag !== "Success") return null;
765-
if (strippedPath === null) {
766-
return pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries);
767-
}
768-
const match = pickStrippedWorkspaceMatch(strippedPath, cwd, result.value.entries);
769-
if (match === null) return null;
770-
// Search can be truncated or still scanning, so it cannot rule out the
771-
// literal path. Check the host before redirecting to the stripped match.
772-
const metadata = await getFilesystemMetadata({
773-
environmentId,
774-
input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] },
775-
});
776-
return metadata._tag === "Success" && metadata.value.entries[0] === null ? match : null;
789+
return strippedPath === null
790+
? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)
791+
: pickStrippedWorkspaceMatch(strippedPath, cwd, result.value.entries);
777792
};
778793
const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
779794
if (!threadRef) return;
780795
// Every open supersedes pending lookups, including synchronous opens.
781796
const isLatestLookup = claimWorkspaceBasenameLookup();
782797
const openAt = (path: string) =>
783798
useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line);
784-
if (
785-
fileLinkMeta.workspaceLookupPath === null ||
786-
!cwd ||
787-
(!needsWorkspaceBasenameLookup(panelPath) &&
788-
stripRepeatedWorkspacePrefix(panelPath, cwd) === null)
789-
) {
799+
if (fileLinkMeta.workspaceLookupPath === null || !cwd) {
790800
openAt(panelPath);
791801
return;
792802
}
@@ -807,6 +817,20 @@ function useChatMarkdownState({
807817
cwd,
808818
findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta),
809819
});
820+
const openResolved =
821+
<A, E>(
822+
open: (
823+
hostPath: Awaited<ReturnType<typeof resolveHostPath>>,
824+
isLatestLookup: () => boolean,
825+
) => Promise<AtomCommandResult<A, E>>,
826+
) =>
827+
async () => {
828+
const isLatestLookup = claimWorkspaceBasenameLookup();
829+
const hostPath = await resolveHostPath();
830+
return isLatestLookup()
831+
? open(hostPath, isLatestLookup)
832+
: AsyncResult.failure<A, E>(Cause.interrupt());
833+
};
810834
const mediaPath = mediaSource ?? fileLinkMeta.filePath;
811835
const canPreviewMedia =
812836
mediaMimeTypeFromExtension(
@@ -838,10 +862,9 @@ function useChatMarkdownState({
838862
threadRef={threadRef}
839863
onOpen={
840864
canUseShellActions
841-
? async () =>
842-
openInPreferredEditor(
843-
markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),
844-
)
865+
? openResolved((hostPath) =>
866+
openInPreferredEditor(markdownFileEditorTarget(fileLinkMeta, hostPath)),
867+
)
845868
: undefined
846869
}
847870
resolveCopyPaths={async () =>
@@ -856,7 +879,7 @@ function useChatMarkdownState({
856879
openInEditorMenuLabel={preferredEditorMenuLabel}
857880
onReveal={
858881
canUseShellActions && revealInFileManagerLabel !== undefined
859-
? async () => revealFileInFileManager((await resolveHostPath()).absolutePath)
882+
? openResolved((hostPath) => revealFileInFileManager(hostPath.absolutePath))
860883
: undefined
861884
}
862885
revealLabel={revealInFileManagerLabel}
@@ -865,7 +888,9 @@ function useChatMarkdownState({
865888
canOperatePreview &&
866889
isPreviewAvailableFor(threadRef.environmentId) &&
867890
isBrowserPreviewFile(fileLinkMeta.filePath)
868-
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
891+
? openResolved((hostPath, isLatestLookup) =>
892+
openMarkdownFileInPreview(hostPath.absolutePath, isLatestLookup),
893+
)
869894
: undefined
870895
}
871896
/>

0 commit comments

Comments
 (0)