Skip to content

Commit 82dcfa7

Browse files
Cache workspace file queries in shared query state
- Move file tree and preview loading onto SWR atoms - Preserve cached entries during refresh and add file icon parity
1 parent e18504c commit 82dcfa7

6 files changed

Lines changed: 270 additions & 110 deletions

File tree

‎apps/web/src/components/ChatView.browser.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2181,6 +2181,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
21812181
1,
21822182
);
21832183

2184+
useRightPanelStore.getState().openFile(THREAD_REF, "components.json");
2185+
const fileTabIcon = await waitForElement(
2186+
() =>
2187+
document.querySelector<SVGElement>(
2188+
'[data-right-panel-tabbar] [data-pierre-icon][data-icon-token="json"]',
2189+
),
2190+
"Unable to find the Pierre file icon in the file tab.",
2191+
);
2192+
expect(fileTabIcon.closest("button")?.textContent).toContain("components.json");
2193+
21842194
document.documentElement.classList.add("wco");
21852195
expect(rightPanelTabbar.getBoundingClientRect().height).toBe(
21862196
panelLayoutControls.getBoundingClientRect().height,

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

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
11
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
22
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
3-
import {
4-
ClipboardList,
5-
FileCode2,
6-
FileDiff,
7-
Files,
8-
Globe2,
9-
Plus,
10-
TerminalSquare,
11-
X,
12-
} from "lucide-react";
3+
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
134
import { type ReactNode, useState } from "react";
145

156
import { isElectron } from "~/env";
@@ -18,8 +9,10 @@ import { cn } from "~/lib/utils";
189
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
1910
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
2011
import { faviconUrlForOrigin } from "~/lib/favicon";
12+
import { useTheme } from "~/hooks/useTheme";
2113

2214
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
15+
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
2316

2417
interface RightPanelTabsProps {
2518
mode: PreviewPanelMode;
@@ -165,9 +158,11 @@ function PreviewFavicon({ url }: { url: string | null }) {
165158
function SurfaceIcon({
166159
surface,
167160
sessions,
161+
theme,
168162
}: {
169163
surface: RightPanelSurface;
170164
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
165+
theme: "light" | "dark";
171166
}) {
172167
switch (surface.kind) {
173168
case "preview": {
@@ -180,7 +175,14 @@ function SurfaceIcon({
180175
case "files":
181176
return <Files className="size-3.5 shrink-0" />;
182177
case "file":
183-
return <FileCode2 className="size-3.5 shrink-0" />;
178+
return (
179+
<PierreEntryIcon
180+
pathValue={surface.relativePath}
181+
kind="file"
182+
theme={theme}
183+
className="size-3.5"
184+
/>
185+
);
184186
case "terminal":
185187
return <TerminalSquare className="size-3.5 shrink-0" />;
186188
case "plan":
@@ -190,6 +192,7 @@ function SurfaceIcon({
190192

191193
export function RightPanelTabs(props: RightPanelTabsProps) {
192194
const ownsDesktopTitleBar = isElectron && props.mode === "inline";
195+
const { resolvedTheme } = useTheme();
193196

194197
return (
195198
<PreviewPanelShell
@@ -227,7 +230,11 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
227230
className="flex min-w-0 flex-1 items-center gap-1.5"
228231
onClick={() => props.onActivate(surface)}
229232
>
230-
<SurfaceIcon surface={surface} sessions={props.previewSessions} />
233+
<SurfaceIcon
234+
surface={surface}
235+
sessions={props.previewSessions}
236+
theme={resolvedTheme}
237+
/>
231238
<span className="truncate">{title}</span>
232239
</button>
233240
}

‎apps/web/src/components/files/FileBrowserPanel.tsx‎

Lines changed: 25 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
22
import { FileTree, useFileTree } from "@pierre/trees/react";
33
import { RefreshCw, Search } from "lucide-react";
4-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4+
import { useEffect, useMemo, useRef } from "react";
55

6-
import { readEnvironmentApi } from "~/environmentApi";
76
import { useTheme } from "~/hooks/useTheme";
87
import { cn } from "~/lib/utils";
98
import { T3_PIERRE_ICONS } from "~/pierre-icons";
109

10+
import { useProjectEntriesQuery } from "./projectFilesQueryState";
11+
1112
interface FileBrowserPanelProps {
1213
environmentId: EnvironmentId;
1314
cwd: string;
@@ -38,12 +39,15 @@ export default function FileBrowserPanel({
3839
onOpenFile,
3940
}: FileBrowserPanelProps) {
4041
const { resolvedTheme } = useTheme();
41-
const [entries, setEntries] = useState<readonly ProjectEntry[]>([]);
42-
const [entriesError, setEntriesError] = useState<string | null>(null);
43-
const [isLoadingEntries, setIsLoadingEntries] = useState(true);
44-
const [isTruncated, setIsTruncated] = useState(false);
45-
const entryKindsRef = useRef(new Map<string, ProjectEntry["kind"]>());
46-
const requestGenerationRef = useRef(0);
42+
const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
43+
const entries = entriesQuery.data?.entries ?? [];
44+
const entryKinds = useMemo(
45+
() => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
46+
[entries],
47+
);
48+
const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
49+
const treePaths = useMemo(() => entries.map(treePath), [entries]);
50+
const previousTreePathsRef = useRef<readonly string[]>([]);
4751

4852
const { model } = useFileTree({
4953
density: "compact",
@@ -62,44 +66,12 @@ export default function FileBrowserPanel({
6266
unsafeCSS: TREE_UNSAFE_CSS,
6367
});
6468

65-
const loadEntries = useCallback(() => {
66-
const api = readEnvironmentApi(environmentId);
67-
requestGenerationRef.current += 1;
68-
const generation = requestGenerationRef.current;
69-
setIsLoadingEntries(true);
70-
setEntriesError(null);
71-
72-
if (!api) {
73-
setEntriesError("Environment is not connected.");
74-
setIsLoadingEntries(false);
75-
return;
76-
}
77-
78-
void api.projects.listEntries({ cwd }).then(
79-
(result) => {
80-
if (generation !== requestGenerationRef.current) return;
81-
entryKindsRef.current = new Map(
82-
result.entries.map((entry) => [entry.path, entry.kind] as const),
83-
);
84-
setEntries(result.entries);
85-
setIsTruncated(result.truncated);
86-
model.resetPaths(result.entries.map(treePath));
87-
setIsLoadingEntries(false);
88-
},
89-
(error: unknown) => {
90-
if (generation !== requestGenerationRef.current) return;
91-
setEntriesError(error instanceof Error ? error.message : String(error));
92-
setIsLoadingEntries(false);
93-
},
94-
);
95-
}, [cwd, environmentId, model]);
96-
9769
useEffect(() => {
98-
loadEntries();
99-
return () => {
100-
requestGenerationRef.current += 1;
101-
};
102-
}, [loadEntries]);
70+
if (previousTreePathsRef.current === treePaths) return;
71+
entryKindsRef.current = entryKinds;
72+
previousTreePathsRef.current = treePaths;
73+
model.resetPaths(treePaths);
74+
}, [entryKinds, model, treePaths]);
10375

10476
const fileCount = useMemo(
10577
() => entries.reduce((count, entry) => count + (entry.kind === "file" ? 1 : 0), 0),
@@ -112,8 +84,10 @@ export default function FileBrowserPanel({
11284
<div className="min-w-0 flex-1">
11385
<div className="truncate text-xs font-medium text-foreground">{projectName}</div>
11486
<div className="truncate text-[10px] leading-none text-muted-foreground">
115-
{isLoadingEntries ? "Indexing…" : `${fileCount.toLocaleString()} files`}
116-
{isTruncated ? " · partial" : ""}
87+
{entriesQuery.isPending && entriesQuery.data === null
88+
? "Indexing…"
89+
: `${fileCount.toLocaleString()} files`}
90+
{entriesQuery.data?.truncated ? " · partial" : ""}
11791
</div>
11892
</div>
11993
<button
@@ -128,13 +102,13 @@ export default function FileBrowserPanel({
128102
type="button"
129103
className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
130104
aria-label="Refresh workspace files"
131-
onClick={loadEntries}
105+
onClick={entriesQuery.refresh}
132106
>
133-
<RefreshCw className={cn("size-3.5", isLoadingEntries && "animate-spin")} />
107+
<RefreshCw className={cn("size-3.5", entriesQuery.isPending && "animate-spin")} />
134108
</button>
135109
</div>
136-
{entriesError ? (
137-
<div className="p-4 text-xs leading-relaxed text-destructive">{entriesError}</div>
110+
{entriesQuery.error && entriesQuery.data === null ? (
111+
<div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
138112
) : (
139113
<FileTree
140114
model={model}

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 12 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
1-
import type { EnvironmentId, ProjectReadFileResult } from "@t3tools/contracts";
1+
import type { EnvironmentId } from "@t3tools/contracts";
22
import { File } from "@pierre/diffs/react";
33
import { ChevronRight, FolderTree, LoaderCircle } from "lucide-react";
4-
import { useEffect, useMemo, useState } from "react";
4+
import { useMemo, useState } from "react";
55

6-
import { readEnvironmentApi } from "~/environmentApi";
76
import { useTheme } from "~/hooks/useTheme";
87
import { resolveDiffThemeName } from "~/lib/diffRendering";
98
import { cn } from "~/lib/utils";
109
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
1110

1211
import FileBrowserPanel from "./FileBrowserPanel";
1312
import { fileBreadcrumbs } from "./filePath";
14-
15-
type FileLoadState =
16-
| { status: "loading" }
17-
| { status: "loaded"; result: ProjectReadFileResult }
18-
| { status: "error"; message: string };
13+
import { useProjectFileQuery } from "./projectFilesQueryState";
1914

2015
interface FilePreviewPanelProps {
2116
environmentId: EnvironmentId;
@@ -43,7 +38,7 @@ export default function FilePreviewPanel({
4338
onOpenFile,
4439
}: FilePreviewPanelProps) {
4540
const { resolvedTheme } = useTheme();
46-
const [file, setFile] = useState<FileLoadState>({ status: "loading" });
41+
const file = useProjectFileQuery(environmentId, cwd, relativePath);
4742
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
4843
const breadcrumbs = useMemo(
4944
() => fileBreadcrumbs(projectName, relativePath),
@@ -60,35 +55,6 @@ export default function FilePreviewPanel({
6055
});
6156
};
6257

63-
useEffect(() => {
64-
let active = true;
65-
const api = readEnvironmentApi(environmentId);
66-
setFile({ status: "loading" });
67-
if (!api) {
68-
setFile({ status: "error", message: "Environment is not connected." });
69-
return () => {
70-
active = false;
71-
};
72-
}
73-
74-
void api.projects.readFile({ cwd, relativePath }).then(
75-
(result) => {
76-
if (active) setFile({ status: "loaded", result });
77-
},
78-
(error: unknown) => {
79-
if (!active) return;
80-
setFile({
81-
status: "error",
82-
message: error instanceof Error ? error.message : String(error),
83-
});
84-
},
85-
);
86-
87-
return () => {
88-
active = false;
89-
};
90-
}, [cwd, environmentId, relativePath]);
91-
9258
return (
9359
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
9460
<div className="flex h-11 shrink-0 items-center gap-2 border-y border-border/60 px-3">
@@ -130,30 +96,29 @@ export default function FilePreviewPanel({
13096
<TooltipPopup>{explorerOpen ? "Hide file explorer" : "Show file explorer"}</TooltipPopup>
13197
</Tooltip>
13298
</div>
133-
{file.status === "loaded" && file.result.truncated ? (
99+
{file.data?.truncated ? (
134100
<div className="shrink-0 border-b border-amber-500/20 bg-amber-500/8 px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-300">
135-
Preview limited to the first 1 MB of a {file.result.byteLength.toLocaleString()} byte
136-
file.
101+
Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
137102
</div>
138103
) : null}
139104
<div className="flex min-h-0 flex-1 overflow-hidden">
140105
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
141-
{file.status === "error" ? (
106+
{file.error && file.data === null ? (
142107
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
143-
{file.message}
108+
{file.error}
144109
</div>
145-
) : file.status === "loading" ? (
110+
) : file.data === null ? (
146111
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
147112
<LoaderCircle className="size-5 animate-spin" />
148113
</div>
149114
) : (
150115
<File
151-
key={`${relativePath}:${resolvedTheme}:${file.result.byteLength}`}
116+
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
152117
disableWorkerPool
153118
file={{
154119
name: relativePath,
155-
contents: file.result.contents,
156-
cacheKey: `${cwd}:${relativePath}:${file.result.byteLength}`,
120+
contents: file.data.contents,
121+
cacheKey: `${cwd}:${relativePath}:${file.data.byteLength}`,
157122
}}
158123
options={{
159124
disableFileHeader: true,
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import type { EnvironmentApi, ProjectListEntriesResult } from "@t3tools/contracts";
2+
import { EnvironmentId } from "@t3tools/contracts";
3+
import * as Option from "effect/Option";
4+
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
5+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6+
7+
import {
8+
__resetEnvironmentApiOverridesForTests,
9+
__setEnvironmentApiOverrideForTests,
10+
} from "~/environmentApi";
11+
12+
import { getProjectEntriesQueryAtom } from "./projectFilesQueryState";
13+
14+
const environmentId = EnvironmentId.make("environment-project-files-query-test");
15+
16+
function deferred<A>() {
17+
let resolve!: (value: A) => void;
18+
const promise = new Promise<A>((resolvePromise) => {
19+
resolve = resolvePromise;
20+
});
21+
return { promise, resolve };
22+
}
23+
24+
describe("project files queries", () => {
25+
afterEach(() => {
26+
__resetEnvironmentApiOverridesForTests();
27+
vi.unstubAllGlobals();
28+
});
29+
30+
it("retains cached entries while explicitly revalidating", async () => {
31+
vi.stubGlobal("window", {});
32+
const first = {
33+
entries: [{ path: "README.md", kind: "file" }],
34+
truncated: false,
35+
} satisfies ProjectListEntriesResult;
36+
const second = {
37+
entries: [
38+
{ path: "README.md", kind: "file" },
39+
{ path: "src", kind: "directory" },
40+
],
41+
truncated: false,
42+
} satisfies ProjectListEntriesResult;
43+
const revalidation = deferred<ProjectListEntriesResult>();
44+
const listEntries = vi
45+
.fn<EnvironmentApi["projects"]["listEntries"]>()
46+
.mockResolvedValueOnce(first)
47+
.mockReturnValueOnce(revalidation.promise);
48+
__setEnvironmentApiOverrideForTests(environmentId, {
49+
projects: { listEntries },
50+
} as unknown as EnvironmentApi);
51+
const registry = AtomRegistry.make();
52+
const atom = getProjectEntriesQueryAtom(environmentId, "/repo");
53+
54+
registry.get(atom);
55+
await vi.waitFor(() => {
56+
expect(Option.getOrNull(AsyncResult.value(registry.get(atom)))).toEqual(first);
57+
});
58+
59+
registry.refresh(atom);
60+
await vi.waitFor(() => expect(listEntries).toHaveBeenCalledTimes(2));
61+
const refreshing = registry.get(atom);
62+
expect(refreshing.waiting).toBe(true);
63+
expect(Option.getOrNull(AsyncResult.value(refreshing))).toEqual(first);
64+
65+
revalidation.resolve(second);
66+
await vi.waitFor(() => {
67+
expect(Option.getOrNull(AsyncResult.value(registry.get(atom)))).toEqual(second);
68+
});
69+
registry.dispose();
70+
});
71+
});

0 commit comments

Comments
 (0)