Skip to content
TypeScript

fix(web): folder links from chat open the file tree instead of a broken preview (#10909)

pcstyle886c83450797
diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx
index 750fa3c7d19..3703025cdcd 100644
--- a/apps/web/src/components/files/FileBrowserPanel.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.tsx
@@ -31,7 +31,7 @@ interface FileBrowserPanelProps {
environmentId: EnvironmentId;
cwd: string;
projectName: string;
- /** File currently open in the preview pane; revealed and selected in the tree. */
+ /** Entry currently open in the surface; revealed and selected in the tree. A directory is expanded. */
selectedPath: string | null;
/** Bumped when the same path should be revealed again (e.g. re-opened from search). */
selectedPathRevealId: number;
@@ -376,7 +376,10 @@ export default function FileBrowserPanel({
handledRevealRef.current = null;
return;
}
- if (entryKinds.get(selectedPath) !== "file") {
+ const selectedKind = entryKinds.get(selectedPath);
+ // An unloaded entry has no row to reveal yet; folders do, and chat links can
+ // point at them.
+ if (selectedKind === undefined) {
handledRevealRef.current = null;
return;
}
@@ -390,7 +393,9 @@ export default function FileBrowserPanel({
) {
return;
}
- const selectedItem = model.getItem(selectedPath);
+ // Directory rows are registered with a trailing slash (see treePath).
+ const selectedTreePath = selectedKind === "directory" ? `${selectedPath}/` : selectedPath;
+ const selectedItem = model.getItem(selectedTreePath);
if (!selectedItem) return;
// A selection that originated inside the tree (clicking a row, possibly
@@ -425,8 +430,12 @@ export default function FileBrowserPanel({
if (item && "expand" in item) item.expand();
}
+ if ("expand" in selectedItem) selectedItem.expand();
selectedItem.select();
- model.scrollToPath(selectedPath, { focus: true, offset: "center" });
+ model.scrollToPath(selectedTreePath, {
+ focus: true,
+ offset: "center",
+ });
queueMicrotask(() => {
syncingSelectionRef.current = false;
});
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index 37228d69ce5..1d89d58bc67 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -941,15 +941,22 @@ export default function FilePreviewPanel({
// A file outside the workspace (an absolute path) is shown, never edited.
const isHostFile =
attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
- const file = useProjectFileQuery(
- environmentId,
- cwd,
- relativePath,
- attachment === undefined && !isMedia && !isPdf,
- );
+ // Media and PDFs render from their absolute path, so their contents are never
+ // shown. The read still runs: a folder named `assets.png` is only knowable as a
+ // folder from the read failure, and the server stats before reading, so a folder
+ // costs an open and a stat and returns no body.
+ const file = useProjectFileQuery(environmentId, cwd, relativePath, attachment === undefined);
+ // A chat link cannot tell a folder from a file, so a folder arrives here as
+ // a file surface and the read fails. Keep the breadcrumbs, drop the preview
+ // pane, and let the tree fill the surface with the folder revealed. Mutation
+ // refresh stays on so the surface notices if the path becomes a file. A host
+ // path cannot be revealed in the workspace tree, so it keeps the read error.
+ const isDirectory = file.isNotFile && !isHostFile;
+ // Everything preview-related keys off previewPath; a folder has no preview.
+ const previewPath = isDirectory ? null : relativePath;
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const showExplorer = shouldShowFileExplorer({
- relativePath,
+ relativePath: previewPath,
explorerOpen,
attachmentOpen: attachment !== undefined,
});
@@ -977,9 +984,9 @@ export default function FilePreviewPanel({
null,
);
const breadcrumbRef = useRef<HTMLDivElement>(null);
- const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false;
+ const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
const tableDelimiter =
- relativePath && attachment === undefined ? filePreviewDelimiter({ name: relativePath }) : null;
+ previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
// A reveal still wins over the preference: the line only exists in the source.
const revealHandled =
revealLine === null ||
@@ -994,12 +1001,13 @@ export default function FilePreviewPanel({
: isHtml
? ("html" as const)
: null;
- const canToggleRendered = attachment === undefined && renderedMode !== null;
+ const canToggleRendered =
+ previewPath !== null && attachment === undefined && renderedMode !== null;
const updateClientSettings = useUpdateClientSettings();
// Word wrap only reaches the text bodies. A rendered Markdown document, a table and the
// browser frame all lay themselves out, so the toggle stays hidden rather than inert.
const showsRawText =
- relativePath !== null &&
+ previewPath !== null &&
file.data !== null &&
!(isMarkdown && renderMarkdown) &&
!(tableDelimiter && renderTable) &&
@@ -1011,11 +1019,11 @@ export default function FilePreviewPanel({
? setRenderTablePreferred
: setRenderBrowserFilePreferred;
const canOpenInBrowser =
- relativePath !== null &&
+ previewPath !== null &&
attachment === undefined &&
!isVideo &&
isPreviewSupportedInRuntime() &&
- isBrowserPreviewFile(relativePath);
+ isBrowserPreviewFile(previewPath);
const absolutePath =
relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
@@ -1023,8 +1031,10 @@ export default function FilePreviewPanel({
enabled:
attachment === undefined &&
relativePath !== null &&
- !isMedia &&
- !isPdf &&
+ // Media and PDFs never show their contents, so re-reading them on every
+ // workspace mutation is waste. A folder named like one still re-reads, so
+ // it notices when the path becomes a file.
+ (isDirectory || (!isMedia && !isPdf)) &&
!selectedFilePending,
mutationId: workspaceMutationId,
refresh: file.refresh,
@@ -1145,7 +1155,7 @@ export default function FilePreviewPanel({
<Globe2 className="size-3.5" />
</FileSurfaceAction>
) : null}
- {!isHostFile ? (
+ {!isHostFile && previewPath !== null ? (
<FileSurfaceAction
label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
pressed={explorerOpen}
@@ -1156,7 +1166,7 @@ export default function FilePreviewPanel({
) : null}
</div>
) : null}
- {relativePath &&
+ {previewPath &&
attachment === undefined &&
!isMedia &&
!renderBrowserFile &&
@@ -1167,12 +1177,9 @@ export default function FilePreviewPanel({
) : null}
<div className="flex min-h-0 flex-1 overflow-hidden">
<div
- className={cn(
- "min-w-0 flex-1 flex-col overflow-hidden",
- relativePath ? "flex" : "hidden",
- )}
+ className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
>
- {relativePath && attachment ? (
+ {isDirectory ? null : relativePath && attachment ? (
<AttachmentFilePreview
key={`${environmentId}:${attachment.id}`}
name={attachment.name}
@@ -1279,7 +1286,7 @@ export default function FilePreviewPanel({
<aside
className={cn(
"flex min-h-0 shrink-0 bg-background",
- relativePath
+ previewPath
? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
: "min-w-0 flex-1",
)}
@@ -1293,7 +1300,7 @@ export default function FilePreviewPanel({
selectedPathRevealId={revealRequestId}
onOpenFile={onOpenFile}
workspaceMutationId={workspaceMutationId}
- {...(relativePath && !isMedia && !isPdf
+ {...(previewPath && !isMedia && !isPdf
? { onRefreshSelectedFile: file.refresh }
: {})}
/>
diff --git a/apps/web/src/components/files/projectFilesQueryState.test.tsx b/apps/web/src/components/files/projectFilesQueryState.test.tsx
index 8edf982a030..8ac6f4e1cd2 100644
--- a/apps/web/src/components/files/projectFilesQueryState.test.tsx
+++ b/apps/web/src/components/files/projectFilesQueryState.test.tsx
@@ -1,6 +1,7 @@
import {
EnvironmentId,
type ProjectListEntriesResult,
+ ProjectReadFileError,
type ProjectReadFileResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -250,4 +251,62 @@ describe("project query refresh", () => {
atomHooks.registry = null;
}
});
+
+ it("reports a directory named like an image as not a file", async () => {
+ const readAtom = Atom.make(
+ Effect.fail(
+ new ProjectReadFileError({
+ cwd: "/repo",
+ relativePath: "assets.png",
+ failure: "path_not_file",
+ }),
+ ),
+ );
+ const registry = AtomRegistry.make();
+ const unmount = registry.mount(readAtom);
+ projectMocks.readFile.mockReturnValue(readAtom);
+ projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
+ atomHooks.registry = registry;
+
+ try {
+ await flushEffects();
+ reactHooks.beginRender();
+ const query = useProjectFileQuery(environmentId, "/repo", "assets.png");
+ expect(query.isNotFile).toBe(true);
+ expect(query.data).toBeNull();
+ } finally {
+ unmount();
+ registry.dispose();
+ atomHooks.registry = null;
+ }
+ });
+
+ it("reports a directory read as not a file", async () => {
+ const readAtom = Atom.make(
+ Effect.fail(
+ new ProjectReadFileError({
+ cwd: "/repo",
+ relativePath: ".agents/skills",
+ failure: "path_not_file",
+ }),
+ ),
+ );
+ const registry = AtomRegistry.make();
+ const unmount = registry.mount(readAtom);
+ projectMocks.readFile.mockReturnValue(readAtom);
+ projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
+ atomHooks.registry = registry;
+
+ try {
+ await flushEffects();
+ reactHooks.beginRender();
+ const query = useProjectFileQuery(environmentId, "/repo", ".agents/skills");
+ expect(query.isNotFile).toBe(true);
+ expect(query.data).toBeNull();
+ } finally {
+ unmount();
+ registry.dispose();
+ atomHooks.registry = null;
+ }
+ });
});
diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts
index 4129ac038c3..b9a88030183 100644
--- a/apps/web/src/components/files/projectFilesQueryState.ts
+++ b/apps/web/src/components/files/projectFilesQueryState.ts
@@ -1,15 +1,13 @@
import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
-import type {
- EnvironmentId,
- ProjectListEntriesResult,
- ProjectReadFileResult,
-} from "@t3tools/contracts";
import {
- isWorkspaceImagePreviewPath,
- isWorkspaceVideoPreviewPath,
-} from "@t3tools/shared/filePreview";
+ type EnvironmentId,
+ type ProjectListEntriesResult,
+ ProjectReadFileError,
+ type ProjectReadFileResult,
+} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
@@ -33,6 +31,11 @@ interface ProjectQueryState<A> {
readonly refresh: () => void;
}
+interface ProjectFileQueryState extends ProjectQueryState<ProjectReadFileResult> {
+ /** The path exists but is not a regular file, typically a directory. */
+ readonly isNotFile: boolean;
+}
+
function getProjectEntriesQueryAtom(
environmentId: EnvironmentId,
cwd: string,
@@ -126,12 +129,17 @@ export function clearProjectFileQueryData(
appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), null);
}
-function errorMessage<A>(result: AsyncResult.AsyncResult<A, unknown>): string | null {
- if (result._tag !== "Failure") return null;
- const cause = Cause.squash(result.cause);
+function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
+ return result._tag === "Failure" ? Cause.squash(result.cause) : null;
+}
+
+function errorMessage(cause: unknown): string | null {
+ if (cause === null) return null;
return cause instanceof Error ? cause.message : "Workspace query failed.";
}
+const isProjectReadFileError = Schema.is(ProjectReadFileError);
+
export function useProjectEntriesQuery(
environmentId: EnvironmentId,
cwd: string,
@@ -143,7 +151,7 @@ export function useProjectEntriesQuery(
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
return {
data: Option.getOrNull(AsyncResult.value(result)),
- error: errorMessage(result),
+ error: errorMessage(failureCause(result)),
isPending: result.waiting,
refresh,
};
@@ -189,14 +197,12 @@ export function useProjectFileQuery(
cwd: string,
relativePath: string | null,
enabled = true,
-): ProjectQueryState<ProjectReadFileResult> {
- const isMedia =
- relativePath !== null &&
- (isWorkspaceImagePreviewPath(relativePath) || isWorkspaceVideoPreviewPath(relativePath));
- const atom =
- enabled && !isMedia
- ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
- : EMPTY_PROJECT_FILE_QUERY_ATOM;
+): ProjectFileQueryState {
+ // The caller decides what to read. A media path is not skipped here: a folder
+ // named `assets.png` is only knowable as a folder from the read failure.
+ const atom = enabled
+ ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
+ : EMPTY_PROJECT_FILE_QUERY_ATOM;
const result = useAtomValue(atom);
const refreshAtom = useAtomRefresh(atom);
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
@@ -205,10 +211,12 @@ export function useProjectFileQuery(
optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
);
const optimisticFile = relativePath === null ? null : optimisticResult;
+ const cause = failureCause(result);
return {
data: optimisticFile?.data ?? data,
- error: errorMessage(result),
+ error: errorMessage(cause),
+ isNotFile: isProjectReadFileError(cause) && cause.failure === "path_not_file",
isPending: result.waiting,
refresh,
};
diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts
index 6f8a104e9f0..151c1699cbf 100644
--- a/apps/web/src/rightPanelStore.test.ts
+++ b/apps/web/src/rightPanelStore.test.ts
@@ -475,6 +475,36 @@ describe("rightPanelStore", () => {
});
});
+ it.each([
+ ["generated\\", "generated"],
+ ["notes/meeting ", "notes/meeting"],
+ [" notes/meeting", "notes/meeting"],
+ ])("keeps %j and %j in separate file tabs", (firstPath, secondPath) => {
+ useRightPanelStore.getState().openFile(refA, firstPath);
+ useRightPanelStore.getState().openFile(refA, secondPath);
+
+ expect(
+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
+ ).toMatchObject([
+ { id: `file:${firstPath}`, relativePath: firstPath },
+ { id: `file:${secondPath}`, relativePath: secondPath },
+ ]);
+ });
+
+ it.each([
+ ["docs/", "docs"],
+ ["docs///", "docs"],
+ ["/", "/"],
+ ["C:/", "C:/"],
+ ])("reuses the folder tab for %j and %j", (linkPath, treePath) => {
+ useRightPanelStore.getState().openFile(refA, linkPath);
+ useRightPanelStore.getState().openFile(refA, treePath);
+
+ expect(
+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
+ ).toMatchObject([{ id: `file:${treePath}`, relativePath: treePath, revealRequestId: 2 }]);
+ });
+
it("opens an attachment as a file surface without the standalone explorer", () => {
const attachment = {
type: "file" as const,
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
index 69b803bcd9c..f020f14466b 100644
--- a/apps/web/src/rightPanelStore.ts
+++ b/apps/web/src/rightPanelStore.ts
@@ -575,9 +575,13 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: next;
}),
),
- openFile: (ref, relativePath, line) =>
+ openFile: (ref, requestedPath, line) =>
set((state) =>
userAction(state, scopedThreadKey(ref), (current) => {
+ // Workspace entry paths use '/', including on Windows.
+ const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
+ ? requestedPath
+ : requestedPath.replace(/\/+$/, "") || requestedPath;
const withoutStandaloneExplorer = current.surfaces.filter(
(surface) => surface.kind !== "files",
);