The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 01:45 UTC
fix(web): repo-root-relative file chips open in subfolder projects (#14510)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Guillermo Casanova committed
Oct 19, 2026 at 17:26 UTC
10b6779a2d4b4696cff0e9ac32f563c0d342a6a6
5 files changed
+270
-21
apps/web/src/components/ChatMarkdown.browser.test.tsx
+175
-1
@@ -1,15 +1,28 @@
1
-import { EnvironmentId } from "@t3tools/contracts";
1
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3
import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4
+import { AsyncResult } from "effect/reactivity";
5
import { act, type ReactElement } from "react";
6
import { createRoot, type Root } from "react-dom/client";
7
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
9
+import { filesystemEnvironment } from "../state/filesystem";
10
+import { useRightPanelStore } from "../rightPanelStore";
11
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
12
import { MarkdownFindContext } from "./chat/markdownFindContext";
13
import { useThreadFindHighlights } from "./chat/threadFindHighlights";
14
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
15
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
+
26
// Atoms derived from the server config run in the real registry over a missing config.
27
vi.mock(import("../state/server"), async (original) => {
28
const actual = await original();
@@ -47,6 +60,8 @@ import ChatMarkdown from "./ChatMarkdown";
60
const roots: Root[] = [];
61
62
beforeEach(() => {
63
+ workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
64
+ filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
65
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
66
});
67
@@ -400,6 +415,165 @@ describe("ChatMarkdown skill chips", () => {
415
});
416
});
417
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
+
577
describe("ChatMarkdown file citations", () => {
578
it.each([true, false])(
579
"renders Codex file citations as file chips with parseRawHtml=%s",
apps/web/src/components/ChatMarkdown.tsx
+43
-17
@@ -11,7 +11,7 @@ import {
11
extractMarkdownLinkHrefs,
12
inlineCodeFilePathCandidate,
13
} from "@t3tools/shared/markdownLinks";
14
-import { isAbsolutePath } from "@t3tools/shared/path";
14
+import { isAbsolutePath, resolveWorkspaceFilePath } from "@t3tools/shared/path";
15
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
16
import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
17
import {
@@ -195,10 +195,13 @@ import { previewEnvironment } from "../state/preview";
195
import { useAtomCommand } from "../state/use-atom-command";
196
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
197
import { projectEnvironment } from "../state/projects";
198
+import { filesystemEnvironment } from "../state/filesystem";
199
import {
200
claimWorkspaceBasenameLookup,
201
needsWorkspaceBasenameLookup,
202
+ pickStrippedWorkspaceMatch,
203
pickWorkspaceBasenameMatch,
204
+ stripRepeatedWorkspacePrefix,
205
WORKSPACE_BASENAME_LOOKUP_LIMIT,
206
} from "../workspaceBasenameLookup";
207
import {
@@ -2386,6 +2389,10 @@ function useChatMarkdownState({
2389
const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {
2390
reportFailure: false,
2391
});
2392
+ const getFilesystemMetadata = useAtomQueryRunner(filesystemEnvironment.getMetadata, {
2393
+ reportFailure: false,
2394
+ refresh: true,
2395
+ });
2396
const openPreview = useAtomCommand(previewEnvironment.open, {
2397
reportFailure: false,
2398
});
@@ -2609,49 +2616,68 @@ function useChatMarkdownState({
2616
openPreview,
2617
});
2618
};
2612
- const findWorkspaceBasenameMatch = async (workspaceRelativePath: string) => {
2619
+ const findWorkspaceFileMatch = async (fileLinkMeta: MarkdownFileLinkMeta) => {
2620
+ const workspaceRelativePath = fileLinkMeta.workspaceLookupPath;
2621
if (
2622
+ !workspaceRelativePath ||
2623
!cwd ||
2624
environmentId === null ||
2616
- !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||
2617
- !needsWorkspaceBasenameLookup(workspaceRelativePath)
2625
+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope)
2626
) {
2627
return null;
2628
}
2629
+ const isBasename = needsWorkspaceBasenameLookup(workspaceRelativePath);
2630
+ const strippedPath = isBasename
2631
+ ? null
2632
+ : stripRepeatedWorkspacePrefix(workspaceRelativePath, cwd);
2633
+ if (!isBasename && strippedPath === null) return null;
2634
const result = await searchProjectEntries({
2635
environmentId,
2636
input: {
2637
cwd,
2625
- query: workspaceRelativePath,
2638
+ query: strippedPath ?? workspaceRelativePath,
2639
limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,
2640
kind: "file",
2641
},
2642
});
2630
- return result._tag === "Success"
2631
- ? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)
2632
- : null;
2643
+ if (result._tag !== "Success") return null;
2644
+ if (strippedPath === null) {
2645
+ return pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries);
2646
+ }
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;
2656
};
2634
- const openFileInPanel = (panelPath: string, line: number | undefined) => {
2657
+ const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
2658
if (!threadRef) return;
2659
// Claimed on every open so a synchronous one supersedes a lookup already
2660
// in flight.
2661
const isLatestLookup = claimWorkspaceBasenameLookup();
2639
- const openAt = (path: string) => useRightPanelStore.getState().openFile(threadRef, path, line);
2640
- if (!cwd || !needsWorkspaceBasenameLookup(panelPath)) {
2662
+ const openAt = (path: string) =>
2663
+ useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line);
2664
+ if (
2665
+ fileLinkMeta.workspaceLookupPath === null ||
2666
+ !cwd ||
2667
+ (!needsWorkspaceBasenameLookup(panelPath) &&
2668
+ stripRepeatedWorkspacePrefix(panelPath, cwd) === null)
2669
+ ) {
2670
openAt(panelPath);
2671
return;
2672
}
2673
void (async () => {
2645
- const match = await findWorkspaceBasenameMatch(panelPath);
2674
+ const match = await findWorkspaceFileMatch(fileLinkMeta);
2675
if (!isLatestLookup()) return;
2676
openAt(match ?? panelPath);
2677
})();
2678
};
2679
const revealMarkdownFileInFileManager = async (fileLinkMeta: MarkdownFileLinkMeta) => {
2651
- const workspaceRelativePath = fileLinkMeta.workspaceRelativePath;
2652
- const match = workspaceRelativePath
2653
- ? await findWorkspaceBasenameMatch(workspaceRelativePath)
2654
- : null;
2680
+ const match = await findWorkspaceFileMatch(fileLinkMeta);
2681
const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;
2682
return revealFileInFileManager(filePath);
2683
};
@@ -2690,7 +2716,7 @@ function useChatMarkdownState({
2716
theme={resolvedTheme}
2717
threadRef={threadRef}
2718
{...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}
2693
- onOpenInPanel={openFileInPanel}
2719
+ onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)}
2720
onOpenMedia={
2721
threadRef && canPreviewMedia
2722
? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)
apps/web/src/markdown-links.ts
+15
-3
@@ -1,8 +1,9 @@
1
-import { fileBasename, workspaceRelativeFilePath } from "@t3tools/shared/path";
1
+import { fileBasename, isAbsolutePath, workspaceRelativeFilePath } from "@t3tools/shared/path";
2
import {
3
inlineCodeFilePathCandidate,
4
isRelativeFilePath,
5
normalizeMarkdownLinkDestination,
6
+ parseMarkdownFileLink,
7
resolveMarkdownFileLinkTarget,
8
} from "@t3tools/shared/markdownLinks";
9
import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";
@@ -12,6 +13,7 @@ import { isTerminalLinkActivation } from "./terminal-links";
13
14
export interface MarkdownFileLinkMeta {
15
filePath: string;
16
+ workspaceLookupPath: string | null;
17
targetPath: string;
18
displayPath: string;
19
workspaceRelativePath: string | null;
@@ -70,10 +72,20 @@ export function resolveMarkdownFileLinkMeta(
72
): MarkdownFileLinkMeta | null {
73
const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
74
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
+ };
86
}
87
76
-function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
88
+function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) {
89
const { path, line, column } = splitFilePathPosition(targetPath);
90
return {
91
filePath: path,
apps/web/src/workspaceBasenameLookup.ts
+33
@@ -1,3 +1,5 @@
1
+import { isAbsolutePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
2
+
3
export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;
4
5
// One counter for every caller: they all open the same panel, so the newest
@@ -46,3 +48,34 @@ export function pickWorkspaceBasenameMatch(
48
);
49
return foldedMatches.length === 1 ? (foldedMatches[0]?.path ?? null) : null;
50
}
51
+
52
+// Repository-relative paths can repeat the project's suffix in subfolder projects.
53
+export function stripRepeatedWorkspacePrefix(relativePath: string, cwd: string): string | null {
54
+ if (isAbsolutePath(relativePath)) return null;
55
+ const pathSegments = relativePath.split(/[\\/]+/);
56
+ const cwdSegments = cwd.split(/[\\/]+/).filter(Boolean);
57
+ const fold = isWindowsAbsolutePath(cwd)
58
+ ? (segment: string | undefined) => segment?.toLowerCase()
59
+ : (segment: string | undefined) => segment;
60
+ for (let count = Math.min(cwdSegments.length, pathSegments.length - 1); count > 0; count--) {
61
+ const prefix = cwdSegments.slice(-count);
62
+ if (prefix.every((segment, index) => fold(segment) === fold(pathSegments[index]))) {
63
+ return pathSegments.slice(count).join("/") || null;
64
+ }
65
+ }
66
+ return null;
67
+}
68
+
69
+export function pickStrippedWorkspaceMatch(
70
+ strippedPath: string,
71
+ cwd: string,
72
+ entries: ReadonlyArray<WorkspaceEntryCandidate>,
73
+): string | null {
74
+ const caseInsensitive = isWindowsAbsolutePath(cwd);
75
+ const key = (path: string) => {
76
+ const normalized = path.replaceAll("\\", "/");
77
+ return caseInsensitive ? normalized.toLowerCase() : normalized;
78
+ };
79
+ const files = entries.filter((entry) => entry.kind === "file");
80
+ return files.find((entry) => key(entry.path) === key(strippedPath))?.path ?? null;
81
+}
packages/client-runtime/src/state/filesystem.ts
+4
@@ -115,6 +115,10 @@ export function createFilesystemEnvironmentAtoms<R, E>(
115
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
116
) {
117
return {
118
+ getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {
119
+ label: "environment-data:filesystem:get-metadata",
120
+ tag: WS_METHODS.filesystemGetMetadata,
121
+ }),
122
browse: createEnvironmentRpcQueryAtomFamily(runtime, {
123
label: "environment-data:filesystem:browse",
124
tag: WS_METHODS.filesystemBrowse,