Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โšก๏ธ perf(files-tab): persist the project tree via replica, prefetch while hidden, read git status in parallel (#20842)

Arvin Xu52a077468940
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 48f9b951e9d..5f378a77019 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -136,7 +136,10 @@ export default class GitController extends ControllerModule {
@IpcMethod()
async getGitWorkingTreeFiles(dirPath: string): Promise<GitWorkingTreeFiles> {
const { getGitWorkingTreeFiles: computeGitWorkingTreeFiles } = await loadGit();
- return computeGitWorkingTreeFiles(dirPath);
+ // The renderer persists this overlay. A failed or timed-out `git status`
+ // must reject so the cached markers survive, rather than be reported as a
+ // confirmed clean working tree.
+ return computeGitWorkingTreeFiles(dirPath, { throwOnError: true });
}
@IpcMethod()
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index fbb3ca875a6..0cc1ac7e5a3 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3047,6 +3047,8 @@
"workingPanel.files.noSearchResults": "No matching files",
"workingPanel.files.open": "Open File",
"workingPanel.files.openNeedsTopic": "Send a message first โ€” this environmentโ€™s files open once the conversation has a session.",
+ "workingPanel.files.partialIndexNotice": "Only part of this large project is shown โ€” refresh to load every file",
+ "workingPanel.files.refreshFailed": "Couldn't refresh this view โ€” showing the last saved files",
"workingPanel.files.search": "Search Files",
"workingPanel.files.searchPlaceholder": "Filter files...",
"workingPanel.files.showInReview": "Show in Review",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 440a186ee9b..6d30dff4d6e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3047,6 +3047,8 @@
"workingPanel.files.noSearchResults": "ๆฒกๆœ‰ๅŒน้…็š„ๆ–‡ไปถ",
"workingPanel.files.open": "ๆ‰“ๅผ€ๆ–‡ไปถ",
"workingPanel.files.openNeedsTopic": "ๅ…ˆๅ‘ไธ€ๆกๆถˆๆฏ โ€”โ€” ่ฏฅ็Žฏๅขƒ็š„ๆ–‡ไปถ่ฆๅœจๅฏน่ฏๅปบ็ซ‹ไผš่ฏๅŽๆ‰่ƒฝๆ‰“ๅผ€ใ€‚",
+ "workingPanel.files.partialIndexNotice": "้กน็›ฎ่พƒๅคง๏ผŒๅฝ“ๅ‰ๅชๆ˜พ็คบ้ƒจๅˆ†ๆ–‡ไปถ๏ผŒๅˆทๆ–ฐๅŽๅฏๅŠ ่ฝฝๅ…จ้ƒจๆ–‡ไปถ",
+ "workingPanel.files.refreshFailed": "ๅˆทๆ–ฐๅคฑ่ดฅ๏ผŒๅฝ“ๅ‰ๆ˜พ็คบไธŠๆฌกไฟๅญ˜็š„ๆ–‡ไปถ",
"workingPanel.files.search": "ๆœ็ดขๆ–‡ไปถ",
"workingPanel.files.searchPlaceholder": "็ญ›้€‰ๆ–‡ไปถ...",
"workingPanel.files.showInReview": "ๅœจๅฎกๆŸฅไธญๆŸฅ็œ‹",
diff --git a/packages/local-file-shell/src/git/__tests__/branches.test.ts b/packages/local-file-shell/src/git/__tests__/branches.test.ts
index 202fc4c9d69..82f9a97224a 100644
--- a/packages/local-file-shell/src/git/__tests__/branches.test.ts
+++ b/packages/local-file-shell/src/git/__tests__/branches.test.ts
@@ -250,6 +250,20 @@ describe('working tree status / files / patches', () => {
expect(files.deleted).toEqual([]);
});
+ it('distinguishes a failed git status from a clean tree when asked', async () => {
+ const notRepo = await mkdtemp(path.join(tmpdir(), 'lfs-not-git-'));
+ cleanup.push(notRepo);
+
+ // Default callers keep the tolerant fallback.
+ await expect(getGitWorkingTreeFiles(notRepo)).resolves.toEqual({
+ added: [],
+ deleted: [],
+ modified: [],
+ });
+ // Persisting callers must see the failure instead of a false-clean tree.
+ await expect(getGitWorkingTreeFiles(notRepo, { throwOnError: true })).rejects.toThrow();
+ });
+
it('getGitWorkingTreePatches returns per-file patches ordered added โ†’ modified', async () => {
const { patches } = await getGitWorkingTreePatches(repo);
const byPath = Object.fromEntries(patches.map((p) => [p.filePath, p]));
diff --git a/packages/local-file-shell/src/git/workingTree.ts b/packages/local-file-shell/src/git/workingTree.ts
index 3d8c534b68d..1ebb6e1275a 100644
--- a/packages/local-file-shell/src/git/workingTree.ts
+++ b/packages/local-file-shell/src/git/workingTree.ts
@@ -427,11 +427,24 @@ const listSubmodulePaths = async (dirPath: string): Promise<Set<string>> => {
}
};
+export interface GetGitWorkingTreeFilesOptions {
+ /**
+ * Reject when `git status` fails (including its timeout) instead of
+ * reporting a clean tree. Callers that persist the overlay must set this:
+ * a transient failure otherwise overwrites the saved dirty markers with an
+ * empty result that looks confirmed.
+ */
+ throwOnError?: boolean;
+}
+
/**
* Return dirty file paths bucketed into added / modified / deleted. Uses
* `git status --porcelain -z` so paths are NUL-terminated and never C-quoted.
*/
-export const getGitWorkingTreeFiles = async (dirPath: string): Promise<GitWorkingTreeFiles> => {
+export const getGitWorkingTreeFiles = async (
+ dirPath: string,
+ options: GetGitWorkingTreeFilesOptions = {},
+): Promise<GitWorkingTreeFiles> => {
const added: string[] = [];
const modified: string[] = [];
const deleted: string[] = [];
@@ -464,7 +477,8 @@ export const getGitWorkingTreeFiles = async (dirPath: string): Promise<GitWorkin
}
}
return { added, deleted, modified };
- } catch {
+ } catch (error) {
+ if (options.throwOnError) throw error;
return { added: [], deleted: [], modified: [] };
}
};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 7ce1ee952bc..c52f4fe7ad6 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3671,6 +3671,9 @@ export default {
'workingPanel.files.filters.title': 'Filter Files',
'workingPanel.files.noSearchResults': 'No matching files',
'workingPanel.files.open': 'Open File',
+ 'workingPanel.files.partialIndexNotice':
+ 'Only part of this large project is shown โ€” refresh to load every file',
+ 'workingPanel.files.refreshFailed': "Couldn't refresh this view โ€” showing the last saved files",
'workingPanel.files.search': 'Search Files',
'workingPanel.files.searchPlaceholder': 'Filter files...',
'workingPanel.files.showInReview': 'Show in Review',
diff --git a/src/features/Conversation/WorkingSidebar/DeferredSkeleton.tsx b/src/features/Conversation/WorkingSidebar/DeferredSkeleton.tsx
new file mode 100644
index 00000000000..846c464f795
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/DeferredSkeleton.tsx
@@ -0,0 +1,24 @@
+import { useEffect, useState } from 'react';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+/**
+ * The right panel's placeholder for a tab that has not mounted yet.
+ *
+ * It waits one frame budget before appearing: the Files tab paints its
+ * replica-backed tree within that window, and an immediately rendered
+ * skeleton would flash over the saved tree even though it is ready.
+ */
+const DeferredSkeleton = () => {
+ const [show, setShow] = useState(false);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setShow(true), 150);
+ return () => clearTimeout(timer);
+ }, []);
+
+ if (!show) return null;
+ return <SkeletonList paddingBlock={8} paddingInline={8} rows={6} />;
+};
+
+export default DeferredSkeleton;
diff --git a/src/features/Conversation/WorkingSidebar/Files/FilesPane.tsx b/src/features/Conversation/WorkingSidebar/Files/FilesPane.tsx
new file mode 100644
index 00000000000..f0a8b7d660c
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/FilesPane.tsx
@@ -0,0 +1,71 @@
+import { Flexbox } from '@lobehub/ui';
+import { Activity, memo } from 'react';
+
+import FilesPrefetch from './FilesPrefetch';
+import Files from './index';
+
+interface FilesPaneProps {
+ active: boolean;
+ /** The tab is offered (agent mode) and a directory resolved. */
+ available: boolean;
+ className?: string;
+ contentReady: boolean;
+ deviceId?: string;
+ directory?: string;
+ /** Warm the tree even while the pane itself is hidden or still loading. */
+ prefetch: boolean;
+ sandboxInstanceId?: string;
+ sandboxTopicId?: string;
+}
+
+/**
+ * The Files tab, including its cold-start prefetch.
+ *
+ * The prefetch has to live outside the sidebar's `contentReady` gate: a
+ * collapsed panel keeps the pane mounted but tears down its effects, so the
+ * tree would otherwise be read only after the user opens the tab.
+ */
+const FilesPane = memo<FilesPaneProps>(
+ ({
+ active,
+ available,
+ className,
+ contentReady,
+ deviceId,
+ directory,
+ prefetch,
+ sandboxInstanceId,
+ sandboxTopicId,
+ }) => {
+ if (!available || directory === undefined) return null;
+
+ return (
+ <>
+ {prefetch && (
+ <FilesPrefetch
+ deviceId={deviceId}
+ sandboxInstanceId={sandboxInstanceId}
+ sandboxTopicId={sandboxTopicId}
+ workingDirectory={directory}
+ />
+ )}
+ {contentReady && (
+ <Activity mode={active ? 'visible' : 'hidden'}>
+ <Flexbox className={className}>
+ <Files
+ deviceId={deviceId}
+ sandboxInstanceId={sandboxInstanceId}
+ sandboxTopicId={sandboxTopicId}
+ workingDirectory={directory}
+ />
+ </Flexbox>
+ </Activity>
+ )}
+ </>
+ );
+ },
+);
+
+FilesPane.displayName = 'AgentWorkingSidebarFilesPane';
+
+export default FilesPane;
diff --git a/src/features/Conversation/WorkingSidebar/Files/FilesPrefetch.tsx b/src/features/Conversation/WorkingSidebar/Files/FilesPrefetch.tsx
new file mode 100644
index 00000000000..bfc998caf70
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/FilesPrefetch.tsx
@@ -0,0 +1,34 @@
+import { memo } from 'react';
+
+import { useFilesTreeSources } from './useFilesTreeSources';
+
+interface FilesPrefetchProps {
+ deviceId?: string;
+ sandboxInstanceId?: string;
+ sandboxTopicId?: string;
+ workingDirectory: string;
+}
+
+/**
+ * Warms the Files tree while its pane is hidden. A hidden `<Activity>` keeps
+ * the pane mounted but tears down its effects, and SWR only fetches from an
+ * effect โ€” so a collapsed panel whose remembered tab is Files would otherwise
+ * start reading the tree only once the user opened it.
+ */
+const FilesPrefetch = memo<FilesPrefetchProps>(
+ ({ deviceId, sandboxInstanceId, sandboxTopicId, workingDirectory }) => {
+ useFilesTreeSources(deviceId, workingDirectory, {
+ instanceId: sandboxInstanceId,
+ // Warm the tree once. A hidden prefetch must not inherit the visible
+ // pane's sandbox polling or focus revalidation and keep walking the
+ // workspace.
+ live: false,
+ topicId: sandboxTopicId,
+ });
+ return null;
+ },
+);
+
+FilesPrefetch.displayName = 'AgentWorkingSidebarFilesPrefetch';
+
+export default FilesPrefetch;
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/FilesPrefetch.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/FilesPrefetch.test.tsx
new file mode 100644
index 00000000000..bedf30f7911
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/FilesPrefetch.test.tsx
@@ -0,0 +1,21 @@
+import { render } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+const calls = vi.hoisted(() => [] as unknown[][]);
+
+vi.mock('../useFilesTreeSources', () => ({
+ useFilesTreeSources: (...args: unknown[]) => {
+ calls.push(args);
+ },
+}));
+
+const { default: FilesPrefetch } = await import('../FilesPrefetch');
+
+describe('FilesPrefetch', () => {
+ it('warms a sandbox tree once instead of enabling live polling', () => {
+ render(<FilesPrefetch sandboxInstanceId={'instance-1'} workingDirectory={''} />);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0][2]).toMatchObject({ instanceId: 'instance-1', live: false });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/harness.tsx
new file mode 100644
index 00000000000..3e2d3b594b4
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/harness.tsx
@@ -0,0 +1,379 @@
+// Shared mocks and fixtures for the Files pane suites. Import this module before
+// `../index` so the module mocks are registered before the pane loads.
+
+import { fireEvent, screen } from '@testing-library/react';
+import type { ReactNode as ReactNodeType, Ref } from 'react';
+import { useImperativeHandle } from 'react';
+import { afterEach, beforeEach, vi } from 'vitest';
+
+import { useGlobalStore } from '@/store/global';
+import { initialState } from '@/store/global/initialState';
+
+// โ”€โ”€โ”€ shared mutable handle spies โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+const handleSpies = {
+ focus: vi.fn(),
+ getSelectedIds: vi.fn((): string[] => []),
+ resync: vi.fn(),
+ select: vi.fn(),
+ setExpanded: vi.fn(),
+ startCreating: vi.fn(),
+ startRenaming: vi.fn(),
+};
+
+const explorerTreeProps = vi.hoisted(() => ({
+ current: undefined as Record<string, unknown> | undefined,
+}));
+const gitFilesMock = vi.hoisted(() => ({
+ data: {
+ added: ['root.ts'],
+ deleted: ['deleted.ts'],
+ modified: ['src/foo/bar.ts'],
+ },
+ error: undefined as Error | undefined,
+}));
+const openLocalFileMock = vi.hoisted(() => vi.fn());
+const searchProjectFilesMock = vi.hoisted(() => vi.fn());
+const listProjectDirectoryMock = vi.hoisted(() => vi.fn());
+const fileOpsMock = vi.hoisted(() => ({
+ copyProjectFiles: vi.fn(),
+ createProjectDirectory: vi.fn(),
+ createProjectFile: vi.fn(),
+ moveProjectFiles: vi.fn(),
+ refreshProjectFiles: vi.fn(),
+ renameProjectFile: vi.fn(),
+ trashProjectFiles: vi.fn(),
+}));
+const uiSpies = vi.hoisted(() => ({
+ confirmModal: vi.fn(),
+ toastError: vi.fn(),
+ toastSuccess: vi.fn(),
+}));
+const projectFilesMock = vi.hoisted(() => {
+ const baseEntries = [
+ { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
+ { isDirectory: true, name: 'foo', path: '/repo/src/foo', relativePath: 'src/foo/' },
+ {
+ isDirectory: false,
+ name: 'bar.ts',
+ path: '/repo/src/foo/bar.ts',
+ relativePath: 'src/foo/bar.ts',
+ },
+ { isDirectory: false, name: 'root.ts', path: '/repo/root.ts', relativePath: 'root.ts' },
+ {
+ isDirectory: false,
+ name: '__project_root__',
+ path: '/repo/__project_root__',
+ relativePath: '__project_root__',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.env.local',
+ path: '/repo/.env.local',
+ relativePath: '.env.local',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.DS_Store',
+ path: '/repo/.DS_Store',
+ relativePath: '.DS_Store',
+ },
+ { isDirectory: false, name: 'draft.md~', path: '/repo/draft.md~', relativePath: 'draft.md~' },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: '.git',
+ path: '/repo/.git',
+ relativePath: '.git/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: 'config',
+ path: '/repo/.git/config',
+ relativePath: '.git/config',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'node_modules',
+ path: '/repo/node_modules',
+ relativePath: 'node_modules/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: '.next',
+ path: '/repo/.next',
+ relativePath: '.next/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'dist',
+ path: '/repo/dist',
+ relativePath: 'dist/',
+ },
+ { isDirectory: true, name: 'build', path: '/repo/build', relativePath: 'build/' },
+ { isDirectory: true, name: '.github', path: '/repo/.github', relativePath: '.github/' },
+ { isDirectory: true, name: '.vscode', path: '/repo/.vscode', relativePath: '.vscode/' },
+ ];
+
+ return {
+ baseEntries,
+ data: {
+ entries: [...baseEntries],
+ indexedAt: '2026-01-01',
+ persistedPartial: undefined as true | undefined,
+ root: '/repo',
+ source: 'git' as 'git' | 'glob',
+ },
+ error: undefined as Error | undefined,
+ isValidating: false,
+ };
+});
+
+// โ”€โ”€โ”€ mocks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+vi.mock('@/features/ExplorerTree', () => {
+ const MockExplorerTree = ({ ref, ...props }: { ref?: Ref<unknown>; [key: string]: unknown }) => {
+ explorerTreeProps.current = props;
+ useImperativeHandle(ref, () => ({
+ focus: handleSpies.focus,
+ getFocusedId: vi.fn(() => null),
+ getSelectedIds: handleSpies.getSelectedIds,
+ deselect: vi.fn(),
+ resync: handleSpies.resync,
+ select: handleSpies.select,
+ setExpanded: handleSpies.setExpanded,
+ startCreating: handleSpies.startCreating,
+ startRenaming: handleSpies.startRenaming,
+ }));
+ return <div data-testid="explorer-tree" />;
+ };
+ MockExplorerTree.displayName = 'MockExplorerTree';
+ return {
+ ExplorerTree: MockExplorerTree,
+ FOLDER_ICON_CSS: 'folder-css',
+ HIDE_POINTER_FOCUS_RING_CSS: 'hide-pointer-focus-ring-css',
+ getExplorerTreeStyleVars: () => ({}),
+ };
+});
+
+vi.mock('../useGitWorkingTreeFiles', () => ({
+ buildGitStatusEntries: (files?: { added: string[]; deleted: string[]; modified: string[] }) =>
+ files
+ ? [
+ ...files.added.map((path) => ({ path, status: 'added' })),
+ ...files.modified.map((path) => ({ path, status: 'modified' })),
+ ...files.deleted.map((path) => ({ path, status: 'deleted' })),
+ ]
+ : [],
+ useGitWorkingTreeFiles: () => ({ data: gitFilesMock.data, error: gitFilesMock.error }),
+}));
+
+vi.mock('../useProjectFiles', () => ({
+ useProjectFiles: (_deviceId: string | undefined, workingDirectory: string) => ({
+ data: {
+ ...projectFilesMock.data,
+ entries: projectFilesMock.data.entries,
+ source: workingDirectory === '/non-git' ? 'glob' : projectFilesMock.data.source,
+ },
+ isLoading: false,
+ error: projectFilesMock.error,
+ isValidating: projectFilesMock.isValidating,
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: {
+ copyProjectFiles: fileOpsMock.copyProjectFiles,
+ createProjectDirectory: fileOpsMock.createProjectDirectory,
+ createProjectFile: fileOpsMock.createProjectFile,
+ listProjectDirectory: listProjectDirectoryMock,
+ moveProjectFiles: fileOpsMock.moveProjectFiles,
+ renameProjectFile: fileOpsMock.renameProjectFile,
+ searchProjectFiles: searchProjectFilesMock,
+ trashProjectFiles: fileOpsMock.trashProjectFiles,
+ },
+ refreshProjectFiles: fileOpsMock.refreshProjectFiles,
+}));
+
+vi.mock('@/utils/platform', () => ({
+ getPlatform: () => 'Mac OS',
+ isMacOS: () => true,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({
+ activeAgentId: 'agt_1',
+ activeTopicId: 'tpc_1',
+ openLocalFile: openLocalFileMock,
+ }),
+}));
+
+const messageSpy = vi.hoisted(() => ({ warning: vi.fn() }));
+
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ message: messageSpy,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options ? `${key} ${JSON.stringify(options)}` : key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ const factories: ((original: typeof importOriginal) => unknown)[] = [
+ async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ confirmModal: uiSpies.confirmModal,
+ toast: { error: uiSpies.toastError, success: uiSpies.toastSuccess },
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button title={title} type={'button'} onClick={onClick} />
+ ),
+ Button: ({ children, title }: { children?: ReactNodeType; title?: string }) => (
+ <button title={title} type={'button'}>
+ {children}
+ </button>
+ ),
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children?: ReactNodeType;
+ items: {
+ key: string;
+ label: ReactNodeType;
+ onCheckedChange?: (checked: boolean) => void;
+ onClick?: () => void;
+ }[];
+ }) => (
+ <div>
+ {children}
+ {items.map((item) => (
+ <button
+ key={item.key}
+ type={'button'}
+ onClick={() => {
+ item.onClick?.();
+ item.onCheckedChange?.(true);
+ }}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+ ),
+ }),
+ () => ({
+ Center: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
+ copyToClipboard: vi.fn(),
+ Empty: ({ description }: { description?: ReactNodeType }) => <div>{description}</div>,
+ Flexbox: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
+ Icon: () => <span />,
+ stopPropagation: vi.fn(),
+ }),
+ async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+
+ return {
+ ...actual,
+ createStaticStyles: () => () => ({}),
+ };
+ },
+ ];
+ const merged: Record<string, unknown> = { ...actual };
+ for (const factory of factories) {
+ const part = (await factory(importOriginal)) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
+ }
+ return merged;
+});
+
+// โ”€โ”€โ”€ helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+const setReveal = (path: string, nonce: number) => {
+ useGlobalStore.setState({
+ status: {
+ ...useGlobalStore.getState().status,
+ workingSidebarRevealRequest: { nonce, path },
+ },
+ });
+};
+
+const expandSearch = () => {
+ fireEvent.click(screen.getByTitle('workingPanel.files.search'));
+};
+
+// โ”€โ”€โ”€ tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+beforeEach(() => {
+ projectFilesMock.data.source = 'git';
+ projectFilesMock.data.persistedPartial = undefined;
+ projectFilesMock.error = undefined;
+ projectFilesMock.isValidating = false;
+ gitFilesMock.error = undefined;
+ projectFilesMock.data.entries = [...projectFilesMock.baseEntries];
+ explorerTreeProps.current = undefined;
+ handleSpies.focus.mockClear();
+ handleSpies.select.mockClear();
+ handleSpies.setExpanded.mockClear();
+ handleSpies.getSelectedIds.mockReset();
+ handleSpies.getSelectedIds.mockReturnValue([]);
+ handleSpies.resync.mockClear();
+ handleSpies.startCreating.mockClear();
+ handleSpies.startRenaming.mockClear();
+ for (const mock of Object.values(fileOpsMock)) mock.mockReset();
+ fileOpsMock.refreshProjectFiles.mockResolvedValue(undefined);
+ uiSpies.confirmModal.mockReset();
+ uiSpies.toastError.mockReset();
+ uiSpies.toastSuccess.mockReset();
+ messageSpy.warning.mockClear();
+ openLocalFileMock.mockClear();
+ listProjectDirectoryMock.mockReset();
+ listProjectDirectoryMock.mockResolvedValue({ entries: [], truncated: false });
+ // Default to an empty result so EVERY call resolves to a promise. The search
+ // effect can fire more than once (debounce + effect re-run / StrictMode), and
+ // per-test `mockResolvedValueOnce` only covers the first call โ€” an extra,
+ // un-mocked call would return `undefined`, and the component's
+ // `searchProjectFiles(...).then(...)` would throw "reading 'then'" (flaky in CI).
+ searchProjectFilesMock.mockReset();
+ searchProjectFilesMock.mockResolvedValue({
+ entries: [],
+ root: '/repo',
+ searchedAt: '2026-01-01',
+ source: 'git',
+ });
+ useGlobalStore.setState({
+ ...initialState,
+ status: { ...initialState.status, workingSidebarRevealRequest: undefined },
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+export {
+ expandSearch,
+ explorerTreeProps,
+ fileOpsMock,
+ gitFilesMock,
+ handleSpies,
+ listProjectDirectoryMock,
+ messageSpy,
+ openLocalFileMock,
+ projectFilesMock,
+ searchProjectFilesMock,
+ setReveal,
+ uiSpies,
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index 3f5cf218417..a192ca2b67c 100644
--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -1,357 +1,27 @@
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import type { ReactNode as ReactNodeType, Ref } from 'react';
-import { useImperativeHandle } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ComponentType } from 'react';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
-import { useGlobalStore } from '@/store/global';
-import { initialState } from '@/store/global/initialState';
import { useUserStore } from '@/store/user';
-import Files from '../index';
-
-// โ”€โ”€โ”€ shared mutable handle spies โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
-const handleSpies = {
- focus: vi.fn(),
- getSelectedIds: vi.fn((): string[] => []),
- resync: vi.fn(),
- select: vi.fn(),
- setExpanded: vi.fn(),
- startCreating: vi.fn(),
- startRenaming: vi.fn(),
-};
-
-const explorerTreeProps = vi.hoisted(() => ({
- current: undefined as Record<string, unknown> | undefined,
-}));
-const gitFilesMock = vi.hoisted(() => ({
- data: {
- added: ['root.ts'],
- deleted: ['deleted.ts'],
- modified: ['src/foo/bar.ts'],
- },
-}));
-const openLocalFileMock = vi.hoisted(() => vi.fn());
-const searchProjectFilesMock = vi.hoisted(() => vi.fn());
-const listProjectDirectoryMock = vi.hoisted(() => vi.fn());
-const fileOpsMock = vi.hoisted(() => ({
- copyProjectFiles: vi.fn(),
- createProjectDirectory: vi.fn(),
- createProjectFile: vi.fn(),
- moveProjectFiles: vi.fn(),
- refreshProjectFiles: vi.fn(),
- renameProjectFile: vi.fn(),
- trashProjectFiles: vi.fn(),
-}));
-const uiSpies = vi.hoisted(() => ({
- confirmModal: vi.fn(),
- toastError: vi.fn(),
- toastSuccess: vi.fn(),
-}));
-const projectFilesMock = vi.hoisted(() => {
- const baseEntries = [
- { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
- { isDirectory: true, name: 'foo', path: '/repo/src/foo', relativePath: 'src/foo/' },
- {
- isDirectory: false,
- name: 'bar.ts',
- path: '/repo/src/foo/bar.ts',
- relativePath: 'src/foo/bar.ts',
- },
- { isDirectory: false, name: 'root.ts', path: '/repo/root.ts', relativePath: 'root.ts' },
- {
- isDirectory: false,
- name: '__project_root__',
- path: '/repo/__project_root__',
- relativePath: '__project_root__',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: '.env.local',
- path: '/repo/.env.local',
- relativePath: '.env.local',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: '.DS_Store',
- path: '/repo/.DS_Store',
- relativePath: '.DS_Store',
- },
- { isDirectory: false, name: 'draft.md~', path: '/repo/draft.md~', relativePath: 'draft.md~' },
- {
- gitIgnored: true,
- isDirectory: true,
- name: '.git',
- path: '/repo/.git',
- relativePath: '.git/',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: 'config',
- path: '/repo/.git/config',
- relativePath: '.git/config',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: 'node_modules',
- path: '/repo/node_modules',
- relativePath: 'node_modules/',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: '.next',
- path: '/repo/.next',
- relativePath: '.next/',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: 'dist',
- path: '/repo/dist',
- relativePath: 'dist/',
- },
- { isDirectory: true, name: 'build', path: '/repo/build', relativePath: 'build/' },
- { isDirectory: true, name: '.github', path: '/repo/.github', relativePath: '.github/' },
- { isDirectory: true, name: '.vscode', path: '/repo/.vscode', relativePath: '.vscode/' },
- ];
-
- return {
- baseEntries,
- data: {
- entries: [...baseEntries],
- indexedAt: '2026-01-01',
- root: '/repo',
- source: 'git' as 'git' | 'glob',
- },
- };
-});
-
-// โ”€โ”€โ”€ mocks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
-vi.mock('@/features/ExplorerTree', () => {
- const MockExplorerTree = ({ ref, ...props }: { ref?: Ref<unknown>; [key: string]: unknown }) => {
- explorerTreeProps.current = props;
- useImperativeHandle(ref, () => ({
- focus: handleSpies.focus,
- getFocusedId: vi.fn(() => null),
- getSelectedIds: handleSpies.getSelectedIds,
- deselect: vi.fn(),
- resync: handleSpies.resync,
- select: handleSpies.select,
- setExpanded: handleSpies.setExpanded,
- startCreating: handleSpies.startCreating,
- startRenaming: handleSpies.startRenaming,
- }));
- return <div data-testid="explorer-tree" />;
- };
- MockExplorerTree.displayName = 'MockExplorerTree';
- return {
- ExplorerTree: MockExplorerTree,
- FOLDER_ICON_CSS: 'folder-css',
- HIDE_POINTER_FOCUS_RING_CSS: 'hide-pointer-focus-ring-css',
- getExplorerTreeStyleVars: () => ({}),
- };
-});
-
-vi.mock('../useGitWorkingTreeFiles', () => ({
- buildGitStatusEntries: (files?: { added: string[]; deleted: string[]; modified: string[] }) =>
- files
- ? [
- ...files.added.map((path) => ({ path, status: 'added' })),
- ...files.modified.map((path) => ({ path, status: 'modified' })),
- ...files.deleted.map((path) => ({ path, status: 'deleted' })),
- ]
- : [],
- useGitWorkingTreeFiles: () => ({ data: gitFilesMock.data }),
-}));
-
-vi.mock('../useProjectFiles', () => ({
- useProjectFiles: (_deviceId: string | undefined, workingDirectory: string) => ({
- data: {
- ...projectFilesMock.data,
- entries: projectFilesMock.data.entries,
- source: workingDirectory === '/non-git' ? 'glob' : projectFilesMock.data.source,
- },
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- }),
-}));
-
-vi.mock('@/services/projectFile', () => ({
- projectFileService: {
- copyProjectFiles: fileOpsMock.copyProjectFiles,
- createProjectDirectory: fileOpsMock.createProjectDirectory,
- createProjectFile: fileOpsMock.createProjectFile,
- listProjectDirectory: listProjectDirectoryMock,
- moveProjectFiles: fileOpsMock.moveProjectFiles,
- renameProjectFile: fileOpsMock.renameProjectFile,
- searchProjectFiles: searchProjectFilesMock,
- trashProjectFiles: fileOpsMock.trashProjectFiles,
- },
- refreshProjectFiles: fileOpsMock.refreshProjectFiles,
-}));
-
-vi.mock('@/utils/platform', () => ({
- getPlatform: () => 'Mac OS',
- isMacOS: () => true,
-}));
-
-vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({
- activeAgentId: 'agt_1',
- activeTopicId: 'tpc_1',
- openLocalFile: openLocalFileMock,
- }),
-}));
-
-const messageSpy = vi.hoisted(() => ({ warning: vi.fn() }));
-
-vi.mock('antd', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- message: messageSpy,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string, options?: Record<string, unknown>) =>
- options ? `${key} ${JSON.stringify(options)}` : key,
- }),
-}));
-
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const actual = await importOriginal<Record<string, unknown>>();
- const factories: ((original: typeof importOriginal) => unknown)[] = [
- async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- confirmModal: uiSpies.confirmModal,
- toast: { error: uiSpies.toastError, success: uiSpies.toastSuccess },
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button title={title} type={'button'} onClick={onClick} />
- ),
- Button: ({ children, title }: { children?: ReactNodeType; title?: string }) => (
- <button title={title} type={'button'}>
- {children}
- </button>
- ),
- DropdownMenu: ({
- children,
- items,
- }: {
- children?: ReactNodeType;
- items: {
- key: string;
- label: ReactNodeType;
- onCheckedChange?: (checked: boolean) => void;
- onClick?: () => void;
- }[];
- }) => (
- <div>
- {children}
- {items.map((item) => (
- <button
- key={item.key}
- type={'button'}
- onClick={() => {
- item.onClick?.();
- item.onCheckedChange?.(true);
- }}
- >
- {item.label}
- </button>
- ))}
- </div>
- ),
- }),
- () => ({
- Center: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
- copyToClipboard: vi.fn(),
- Empty: ({ description }: { description?: ReactNodeType }) => <div>{description}</div>,
- Flexbox: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
- Icon: () => <span />,
- stopPropagation: vi.fn(),
- }),
- async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
-
- return {
- ...actual,
- createStaticStyles: () => () => ({}),
- };
- },
- ];
- const merged: Record<string, unknown> = { ...actual };
- for (const factory of factories) {
- const part = (await factory(importOriginal)) as Record<string, unknown>;
- for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
- }
- return merged;
-});
-
-// โ”€โ”€โ”€ helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
-const setReveal = (path: string, nonce: number) => {
- useGlobalStore.setState({
- status: {
- ...useGlobalStore.getState().status,
- workingSidebarRevealRequest: { nonce, path },
- },
- });
-};
-
-const expandSearch = () => {
- fireEvent.click(screen.getByTitle('workingPanel.files.search'));
-};
-
-// โ”€โ”€โ”€ tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
-beforeEach(() => {
- projectFilesMock.data.source = 'git';
- projectFilesMock.data.entries = [...projectFilesMock.baseEntries];
- explorerTreeProps.current = undefined;
- handleSpies.focus.mockClear();
- handleSpies.select.mockClear();
- handleSpies.setExpanded.mockClear();
- handleSpies.getSelectedIds.mockReset();
- handleSpies.getSelectedIds.mockReturnValue([]);
- handleSpies.resync.mockClear();
- handleSpies.startCreating.mockClear();
- handleSpies.startRenaming.mockClear();
- for (const mock of Object.values(fileOpsMock)) mock.mockReset();
- fileOpsMock.refreshProjectFiles.mockResolvedValue(undefined);
- uiSpies.confirmModal.mockReset();
- uiSpies.toastError.mockReset();
- uiSpies.toastSuccess.mockReset();
- messageSpy.warning.mockClear();
- openLocalFileMock.mockClear();
- listProjectDirectoryMock.mockReset();
- listProjectDirectoryMock.mockResolvedValue({ entries: [], truncated: false });
- // Default to an empty result so EVERY call resolves to a promise. The search
- // effect can fire more than once (debounce + effect re-run / StrictMode), and
- // per-test `mockResolvedValueOnce` only covers the first call โ€” an extra,
- // un-mocked call would return `undefined`, and the component's
- // `searchProjectFiles(...).then(...)` would throw "reading 'then'" (flaky in CI).
- searchProjectFilesMock.mockReset();
- searchProjectFilesMock.mockResolvedValue({
- entries: [],
- root: '/repo',
- searchedAt: '2026-01-01',
- source: 'git',
- });
- useGlobalStore.setState({
- ...initialState,
- status: { ...initialState.status, workingSidebarRevealRequest: undefined },
- });
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
+import {
+ expandSearch,
+ explorerTreeProps,
+ fileOpsMock,
+ handleSpies,
+ listProjectDirectoryMock,
+ messageSpy,
+ openLocalFileMock,
+ projectFilesMock,
+ searchProjectFilesMock,
+ setReveal,
+} from './harness';
+
+// Loaded after the mock harness so module mocks are registered first.
+let Files: ComponentType<{ workingDirectory: string }>;
+
+beforeAll(async () => {
+ Files = (await import('../index')).default;
});
describe('Files โ€” reveal request integration', () => {
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/partialIndex.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/partialIndex.test.tsx
new file mode 100644
index 00000000000..63efd786b30
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/partialIndex.test.tsx
@@ -0,0 +1,41 @@
+import { render, screen } from '@testing-library/react';
+import type { ComponentType } from 'react';
+import { beforeAll, beforeEach, describe, expect, it } from 'vitest';
+
+import { projectFilesMock } from './harness';
+
+// Loaded after the harness so its module mocks are registered first.
+let Files: ComponentType<{ workingDirectory: string }>;
+
+beforeAll(async () => {
+ Files = (await import('../index')).default;
+});
+
+describe('Files โ€” partial index', () => {
+ beforeEach(() => {
+ projectFilesMock.data.source = 'git';
+ projectFilesMock.data.persistedPartial = undefined;
+ projectFilesMock.isValidating = false;
+ projectFilesMock.data.entries = [...projectFilesMock.baseEntries];
+ });
+
+ it('flags a saved partial tree only once its refresh is no longer running', () => {
+ // Restored from a capped row (a large project) while the refresh is in flight.
+ projectFilesMock.data.persistedPartial = true;
+ projectFilesMock.isValidating = true;
+ const { unmount } = render(<Files workingDirectory="/repo" />);
+ expect(screen.queryByText('workingPanel.files.partialIndexNotice')).not.toBeInTheDocument();
+ unmount();
+
+ // The refresh failed: the partial tree is all there is, and it must say so.
+ projectFilesMock.isValidating = false;
+ render(<Files workingDirectory="/repo" />);
+ expect(screen.getByText('workingPanel.files.partialIndexNotice')).toBeInTheDocument();
+ });
+
+ it('does not flag a complete tree', () => {
+ render(<Files workingDirectory="/repo" />);
+
+ expect(screen.queryByText('workingPanel.files.partialIndexNotice')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/refreshFailure.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/refreshFailure.test.tsx
new file mode 100644
index 00000000000..0ff3ca2e722
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/refreshFailure.test.tsx
@@ -0,0 +1,38 @@
+import { render, screen } from '@testing-library/react';
+import type { ComponentType } from 'react';
+import { beforeAll, describe, expect, it } from 'vitest';
+
+import { gitFilesMock, projectFilesMock } from './harness';
+
+// Loaded after the harness so its module mocks are registered first.
+let Files: ComponentType<{ workingDirectory: string }>;
+
+beforeAll(async () => {
+ Files = (await import('../index')).default;
+});
+
+describe('Files โ€” refresh failure with a saved tree', () => {
+ it('keeps the saved tree but says it could not refresh', () => {
+ projectFilesMock.error = new Error('index read failed');
+
+ render(<Files workingDirectory="/repo" />);
+
+ expect(screen.getByTestId('explorer-tree')).toBeInTheDocument();
+ expect(screen.getByText('workingPanel.files.refreshFailed')).toBeInTheDocument();
+ });
+
+ it('surfaces a failed git overlay refresh on the same saved tree', () => {
+ gitFilesMock.error = new Error('git status failed');
+
+ render(<Files workingDirectory="/repo" />);
+
+ expect(screen.getByTestId('explorer-tree')).toBeInTheDocument();
+ expect(screen.getByText('workingPanel.files.refreshFailed')).toBeInTheDocument();
+ });
+
+ it('stays quiet when both refreshes succeed', () => {
+ render(<Files workingDirectory="/repo" />);
+
+ expect(screen.queryByText('workingPanel.files.refreshFailed')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesPaneLocation.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesPaneLocation.test.ts
new file mode 100644
index 00000000000..91d4f5a3a94
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesPaneLocation.test.ts
@@ -0,0 +1,103 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const captured = vi.hoisted(() => ({ calls: [] as unknown[][] }));
+const device = vi.hoisted(() => ({ confirmed: false, loaded: false }));
+
+vi.mock('@/store/device', () => ({
+ deviceSelectors: {
+ isDeviceListConfirmed: (s: { confirmed: boolean }) => s.confirmed,
+ isDeviceListLoaded: (s: { loaded: boolean }) => s.loaded,
+ },
+ useDeviceStore: (selector: (s: { confirmed: boolean; loaded: boolean }) => boolean) =>
+ selector(device),
+}));
+
+vi.mock('../useRememberedFilesLocation', () => ({
+ filesLocationContextKey: (topicId?: string, agentId?: string) =>
+ topicId ? `topic/${topicId}` : agentId ? `agent/${agentId}` : undefined,
+ useRememberedFilesLocation: (...args: unknown[]) => {
+ captured.calls.push(args);
+ return undefined;
+ },
+}));
+
+const { useFilesPaneLocation } = await import('../useFilesPaneLocation');
+
+const base = {
+ activeAgentId: 'agent-1',
+ sandboxDirectory: '',
+ sandboxDirectoryKnown: false,
+ topicId: 'tpc_1',
+};
+
+beforeEach(() => {
+ captured.calls.length = 0;
+ device.confirmed = false;
+ device.loaded = false;
+});
+
+describe('useFilesPaneLocation', () => {
+ it('does not consult a remembered filesystem path when the environment cannot read one', () => {
+ const { result } = renderHook(() =>
+ useFilesPaneLocation({
+ ...base,
+ filesystemEnvironmentAvailable: false,
+ isSandboxExecution: true,
+ sandboxDirectoryKnown: true,
+ sandboxInstanceId: 'instance-1',
+ }),
+ );
+
+ // Neither the conversation key nor a resolved location reaches the hook,
+ // so a saved local directory cannot enable Files in a sandbox.
+ expect(captured.calls[0][0]).toBeUndefined();
+ expect(captured.calls[0][1]).toBeUndefined();
+ expect(result.current).toEqual({ deviceId: undefined, directory: '', isSandbox: true });
+ });
+
+ it('waits for a server-confirmed device list before settling the path', () => {
+ // A persisted device list counts as loaded, but its `workingDirs` are
+ // stale. Settling on it would drop the remembered directory before the
+ // server answers, so the hook must pass `settled: false` until confirmed.
+ device.loaded = true;
+ device.confirmed = false;
+
+ renderHook(() =>
+ useFilesPaneLocation({
+ ...base,
+ filesystemEnvironmentAvailable: true,
+ isSandboxExecution: false,
+ workingDirectory: '/from-stale-device-list',
+ }),
+ );
+
+ expect(captured.calls[0][2]).toBe(false);
+
+ device.confirmed = true;
+ renderHook(() =>
+ useFilesPaneLocation({
+ ...base,
+ filesystemEnvironmentAvailable: true,
+ isSandboxExecution: false,
+ workingDirectory: '/from-stale-device-list',
+ }),
+ );
+ expect(captured.calls[1][2]).toBe(true);
+ });
+
+ it('keeps the known remote host while its directory is still unresolved', () => {
+ renderHook(() =>
+ useFilesPaneLocation({
+ ...base,
+ filesystemEnvironmentAvailable: true,
+ isSandboxExecution: false,
+ remoteDeviceId: 'device-1',
+ workingDirectory: undefined,
+ }),
+ );
+
+ expect(captured.calls[0][0]).toBe('topic/tpc_1');
+ expect(captured.calls[0][1]).toEqual({ deviceId: 'device-1', directory: undefined });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.prefetch.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.prefetch.test.ts
new file mode 100644
index 00000000000..29448631234
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.prefetch.test.ts
@@ -0,0 +1,43 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const calls = vi.hoisted(() => ({
+ git: [] as unknown[][],
+ project: [] as unknown[][],
+}));
+
+vi.mock('../useProjectFiles', () => ({
+ useProjectFiles: (...args: unknown[]) => {
+ calls.project.push(args);
+ return { data: undefined };
+ },
+}));
+
+vi.mock('../useGitWorkingTreeFiles', () => ({
+ useGitWorkingTreeFiles: (...args: unknown[]) => {
+ calls.git.push(args);
+ return { data: undefined };
+ },
+}));
+
+const { useFilesTreeSources } = await import('../useFilesTreeSources');
+
+beforeEach(() => {
+ calls.git.length = 0;
+ calls.project.length = 0;
+});
+
+describe('useFilesTreeSources โ€” prefetch mode', () => {
+ it('disables focus revalidation for a hidden prefetch', () => {
+ renderHook(() => useFilesTreeSources('device-1', '/repo', { instanceId: 'i', live: false }));
+
+ expect(calls.project[0][2]).toMatchObject({ live: false });
+ expect(calls.git[0][3]).toEqual({ revalidateOnFocus: false });
+ });
+
+ it('keeps focus revalidation for the visible pane', () => {
+ renderHook(() => useFilesTreeSources('device-1', '/repo', { instanceId: 'i' }));
+
+ expect(calls.git[0][3]).toEqual({ revalidateOnFocus: true });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.test.ts
new file mode 100644
index 00000000000..66c1d531290
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useFilesTreeSources.test.ts
@@ -0,0 +1,96 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useFilesTreeSources } from '../useFilesTreeSources';
+
+const services = vi.hoisted(() => ({
+ getGitWorkingTreeFiles: vi.fn(),
+ getProjectFileIndex: vi.fn(),
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { getProjectFileIndex: services.getProjectFileIndex },
+}));
+vi.mock('@/services/git', () => ({
+ gitService: { getGitWorkingTreeFiles: services.getGitWorkingTreeFiles },
+}));
+vi.mock('@/store/chat', () => ({ useChatStore: () => false }));
+vi.mock('@/store/chat/selectors', () => ({ operationSelectors: {} }));
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
+
+beforeEach(() => {
+ services.getGitWorkingTreeFiles.mockReset();
+ services.getProjectFileIndex.mockReset();
+});
+
+describe('useFilesTreeSources', () => {
+ it('reads the git overlay alongside the index instead of after it', async () => {
+ const index = deferred<unknown>();
+ services.getProjectFileIndex.mockReturnValue(index.promise);
+ services.getGitWorkingTreeFiles.mockResolvedValue({
+ added: [],
+ deleted: [],
+ modified: ['a.ts'],
+ });
+
+ const { result } = renderHook(() => useFilesTreeSources('device-1', '/repo'), { wrapper });
+
+ // The index is still in flight, yet the overlay has already been asked for.
+ await waitFor(() => expect(result.current.git.data?.modified).toEqual(['a.ts']));
+ expect(services.getGitWorkingTreeFiles).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ path: '/repo',
+ });
+ expect(result.current.project.data).toBeUndefined();
+
+ await act(async () => {
+ index.resolve({ entries: [], indexedAt: 'now', root: '/repo', source: 'git' });
+ });
+ expect(result.current.project.data?.source).toBe('git');
+ expect(result.current.git.data?.modified).toEqual(['a.ts']);
+ });
+
+ it('drops the overlay once the index settles on a non-git source', async () => {
+ services.getProjectFileIndex.mockResolvedValue({
+ entries: [],
+ indexedAt: 'now',
+ root: '/plain',
+ source: 'glob',
+ });
+ services.getGitWorkingTreeFiles.mockResolvedValue({ added: [], deleted: [], modified: [] });
+
+ const { result } = renderHook(() => useFilesTreeSources('device-1', '/plain'), { wrapper });
+
+ await waitFor(() => expect(result.current.project.data?.source).toBe('glob'));
+ expect(result.current.git.data).toBeUndefined();
+ });
+
+ it('never asks a sandbox tree for git status', async () => {
+ services.getProjectFileIndex.mockResolvedValue({
+ entries: [],
+ indexedAt: 'now',
+ root: '',
+ source: 'sandbox',
+ });
+
+ const { result } = renderHook(
+ () => useFilesTreeSources(undefined, '', { instanceId: 'instance-1' }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.project.data?.source).toBe('sandbox'));
+ expect(services.getGitWorkingTreeFiles).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useProjectFiles.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useProjectFiles.test.ts
new file mode 100644
index 00000000000..267fe18e22f
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useProjectFiles.test.ts
@@ -0,0 +1,57 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+const captured = vi.hoisted(() => ({
+ options: undefined as { refreshInterval?: number; revalidateOnFocus?: boolean } | undefined,
+}));
+
+vi.mock('@lobechat/const', () => ({ isDesktop: true }));
+vi.mock('@/store/chat', () => ({ useChatStore: () => true }));
+vi.mock('@/store/chat/selectors', () => ({
+ operationSelectors: { isAgentRuntimeRunning: Symbol('isAgentRuntimeRunning') },
+}));
+vi.mock('@/store/projectFile', () => ({
+ projectFileActions: {
+ useFetchProjectIndex: (
+ _params: unknown,
+ options: { refreshInterval?: number; revalidateOnFocus?: boolean },
+ ): {
+ error: undefined;
+ isHydrated: boolean;
+ isValidating: boolean;
+ revalidate: () => void;
+ } => {
+ captured.options = options;
+ return {
+ error: undefined,
+ isHydrated: true,
+ isValidating: false,
+ revalidate: vi.fn(),
+ };
+ },
+ },
+ projectIndexResource: { key: (params: unknown) => JSON.stringify(params) },
+ useProjectFileStore: (selector: (state: { projectIndex: Record<string, never> }) => unknown) =>
+ selector({ projectIndex: {} }),
+}));
+
+const { useProjectFiles } = await import('../useProjectFiles');
+
+describe('useProjectFiles โ€” sandbox live polling', () => {
+ it('polls a running sandbox only when the caller allows live reads', () => {
+ const { rerender } = renderHook(
+ ({ live }: { live: boolean }) =>
+ useProjectFiles(undefined, '', { instanceId: 'instance-1', live }),
+ { initialProps: { live: true } },
+ );
+
+ expect(captured.options?.refreshInterval).toBe(15_000);
+ expect(captured.options?.revalidateOnFocus).toBe(true);
+
+ // The hidden prefetch warms the tree once instead of walking the workspace
+ // every interval or on every app focus until the run ends.
+ rerender({ live: false });
+ expect(captured.options?.refreshInterval).toBe(0);
+ expect(captured.options?.revalidateOnFocus).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts
new file mode 100644
index 00000000000..b02da1c5181
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useRememberedFilesLocation.test.ts
@@ -0,0 +1,205 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FilesLocation } from '../useRememberedFilesLocation';
+
+const scope = vi.hoisted(() => ({ current: 'u1:personal' }));
+const trusted = vi.hoisted(() => ({ current: true }));
+
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => trusted.current,
+ useCacheScope: () => scope.current,
+ useIsScopeTrusted: () => trusted.current,
+}));
+
+interface Props {
+ contextKey?: string;
+ resolved?: FilesLocation;
+ settled: boolean;
+}
+
+/** A fresh page (new store and replica engine) over the same localStorage. */
+const boot = async (initialProps: Props) => {
+ vi.resetModules();
+ const { useRememberedFilesLocation } = await import('../useRememberedFilesLocation');
+ return renderHook(
+ ({ contextKey, resolved, settled }: Props) =>
+ useRememberedFilesLocation(contextKey, resolved, settled),
+ { initialProps },
+ );
+};
+
+/** One session that settles on `location` for `contextKey`. */
+const storedRows = () =>
+ Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i)!).filter(
+ (key) => key.startsWith('replica:filesLocation:') && !key.includes('__replica'),
+ );
+
+const remember = async (contextKey: string, location: FilesLocation) => {
+ const view = await boot({ contextKey, resolved: location, settled: true });
+ await waitFor(() => expect(storedRows().length).toBeGreaterThan(0));
+ view.unmount();
+};
+
+beforeEach(() => {
+ scope.current = 'u1:personal';
+ trusted.current = true;
+ localStorage.clear();
+});
+
+describe('useRememberedFilesLocation', { timeout: 15_000 }, () => {
+ it('opens where the conversation last was until the device list settles', async () => {
+ await remember('topic/t1', { deviceId: 'device-1', directory: '/repo' });
+
+ // Before the device default is known the live resolution is the home fallback.
+ const { rerender, result } = await boot({
+ contextKey: 'topic/t1',
+ resolved: { deviceId: 'device-1', directory: '/Users/me' },
+ settled: false,
+ });
+ await waitFor(() =>
+ expect(result.current).toEqual({ deviceId: 'device-1', directory: '/repo' }),
+ );
+
+ rerender({
+ contextKey: 'topic/t1',
+ resolved: { deviceId: 'device-1', directory: '/repo/next' },
+ settled: true,
+ });
+ expect(result.current).toEqual({ deviceId: 'device-1', directory: '/repo/next' });
+
+ // The next session opens the new location.
+ const next = await boot({
+ contextKey: 'topic/t1',
+ resolved: { deviceId: 'device-1', directory: '/Users/me' },
+ settled: false,
+ });
+ await waitFor(() =>
+ expect(next.result.current).toEqual({ deviceId: 'device-1', directory: '/repo/next' }),
+ );
+ });
+
+ it('rejects a saved location from a different host before the device list settles', async () => {
+ await remember('topic/t1', { deviceId: 'device-old', directory: '/old-repo' });
+
+ // The agent's target changed: the live host is already known from config.
+ const { result } = await boot({
+ contextKey: 'topic/t1',
+ resolved: { deviceId: 'device-new', directory: '/new-repo' },
+ settled: false,
+ });
+
+ await waitFor(() =>
+ expect(result.current).toEqual({ deviceId: 'device-new', directory: '/new-repo' }),
+ );
+ });
+
+ it('does not use a remembered filesystem location when nothing can read it', async () => {
+ await remember('topic/t1', { directory: '/repo' });
+
+ // A sandbox / cloud-only target: no filesystem environment, so the old
+ // local path must not enable Files or route mutations through IPC.
+ const { result } = await boot({
+ contextKey: undefined,
+ resolved: undefined,
+ settled: false,
+ });
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it('answers with the saved location on the first render, before the replica hydrates', async () => {
+ await remember('topic/t1', { directory: '/repo' });
+
+ const { result } = await boot({
+ contextKey: 'topic/t1',
+ resolved: { directory: '/Users/me' },
+ settled: false,
+ });
+
+ expect(result.current).toEqual({ directory: '/repo' });
+ });
+
+ it('uses the live resolution when nothing was remembered for this context', async () => {
+ await remember('topic/other', { directory: '/elsewhere' });
+
+ const { result } = await boot({
+ contextKey: 'topic/t1',
+ resolved: { directory: '/repo' },
+ settled: false,
+ });
+
+ await waitFor(() => expect(result.current).toEqual({ directory: '/repo' }));
+ });
+
+ it('keeps each identityโ€™s locations apart', async () => {
+ await remember('topic/t1', { directory: '/repo' });
+
+ scope.current = 'u2:personal';
+ const { result } = await boot({
+ contextKey: 'topic/t1',
+ resolved: { directory: '/Users/other' },
+ settled: false,
+ });
+
+ await waitFor(() => expect(result.current).toEqual({ directory: '/Users/other' }));
+ });
+
+ it('does not remember an unsettled resolution', async () => {
+ const view = await boot({
+ contextKey: 'topic/t1',
+ resolved: { directory: '/Users/me' },
+ settled: false,
+ });
+ await waitFor(() => expect(view.result.current).toEqual({ directory: '/Users/me' }));
+
+ expect(storedRows()).toEqual([]);
+ });
+
+ it('keeps its replica keys out of the SWR persistent cache', async () => {
+ const { replicaKeys } = await import('@lobechat/replica');
+ const { unstable_serialize } = await import('swr');
+ const { CACHE_TIERS } = await import('@/libs/swr/localStorageProvider');
+ const { filesLocationResource } = await import('@/store/projectFile/projection');
+ const { filesLocationContextKey } = await import('../useRememberedFilesLocation');
+ const patterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];
+
+ for (const contextKey of [
+ filesLocationContextKey('tpc_1', 'agt_1')!,
+ filesLocationContextKey(undefined, 'agt_1')!,
+ ]) {
+ const { name, version } = filesLocationResource;
+ const storageKey = filesLocationResource.storageKey({ contextKey });
+ // The SWR provider persists any key containing a tier pattern, so the
+ // replica's hydrate read must not carry one.
+ const swrKey = unstable_serialize(
+ replicaKeys.hydrate(name, version, 'u1:personal', storageKey),
+ );
+ expect(patterns.filter((pattern) => swrKey.includes(pattern))).toEqual([]);
+ }
+ });
+
+ it('passes the resolution through when there is no context to remember', async () => {
+ const { result } = await boot({ resolved: { directory: '' }, settled: false });
+
+ expect(result.current).toEqual({ directory: '' });
+ });
+
+ it('writes the location again once identity resolves', async () => {
+ trusted.current = false;
+ const view = await boot({
+ contextKey: 'topic/t1',
+ resolved: { directory: '/repo' },
+ settled: true,
+ });
+ // The engine drops the write while the scope is untrusted, even though the
+ // value is already in memory.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(storedRows()).toHaveLength(0);
+
+ trusted.current = true;
+ view.rerender({ contextKey: 'topic/t1', resolved: { directory: '/repo' }, settled: true });
+ await waitFor(() => expect(storedRows().length).toBeGreaterThan(0));
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index 6df5b3962e9..008161b6c95 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -39,15 +39,16 @@ import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';
import { useClientDataSWR } from '@/libs/swr';
import { projectFileService } from '@/services/projectFile';
import { useGlobalStore } from '@/store/global';
+import { isPersistedPartialIndex } from '@/store/projectFile';
import { filterProjectFileEntries, mergeMissingDeletedEntries } from './fileFilter';
import { FILE_TREE_UNSAFE_CSS } from './fileTreeStyle';
import { isExcludedProjectFileEntry } from './fileVisibility';
import { getAncestorIds, getParentRelativePath, PROJECT_ROOT_NODE_ID } from './treePaths';
import { useCollapsedDirectoryChildren } from './useCollapsedDirectoryChildren';
+import { useFilesTreeSources } from './useFilesTreeSources';
import { useFileTreeActions } from './useFileTreeActions';
-import { buildGitStatusEntries, useGitWorkingTreeFiles } from './useGitWorkingTreeFiles';
-import { useProjectFiles } from './useProjectFiles';
+import { buildGitStatusEntries } from './useGitWorkingTreeFiles';
interface FilesProps {
/**
@@ -219,15 +220,13 @@ const Files = memo<FilesProps>(
// sandbox both answer over the network, and neither can be handed to Electron
// to reveal in a file manager.
const isSandbox = !!sandboxTopicId || !!sandboxInstanceId;
- const { data, error, isLoading } = useProjectFiles(deviceId, workingDirectory, {
+ const {
+ git: { data: gitFiles, error: gitError },
+ project: { data, error, isLoading, isValidating },
+ } = useFilesTreeSources(deviceId, workingDirectory, {
instanceId: sandboxInstanceId,
topicId: sandboxTopicId,
});
- const { data: gitFiles } = useGitWorkingTreeFiles(
- deviceId,
- workingDirectory,
- data?.source === 'git',
- );
const projectSource = data?.source;
const projectRoot = data?.root ?? workingDirectory;
@@ -503,6 +502,14 @@ const Files = memo<FilesProps>(
);
const isEmpty = displayEntries.length === 0;
+ // A large project's saved tree keeps only its shallowest entries. Its own
+ // refresh replaces it within moments; only when that refresh is not running
+ // (it failed, or has not been retried) is the partial tree worth flagging.
+ const showsPartialIndex = isPersistedPartialIndex(data) && !isValidating;
+ // A restored tree / overlay is painted before the host answers again. When
+ // that refresh fails the saved view stays on screen, so it must say that it
+ // could not be revalidated instead of reading as the current directory.
+ const showsRefreshFailure = !!data && !!(error || gitError);
if (!data && isLoading) {
return (
@@ -617,8 +624,14 @@ const Files = memo<FilesProps>(
/>
</div>
)}
- {truncatedCount > 0 && (
- <div className={styles.truncated}>{t('workingPanel.files.truncatedNotice')}</div>
+ {showsRefreshFailure ? (
+ <div className={styles.truncated}>{t('workingPanel.files.refreshFailed')}</div>
+ ) : showsPartialIndex ? (
+ <div className={styles.truncated}>{t('workingPanel.files.partialIndexNotice')}</div>
+ ) : (
+ truncatedCount > 0 && (
+ <div className={styles.truncated}>{t('workingPanel.files.truncatedNotice')}</div>
+ )
)}
</Flexbox>
);
diff --git a/src/features/Conversation/WorkingSidebar/Files/useFilesPaneLocation.ts b/src/features/Conversation/WorkingSidebar/Files/useFilesPaneLocation.ts
new file mode 100644
index 00000000000..0518f203bbd
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useFilesPaneLocation.ts
@@ -0,0 +1,85 @@
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+
+import { filesLocationContextKey, useRememberedFilesLocation } from './useRememberedFilesLocation';
+
+interface FilesPaneLocationParams {
+ activeAgentId?: string;
+ /** This machine or a bound device can read a filesystem tree. */
+ filesystemEnvironmentAvailable: boolean;
+ isSandboxExecution: boolean;
+ remoteDeviceId?: string;
+ /** The instance's directory; the empty string IS the workspace root. */
+ sandboxDirectory: string;
+ sandboxDirectoryKnown: boolean;
+ sandboxInstanceId?: string;
+ sandboxTopicId?: string;
+ topicId?: string;
+ workingDirectory?: string;
+}
+
+export interface FilesPaneLocation {
+ deviceId?: string;
+ directory?: string;
+ /** A sandbox tree is read through its own instance, not a device. */
+ isSandbox: boolean;
+}
+
+/**
+ * Which tree the Files tab shows: host + directory.
+ *
+ * A sandbox resolves from its instance (or, with none picked, from the topic
+ * that names the warm session), and is final as soon as the instance directory
+ * is known. A device-backed directory is only final once the device list has
+ * loaded; until then the tree opens where this conversation last was, so its
+ * cached index can paint instead of a home-directory read or a missing tab.
+ *
+ * A directory is only showable when something can actually read it: the
+ * sandbox through its workspace API, a device or this machine through the
+ * filesystem. A topic can carry a path persisted on a desktop the web client
+ * has no way to reach, and that path is not a tree โ€” it is a string. An
+ * instance is what makes a sandbox tree addressable; persistent mode with none
+ * picked is the workspace root, which the execution plane can only resolve
+ * through a conversation, so that one still waits for the topic.
+ */
+export const useFilesPaneLocation = ({
+ activeAgentId,
+ filesystemEnvironmentAvailable,
+ isSandboxExecution,
+ remoteDeviceId,
+ sandboxDirectory,
+ sandboxDirectoryKnown,
+ sandboxInstanceId,
+ sandboxTopicId,
+ topicId,
+ workingDirectory,
+}: FilesPaneLocationParams): FilesPaneLocation => {
+ const isSandbox = isSandboxExecution && !!(sandboxInstanceId || sandboxTopicId);
+ // The empty string IS the workspace root, so only an unresolved instance
+ // withholds the directory.
+ const sandboxLiveDirectory = isSandbox
+ ? sandboxDirectoryKnown
+ ? sandboxDirectory
+ : undefined
+ : undefined;
+
+ // Not `isDeviceListLoaded`: a hydrated copy already counts as loaded but its
+ // `workingDirs` are stale, so treating it as settled would replace the
+ // conversation's remembered directory before the server confirms the list.
+ const devicesSettled = useDeviceStore(deviceSelectors.isDeviceListConfirmed);
+ // A sandbox has its own backend, and without a filesystem environment there
+ // is nothing this client can read or mutate: never open a remembered path in
+ // either case. A device id is still passed while its directory resolves so a
+ // same-host saved tree can paint before the device list answers.
+ const canReadFilesystem = !isSandbox && filesystemEnvironmentAvailable;
+ const filesLocation = useRememberedFilesLocation(
+ canReadFilesystem ? filesLocationContextKey(topicId, activeAgentId) : undefined,
+ canReadFilesystem ? { deviceId: remoteDeviceId, directory: workingDirectory } : undefined,
+ devicesSettled,
+ );
+
+ return {
+ deviceId: filesLocation?.deviceId,
+ directory: isSandbox ? sandboxLiveDirectory : filesLocation?.directory,
+ isSandbox,
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useFilesTreeSources.ts b/src/features/Conversation/WorkingSidebar/Files/useFilesTreeSources.ts
new file mode 100644
index 00000000000..83f2efbf76e
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useFilesTreeSources.ts
@@ -0,0 +1,39 @@
+import { useGitWorkingTreeFiles } from './useGitWorkingTreeFiles';
+import { useProjectFiles } from './useProjectFiles';
+
+interface FilesTreeSandbox {
+ instanceId?: string;
+ /**
+ * Live reads for a running sandbox and focus revalidation. Only the visible
+ * pane should: a hidden prefetch warms the tree once and must not keep
+ * walking the workspace.
+ */
+ live?: boolean;
+ topicId?: string;
+}
+
+/**
+ * Everything the Files tree reads: the project index and its git overlay.
+ *
+ * The overlay is requested alongside the index, not after it. Waiting for the
+ * index to say `source: 'git'` put the two reads in series, so the dirty-file
+ * colours landed a whole round-trip after the tree. It only stops once the
+ * index has settled on a non-git source; the sandbox has no git overlay.
+ */
+export const useFilesTreeSources = (
+ deviceId: string | undefined,
+ workingDirectory: string | undefined,
+ sandbox?: FilesTreeSandbox,
+) => {
+ const isSandbox = !!sandbox?.instanceId || !!sandbox?.topicId;
+ const project = useProjectFiles(deviceId, workingDirectory, sandbox);
+ const source = project.data?.source;
+ const git = useGitWorkingTreeFiles(
+ deviceId,
+ workingDirectory,
+ !isSandbox && (source === undefined || source === 'git'),
+ { revalidateOnFocus: sandbox?.live ?? true },
+ );
+
+ return { git, project };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts b/src/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts
index 46a728c98e9..9d6ef4890bf 100644
--- a/src/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts
+++ b/src/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts
@@ -1,10 +1,13 @@
import { isDesktop } from '@lobechat/const';
import type { GitWorkingTreeFiles } from '@lobechat/electron-client-ipc';
import type { GitStatusEntry } from '@pierre/trees';
+import { useMemo } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileKeys } from '@/libs/swr/keys';
-import { gitService } from '@/services/git';
+import {
+ gitWorkingTreeFilesResource,
+ projectFileActions,
+ useProjectFileStore,
+} from '@/store/projectFile';
export const buildGitStatusEntries = (files: GitWorkingTreeFiles | undefined): GitStatusEntry[] => {
if (!files) return [];
@@ -17,7 +20,8 @@ export const buildGitStatusEntries = (files: GitWorkingTreeFiles | undefined): G
};
/**
- * Dirty working-tree files for the git-status overlay. Transport-agnostic via
+ * Dirty working-tree files for the git-status overlay, read from its replica so
+ * a reload paints the last overlay with the tree. Transport-agnostic via
* `gitService` (Electron IPC local / `device.*` RPC remote). Disabled until a
* `dirPath` + `enabled`, and on web until a `deviceId` is present too.
*/
@@ -25,17 +29,24 @@ export const useGitWorkingTreeFiles = (
deviceId: string | undefined,
dirPath: string | undefined,
enabled: boolean,
+ options?: { revalidateOnFocus?: boolean },
) => {
const active = (!!deviceId || isDesktop) && !!dirPath && enabled;
- const key = active ? localFileKeys.gitWorkingTreeFiles(deviceId, dirPath!) : null;
-
- return useClientDataSWR<GitWorkingTreeFiles | undefined>(
- key,
- () => gitService.getGitWorkingTreeFiles({ deviceId, path: dirPath! }),
+ const params = useMemo(
+ () => (active ? { deviceId, dirPath: dirPath! } : null),
+ [active, deviceId, dirPath],
+ );
+ const data = useProjectFileStore((s) =>
+ params ? s.gitWorkingTreeFiles[gitWorkingTreeFilesResource.key(params)] : undefined,
+ );
+ const { error, isValidating, revalidate } = projectFileActions.useFetchGitWorkingTreeFiles(
+ params,
{
focusThrottleInterval: 5 * 1000,
- revalidateOnFocus: true,
+ revalidateOnFocus: options?.revalidateOnFocus ?? true,
shouldRetryOnError: false,
},
);
+
+ return { data, error, isValidating, mutate: revalidate };
};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts b/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts
index 5655393ca11..7306ec72869 100644
--- a/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts
+++ b/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts
@@ -1,12 +1,9 @@
import { isDesktop } from '@lobechat/const';
-import type { ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
-import { useEffect, useRef } from 'react';
+import { useEffect, useMemo, useRef } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileKeys } from '@/libs/swr/keys';
-import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
+import { projectFileActions, projectIndexResource, useProjectFileStore } from '@/store/projectFile';
/**
* How often the sandbox tree re-reads itself while an agent run is writing
@@ -17,7 +14,9 @@ import { operationSelectors } from '@/store/chat/selectors';
const SANDBOX_LIVE_REFRESH_INTERVAL = 15 * 1000;
/**
- * Project file tree for a working directory. Transport-agnostic: `fileService`
+ * Project file tree for a working directory, read from the project-index
+ * replica: a reload paints the last tree for this host + directory, then the
+ * host is asked again. Transport-agnostic: `projectFileService`
* dispatches Electron IPC (local), `device.getProjectFileIndex` RPC (remote,
* `deviceId` set), or the cloud sandbox's workspace API (`sandbox` set).
*
@@ -28,38 +27,41 @@ const SANDBOX_LIVE_REFRESH_INTERVAL = 15 * 1000;
export const useProjectFiles = (
deviceId: string | undefined,
dirPath: string | undefined,
- sandbox?: { instanceId?: string; topicId?: string },
+ sandbox?: { instanceId?: string; live?: boolean; topicId?: string },
) => {
const isSandbox = !!sandbox?.instanceId || !!sandbox?.topicId;
const enabled = isSandbox ? dirPath !== undefined : Boolean(dirPath) && (!!deviceId || isDesktop);
- // The host is part of the identity: the same path on a device and in the
- // sandbox are different trees, and `undefined` already means "this machine".
- // Keyed by the INSTANCE where there is one โ€” two conversations running the
- // same instance are looking at one tree, and keying by topic would fetch it
- // twice and let one go stale while the other refreshed.
- const host = isSandbox ? `sandbox:${sandbox?.instanceId ?? sandbox?.topicId}` : deviceId;
- const key = enabled ? localFileKeys.projectIndex(host, dirPath!) : null;
+ const params = useMemo(
+ () =>
+ enabled
+ ? {
+ deviceId,
+ dirPath: dirPath!,
+ sandboxInstanceId: sandbox?.instanceId,
+ sandboxTopicId: sandbox?.topicId,
+ }
+ : null,
+ [enabled, deviceId, dirPath, sandbox?.instanceId, sandbox?.topicId],
+ );
+ const data = useProjectFileStore((s) =>
+ params ? s.projectIndex[projectIndexResource.key(params)] : undefined,
+ );
// The sandbox tree is a mirror of a directory nobody in this browser is
// touching: the writer is the agent, on the other side of the network.
// Refetching on focus alone means a user watching a run in progress sees a
// tree from before it started, so a run is what makes this tree live.
const isRunning = useChatStore(operationSelectors.isAgentRuntimeRunning);
- const live = isSandbox && isRunning;
+ const live = isSandbox && isRunning && (sandbox?.live ?? true);
- const swr = useClientDataSWR<ProjectFileIndexResult | undefined>(
- key,
- () =>
- projectFileService.getProjectFileIndex({
- deviceId,
- sandboxInstanceId: sandbox?.instanceId,
- sandboxTopicId: sandbox?.topicId,
- scope: dirPath!,
- }),
+ const { error, isHydrated, isValidating, revalidate } = projectFileActions.useFetchProjectIndex(
+ params,
{
focusThrottleInterval: 30 * 1000,
refreshInterval: live ? SANDBOX_LIVE_REFRESH_INTERVAL : 0,
- revalidateOnFocus: true,
+ // A hidden prefetch is one-shot: no polling and no focus re-walk for a
+ // pane nobody is looking at.
+ revalidateOnFocus: sandbox?.live ?? true,
shouldRetryOnError: false,
},
);
@@ -67,12 +69,19 @@ export const useProjectFiles = (
// The interval stops with the run, so the last writes of a turn can land in
// the gap between the final poll and the end. One read on the way down is
// what makes the tree agree with the answer the user is reading.
- const { mutate } = swr;
const wasLive = useRef(live);
useEffect(() => {
- if (wasLive.current && !live) mutate();
+ if (wasLive.current && !live) void revalidate();
wasLive.current = live;
- }, [live, mutate]);
+ }, [live, revalidate]);
- return swr;
+ return {
+ data,
+ error,
+ // Only a directory with nothing to show yet is loading: a saved tree is
+ // shown as is while the host is asked again.
+ isLoading: !!params && !data && !error && (!isHydrated || isValidating),
+ isValidating,
+ mutate: revalidate,
+ };
};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useRememberedFilesLocation.ts b/src/features/Conversation/WorkingSidebar/Files/useRememberedFilesLocation.ts
new file mode 100644
index 00000000000..57634e2558c
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useRememberedFilesLocation.ts
@@ -0,0 +1,100 @@
+import { useEffect, useMemo, useRef } from 'react';
+
+import { cacheScope } from '@/libs/replica';
+import { useIsScopeTrusted } from '@/libs/swr/useCacheScope';
+import {
+ type FilesLocation,
+ peekFilesLocation,
+ projectFileActions,
+ useProjectFileStore,
+} from '@/store/projectFile';
+
+export type { FilesLocation } from '@/store/projectFile';
+
+/** The live resolution can know the host before it knows the directory. */
+export interface ResolvedFilesLocation {
+ deviceId?: string;
+ directory?: string;
+}
+
+/**
+ * The conversation a remembered location belongs to. `/` rather than `:` keeps
+ * the replica's own SWR keys clear of the `topic:` / `agent:` prefixes the SWR
+ * persistent cache matches by substring, so the row is stored once, here.
+ */
+export const filesLocationContextKey = (
+ topicId: string | null | undefined,
+ agentId: string | null | undefined,
+): string | undefined => (topicId ? `topic/${topicId}` : agentId ? `agent/${agentId}` : undefined);
+
+/**
+ * The Files tree's directory, stable across a cold start.
+ *
+ * Until the device list arrives the working directory cannot be resolved for
+ * real: a device default is unknown, so it reads as the home fallback (desktop)
+ * or nothing (web) and then jumps. The tree is keyed by that directory, so the
+ * jump meant reading the wrong tree first โ€” or hiding the tab โ€” and the saved
+ * tree for the right one never got a chance to paint. Until `settled`, the
+ * directory this conversation resolved to last time (the `filesLocation`
+ * replica) stands in; once settled, the live resolution wins and is remembered
+ * for next time.
+ */
+export const useRememberedFilesLocation = (
+ contextKey: string | undefined,
+ resolved: ResolvedFilesLocation | undefined,
+ settled: boolean,
+): FilesLocation | undefined => {
+ const scope = cacheScope.use();
+ const params = useMemo(() => (contextKey ? { contextKey } : null), [contextKey]);
+ const stored = useProjectFileStore((s) => (contextKey ? s.filesLocation[contextKey] : undefined));
+ projectFileActions.useFetchFilesLocation(params);
+ // Until the replica has hydrated the entry, its row is read here so the
+ // first frame already opens the saved tree.
+ const peeked = useMemo(
+ () => (contextKey && !stored ? peekFilesLocation(contextKey, scope) : undefined),
+ [contextKey, scope, stored],
+ );
+ const remembered = stored ?? peeked;
+ const scopeTrusted = useIsScopeTrusted();
+ const wasTrusted = useRef(scopeTrusted);
+
+ const resolvedDirectory = resolved?.directory;
+ const resolvedDeviceId = resolved?.deviceId;
+ useEffect(() => {
+ const trustJustResolved = scopeTrusted && !wasTrusted.current;
+ wasTrusted.current = scopeTrusted;
+ // Before identity resolves the engine drops the write; the value still
+ // lands in memory, so the equality check below would otherwise keep the
+ // row out of storage for the rest of the session.
+ if (!scopeTrusted) return;
+ if (!contextKey || !settled || resolvedDirectory === undefined) return;
+ if (
+ !trustJustResolved &&
+ remembered?.directory === resolvedDirectory &&
+ remembered?.deviceId === resolvedDeviceId
+ )
+ return;
+ projectFileActions.rememberFilesLocation(contextKey, {
+ deviceId: resolvedDeviceId,
+ directory: resolvedDirectory,
+ });
+ }, [contextKey, remembered, resolvedDeviceId, resolvedDirectory, scopeTrusted, settled]);
+
+ if (settled) {
+ return resolvedDirectory === undefined
+ ? undefined
+ : { deviceId: resolvedDeviceId, directory: resolvedDirectory };
+ }
+ // The live host is already known from the agent's config before the device
+ // list settles. A tree saved on another machine must not stand in for it, or
+ // the pane would read and mutate the previously bound host until then.
+ if (remembered && remembered.deviceId !== resolvedDeviceId) {
+ return resolvedDirectory === undefined
+ ? undefined
+ : { deviceId: resolvedDeviceId, directory: resolvedDirectory };
+ }
+ if (remembered) return remembered;
+ return resolvedDirectory === undefined
+ ? undefined
+ : { deviceId: resolvedDeviceId, directory: resolvedDirectory };
+};
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/filesColdStart.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/filesColdStart.test.tsx
new file mode 100644
index 00000000000..e4a56b29f92
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/__tests__/filesColdStart.test.tsx
@@ -0,0 +1,104 @@
+import { act, render, screen } from '@testing-library/react';
+import type { ComponentType } from 'react';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { useDeviceStore } from '@/store/device';
+import { DEVICE_LIST_KEY } from '@/store/device/projection';
+import { projectFileActions } from '@/store/projectFile';
+
+import {
+ agentStore,
+ effectiveConfig,
+ filesPrefetchProps,
+ filesProps,
+ globalStore,
+ reviewState,
+} from './harness';
+
+// The first frame is what the cold start is about: the deferred follow-up pass
+// that gates the other panes has not run yet. Most cases assert the settled
+// state; the cold-mount case flips this to false.
+const deferredMount = vi.hoisted(() => ({ value: true }));
+vi.mock('@/hooks/useDeferredMount', () => ({ useDeferredMount: () => deferredMount.value }));
+
+// Loaded after the harness so its module mocks are registered first.
+let AgentWorkingSidebar: ComponentType<{ availableWidth?: number }>;
+
+beforeAll(async () => {
+ AgentWorkingSidebar = (await import('../index')).default;
+});
+
+describe('AgentWorkingSidebar โ€” Files cold start', () => {
+ it('reads the Files tree while the panel is collapsed on a remembered Files tab', () => {
+ agentStore.activeAgentId = 'agent';
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ reviewState.workingDirectory = '/repo';
+ globalStore.status.showRightPanel = false;
+ globalStore.status.workingSidebarTab = 'files';
+
+ render(<AgentWorkingSidebar />);
+
+ expect(filesPrefetchProps.current).toMatchObject({ workingDirectory: '/repo' });
+ });
+
+ it('hands the read to the visible Files pane once it has mounted', () => {
+ agentStore.activeAgentId = 'agent';
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ reviewState.workingDirectory = '/repo';
+ globalStore.status.workingSidebarTab = 'files';
+
+ render(<AgentWorkingSidebar />);
+
+ expect(filesProps.current).toMatchObject({ workingDirectory: '/repo' });
+ expect(screen.queryByTestId('files-prefetch')).not.toBeInTheDocument();
+ });
+
+ it('mounts the Files pane on the first frame instead of the deferred skeleton', () => {
+ agentStore.activeAgentId = 'agent';
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ reviewState.workingDirectory = '/repo';
+ globalStore.status.workingSidebarTab = 'files';
+ deferredMount.value = false;
+
+ render(<AgentWorkingSidebar />);
+
+ // The pane owns its own "no saved tree" spinner, so the sidebar's deferred
+ // skeleton would only cover the tree that is already saved for this folder.
+ expect(screen.getByTestId('files')).toBeInTheDocument();
+ expect(screen.queryByTestId('sidebar-skeleton')).not.toBeInTheDocument();
+ deferredMount.value = true;
+ });
+
+ it('opens the tree where the conversation last was until the device list is confirmed', () => {
+ agentStore.activeAgentId = 'agent';
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ // Without the device default the cwd falls back to home.
+ reviewState.workingDirectory = '/Users/me';
+ globalStore.status.workingSidebarTab = 'files';
+ projectFileActions.rememberFilesLocation('agent/agent', { directory: '/repo' });
+
+ const { rerender } = render(<AgentWorkingSidebar />);
+ expect(filesProps.current).toEqual({ deviceId: undefined, workingDirectory: '/repo' });
+
+ act(() => {
+ // A hydrated list already counts as loaded but its `workingDirs` are
+ // stale, so only the server-confirmed state may replace the remembered
+ // directory.
+ useDeviceStore.setState((state) => ({
+ deviceListMap: { [DEVICE_LIST_KEY]: [] },
+ deviceListReplica: {
+ ...state.deviceListReplica,
+ entries: {
+ ...state.deviceListReplica.entries,
+ [DEVICE_LIST_KEY]: { pending: [], source: 'server', updatedAt: Date.now() },
+ },
+ },
+ }));
+ });
+ rerender(<AgentWorkingSidebar />);
+ expect(filesProps.current).toMatchObject({
+ deviceId: undefined,
+ workingDirectory: '/Users/me',
+ });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
new file mode 100644
index 00000000000..5167765b5fc
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
@@ -0,0 +1,509 @@
+import type { CSSProperties, MouseEvent, ReactNode } from 'react';
+import { afterEach, beforeEach, vi } from 'vitest';
+
+import { useDeviceStore } from '@/store/device';
+
+import type { ComposerTarget } from '../../types';
+
+// Shared mock harness for the WorkingSidebar suites. Import this module before
+// `../index` so every module mock is registered before the component loads.
+
+// โ”€โ”€โ”€ captured RightPanel props โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+// The real RightPanel is a controlled DraggablePanel; here we stub it so the test
+// can read back the `width` it receives and drive its `onSizeChange` directly.
+
+export interface CapturedRightPanelProps {
+ children?: ReactNode;
+ defaultWidth?: number | string;
+ expand?: boolean;
+ maxWidth?: number | string;
+ onSizeChange?: (size?: { height?: number | string; width?: number | string }) => void;
+ style?: CSSProperties;
+ width?: number | string;
+}
+
+const rightPanel = vi.hoisted(() => ({
+ current: undefined as CapturedRightPanelProps | undefined,
+}));
+
+const agentStore = vi.hoisted(() => ({
+ activeAgentId: undefined as string | undefined,
+ isHeterogeneous: false,
+ rawAgencyConfig: undefined as
+ { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,
+}));
+
+const effectiveConfig = vi.hoisted(() => ({
+ agencyConfig: undefined as
+ { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,
+ workspaceScoped: false,
+}));
+
+const platform = vi.hoisted(() => ({ isDesktop: true }));
+const linkedPR = vi.hoisted(() => ({
+ number: undefined as number | undefined,
+ branch: 'feature' as string | undefined,
+ status: undefined as string | undefined,
+}));
+
+vi.mock('@/store/device', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useFetchGitBranch: () => ({ data: linkedPR.branch ? { branch: linkedPR.branch } : undefined }),
+ useFetchGitLinkedPR: () => ({
+ data: {
+ pullRequestStatus: linkedPR.status,
+ pullRequest: linkedPR.number
+ ? { number: linkedPR.number, state: 'open', url: 'https://github.com/test/repo/pull/1' }
+ : undefined,
+ },
+ }),
+}));
+
+vi.mock('../PullRequest', async () => {
+ const { useState } = await import('react');
+ return {
+ default: function PullRequestDraft() {
+ const [draft, setDraft] = useState('');
+ return (
+ <input
+ aria-label="PR draft"
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ />
+ );
+ },
+ };
+});
+
+const filesProps = vi.hoisted(() => ({
+ current: undefined as { deviceId?: string; workingDirectory: string } | undefined,
+}));
+const filesPrefetchProps = vi.hoisted(() => ({
+ current: undefined as { deviceId?: string; workingDirectory: string } | undefined,
+}));
+
+const reviewState = vi.hoisted(() => ({
+ repoType: undefined as string | undefined,
+ setRepoType: undefined as ((repoType?: string) => void) | undefined,
+ showTree: false,
+ workingDirectory: undefined as string | undefined,
+}));
+
+const businessTabs = vi.hoisted(() => ({
+ current: [] as { key: string; label: string; pane: ReactNode }[],
+}));
+
+const paramsSectionState = vi.hoisted(() => ({
+ pending: new Promise<never>(() => undefined),
+ suspend: false,
+}));
+
+const browserPanes = vi.hoisted(() => ({
+ current: [] as {
+ composerTarget: ComposerTarget;
+ onMetadataChange?: (metadata: { faviconUrl?: string; title: string; url: string }) => void;
+ sessionId: string;
+ }[],
+}));
+
+const renderedReview = vi.hoisted(() => ({
+ current: undefined as { composerTarget: ComposerTarget } | undefined,
+}));
+
+const localStorageState = vi.hoisted(() => ({
+ openTabsByContext: {} as Record<string, string[]>,
+ pinnedTabsByAgent: {} as Record<string, string[]>,
+}));
+
+const dropdownMenuState = vi.hoisted(() => ({
+ items: [] as any[],
+ onOpenChangeComplete: undefined as ((open: boolean) => void) | undefined,
+}));
+
+const workspace = vi.hoisted(() => ({ id: undefined as string | undefined }));
+
+const chatStore = vi.hoisted(() => ({
+ activeAgentId: undefined as string | undefined,
+ activeGroupId: undefined as string | undefined,
+ activeThreadId: undefined as string | undefined,
+ activeTopicId: undefined as string | undefined,
+ openTopicComments: vi.fn(),
+ portalStack: [] as Array<{ startMessageId?: string; threadId?: string; type: string }>,
+ showPortal: false,
+ threadMaps: {} as Record<string, any[]>,
+ // read by the real topicSelectors.currentTopicMetadata (sourcePath resolution)
+ topicDataMap: {} as Record<string, unknown>,
+ topicDetailMap: {} as Record<string, unknown>,
+}));
+
+const globalStore = vi.hoisted(() => ({
+ openWorkingSidebar: vi.fn(),
+ updateSystemStatus: vi.fn(),
+ toggleRightPanel: vi.fn(),
+ toggleTerminalPanel: vi.fn(),
+ setWorkingSidebarTab: vi.fn(),
+ status: {
+ portalWidth: 400 as number | undefined,
+ portalWidths: undefined as Record<string, number> | undefined,
+ showRightPanel: true,
+ showWorkingOverview: true as boolean | undefined,
+ workingSidebarTab: 'params' as string | undefined,
+ workingSidebarTabRequest: undefined as { nonce: number; tab: string } | undefined,
+ workingSidebarWidth: 360 as number | undefined,
+ },
+}));
+
+vi.mock('motion/react', () => ({
+ AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('motion/react-m', () => ({
+ div: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+}));
+
+vi.mock('@/features/RightPanel', () => ({
+ default: (props: CapturedRightPanelProps) => {
+ rightPanel.current = props;
+ return (
+ <div data-testid="right-panel" style={props.style}>
+ {props.children}
+ </div>
+ );
+ },
+}));
+
+// โ”€โ”€โ”€ stub every downstream dependency so the sidebar renders deterministically โ”€โ”€
+
+vi.mock('../Files', () => ({
+ default: (props: { deviceId?: string; workingDirectory: string }) => {
+ filesProps.current = props;
+ return <div data-testid="files" />;
+ },
+}));
+vi.mock('../Files/FilesPrefetch', () => ({
+ default: (props: { deviceId?: string; workingDirectory: string }) => {
+ filesPrefetchProps.current = props;
+ return <div data-testid="files-prefetch" />;
+ },
+}));
+vi.mock('../Review', () => ({
+ default: (props: { composerTarget: ComposerTarget }) => {
+ renderedReview.current = props;
+ return <div data-testid="review" />;
+ },
+}));
+vi.mock('../ProgressSection', () => ({ default: () => <div /> }));
+vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));
+vi.mock('@/features/NavPanel/components/SkeletonList', () => ({
+ default: () => <div data-testid="sidebar-skeleton" />,
+}));
+vi.mock('../ParamsSection', () => ({
+ default: () => {
+ if (paramsSectionState.suspend) throw paramsSectionState.pending;
+ return <div data-testid="params-section" />;
+ },
+}));
+vi.mock('../WorksSection', () => ({ default: () => <div /> }));
+vi.mock('../Browser', () => ({
+ default: (props: (typeof browserPanes.current)[number]) => {
+ browserPanes.current.push(props);
+ return <div data-testid={`browser-pane-${props.sessionId}`} />;
+ },
+}));
+vi.mock('../Overview', () => ({
+ default: ({
+ environmentAvailable,
+ onOpenTab,
+ pullRequest,
+ workingDirectory,
+ }: {
+ environmentAvailable: boolean;
+ onOpenTab: (tab: string) => void;
+ pullRequest?: { number: number };
+ workingDirectory?: string;
+ }) => (
+ <>
+ <button type="button" onClick={() => onOpenTab('review')}>
+ Open Review from Overview
+ </button>
+ {pullRequest && (
+ <button type="button" onClick={() => onOpenTab('pr')}>
+ Open Pull Request from Overview
+ </button>
+ )}
+ {environmentAvailable && <span>Workspace environment</span>}
+ {workingDirectory && <span>{workingDirectory}</span>}
+ </>
+ ),
+}));
+vi.mock('@/features/Portal/TopicComments/Sidebar', () => ({
+ default: () => <div data-testid="comments" />,
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => agentStore,
+ useAgentStore: (selector: (s: typeof agentStore) => unknown) => selector(agentStore),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => agentStore.rawAgencyConfig,
+ isWorkspaceAgentById: () => () => false,
+ },
+ agentSelectors: {
+ isCurrentAgentHeterogeneous: () => agentStore.isHeterogeneous,
+ },
+ chatConfigByIdSelectors: {
+ isChatModeById: () => () => false,
+ },
+}));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (s: typeof globalStore) => unknown) => selector(globalStore),
+}));
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ portalWidth: (s: typeof globalStore) => s.status.portalWidth || 400,
+ portalWidths: (s: typeof globalStore) => s.status.portalWidths,
+ showWorkingOverview: (s: typeof globalStore) =>
+ s.status.showWorkingOverview ?? !s.status.showRightPanel,
+ workingSidebarWidth: (s: typeof globalStore) => s.status.workingSidebarWidth || 360,
+ },
+}));
+vi.mock('@/store/electron', () => ({ useElectronStore: () => undefined }));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: typeof chatStore) => unknown) => selector(chatStore),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => workspace.id,
+ useActiveWorkspaceId: () => workspace.id,
+}));
+
+vi.mock('@/business/client/features/WorkingSidebarTabs', () => ({
+ useBusinessWorkingSidebarTabs: () => businessTabs.current,
+}));
+
+vi.mock('@/features/ChatInput/ControlBar/useRepoType', async () => {
+ const { useState } = await import('react');
+
+ return {
+ useRepoType: () => {
+ const [repoType, setRepoType] = useState(reviewState.repoType);
+ reviewState.setRepoType = setRepoType;
+ return repoType;
+ },
+ };
+});
+vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({
+ useEffectiveWorkingDirectory: () => reviewState.workingDirectory,
+}));
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: () => ({
+ agencyConfig: effectiveConfig.agencyConfig,
+ workspaceScoped: effectiveConfig.workspaceScoped,
+ }),
+}));
+vi.mock('@/hooks/useLocalStorageState', async () => {
+ const { useState } = await import('react');
+
+ return {
+ useLocalStorageState: (key: string) =>
+ useState(
+ key === 'lobechat-review-tree'
+ ? reviewState.showTree
+ : key === 'lobechat-working-sidebar-pinned-tabs-v1'
+ ? localStorageState.pinnedTabsByAgent
+ : localStorageState.openTabsByContext,
+ ),
+ };
+});
+vi.mock('@/helpers/agentWorkingDirectory', () => ({ resolveTargetDeviceId: () => undefined }));
+vi.mock('@/helpers/executionTarget', () => ({
+ resolveExecutionTarget: (
+ agencyConfig: { executionTarget?: 'device' | 'local' } | undefined,
+ options: { clientExecutionAvailable: boolean; workspaceScoped?: boolean },
+ ) => {
+ if (options.workspaceScoped) return 'device';
+ const target = agencyConfig?.executionTarget;
+ if (!options.clientExecutionAvailable && target === 'local') return 'sandbox';
+ return target ?? (options.clientExecutionAvailable ? 'local' : 'none');
+ },
+}));
+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));
+vi.mock('@/const/version', () => ({
+ get isDesktop() {
+ return platform.isDesktop;
+ },
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ const factories: ((original: typeof importOriginal) => unknown)[] = [
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button aria-label={title} type="button" onClick={onClick} />
+ ),
+ Skeleton: () => <div data-testid="params-loading" />,
+ }),
+ async (importOriginal) => {
+ const { useState } = await import('react');
+ const actual = (await importOriginal()) as Record<string, unknown>;
+
+ return {
+ ...actual,
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button aria-label={title} type="button" onClick={onClick} />
+ ),
+ ContextMenuTrigger: ({ children, items }: { children: ReactNode; items: any[] }) => {
+ const [open, setOpen] = useState(false);
+ const menuItems = items.filter((item) => item && item.type !== 'divider');
+
+ return (
+ <span
+ onContextMenu={(event: MouseEvent) => {
+ event.preventDefault();
+ setOpen(true);
+ }}
+ >
+ {children}
+ {open &&
+ menuItems.map((item) => (
+ <button
+ disabled={item.disabled}
+ key={item.key}
+ type="button"
+ onClick={item.onClick}
+ >
+ {item.label}
+ </button>
+ ))}
+ </span>
+ );
+ },
+ DropdownMenu: ({
+ children,
+ items,
+ onOpenChangeComplete,
+ }: {
+ children: ReactNode;
+ items: any[] | (() => any[]);
+ onOpenChangeComplete?: (open: boolean) => void;
+ }) => {
+ const [open, setOpen] = useState(false);
+ const resolvedItems = typeof items === 'function' ? items() : items;
+ const menuItems = resolvedItems.flatMap((item) => item.children ?? []);
+ dropdownMenuState.items = resolvedItems;
+ dropdownMenuState.onOpenChangeComplete = onOpenChangeComplete;
+
+ return (
+ <div>
+ <span onClick={() => setOpen((value) => !value)}>{children}</span>
+ {open &&
+ menuItems.map((item) => (
+ <button key={item.key} type="button" onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </div>
+ );
+ },
+ Skeleton: {
+ Text: () => <div data-testid="params-loading" />,
+ },
+ };
+ },
+ async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return {
+ ...actual,
+ createStaticStyles: () => () => ({}),
+ };
+ },
+ ];
+ const merged: Record<string, unknown> = { ...actual };
+ for (const factory of factories) {
+ const part = (await factory(importOriginal)) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
+ }
+ return merged;
+});
+
+beforeEach(() => {
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ callback(0);
+ return 1;
+ });
+ businessTabs.current = [];
+ browserPanes.current = [];
+ paramsSectionState.suspend = false;
+ localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };
+ localStorageState.pinnedTabsByAgent = {};
+ workspace.id = undefined;
+ chatStore.activeAgentId = undefined;
+ chatStore.activeGroupId = undefined;
+ chatStore.activeThreadId = undefined;
+ chatStore.activeTopicId = undefined;
+ chatStore.portalStack = [];
+ chatStore.showPortal = false;
+ chatStore.threadMaps = {};
+ chatStore.openTopicComments.mockReset();
+ agentStore.activeAgentId = undefined;
+ agentStore.isHeterogeneous = false;
+ agentStore.rawAgencyConfig = undefined;
+ effectiveConfig.agencyConfig = undefined;
+ effectiveConfig.workspaceScoped = false;
+ platform.isDesktop = true;
+ linkedPR.number = undefined;
+ linkedPR.branch = 'feature';
+ linkedPR.status = undefined;
+ chatStore.topicDataMap = {};
+ chatStore.topicDetailMap = {};
+ filesProps.current = undefined;
+ filesPrefetchProps.current = undefined;
+ localStorage.clear();
+ useDeviceStore.setState({ deviceListMap: {} });
+ renderedReview.current = undefined;
+ reviewState.repoType = undefined;
+ reviewState.setRepoType = undefined;
+ reviewState.showTree = false;
+ reviewState.workingDirectory = undefined;
+ dropdownMenuState.onOpenChangeComplete = undefined;
+ dropdownMenuState.items = [];
+ globalStore.status.workingSidebarWidth = 360;
+ globalStore.status.showRightPanel = true;
+ globalStore.status.showWorkingOverview = true;
+ globalStore.status.workingSidebarTab = 'params';
+ globalStore.status.workingSidebarTabRequest = undefined;
+ globalStore.updateSystemStatus.mockReset();
+ globalStore.openWorkingSidebar.mockReset();
+ globalStore.toggleRightPanel.mockReset();
+ globalStore.toggleTerminalPanel.mockReset();
+ globalStore.setWorkingSidebarTab.mockReset();
+});
+
+afterEach(() => {
+ rightPanel.current = undefined;
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+export {
+ agentStore,
+ browserPanes,
+ businessTabs,
+ chatStore,
+ dropdownMenuState,
+ effectiveConfig,
+ filesPrefetchProps,
+ filesProps,
+ globalStore,
+ linkedPR,
+ localStorageState,
+ paramsSectionState,
+ platform,
+ renderedReview,
+ reviewState,
+ rightPanel,
+ workspace,
+};
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index b8b664019ba..d4695f80980 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -1,478 +1,36 @@
import type { DeviceGitPullRequestDetail } from '@lobechat/types';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { CSSProperties, MouseEvent, ReactNode } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ComponentType } from 'react';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import type { ComposerTarget } from '../../types';
-import AgentWorkingSidebar from '../index';
import PullRequestSections from '../PullRequest/Sections';
-
-// โ”€โ”€โ”€ captured RightPanel props โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-// The real RightPanel is a controlled DraggablePanel; here we stub it so the test
-// can read back the `width` it receives and drive its `onSizeChange` directly.
-
-interface CapturedRightPanelProps {
- children?: ReactNode;
- defaultWidth?: number | string;
- expand?: boolean;
- maxWidth?: number | string;
- onSizeChange?: (size?: { height?: number | string; width?: number | string }) => void;
- style?: CSSProperties;
- width?: number | string;
-}
-
-const rightPanel = vi.hoisted(() => ({
- current: undefined as CapturedRightPanelProps | undefined,
-}));
-
-const agentStore = vi.hoisted(() => ({
- activeAgentId: undefined as string | undefined,
- isHeterogeneous: false,
- rawAgencyConfig: undefined as
- { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,
-}));
-
-const effectiveConfig = vi.hoisted(() => ({
- agencyConfig: undefined as
- { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,
- workspaceScoped: false,
-}));
-
-const platform = vi.hoisted(() => ({ isDesktop: true }));
-const linkedPR = vi.hoisted(() => ({
- number: undefined as number | undefined,
- branch: 'feature' as string | undefined,
- status: undefined as string | undefined,
-}));
-
-vi.mock('@/store/device', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- useFetchGitBranch: () => ({ data: linkedPR.branch ? { branch: linkedPR.branch } : undefined }),
- useFetchGitLinkedPR: () => ({
- data: {
- pullRequestStatus: linkedPR.status,
- pullRequest: linkedPR.number
- ? { number: linkedPR.number, state: 'open', url: 'https://github.com/test/repo/pull/1' }
- : undefined,
- },
- }),
-}));
-
-vi.mock('../PullRequest', async () => {
- const { useState } = await import('react');
- return {
- default: function PullRequestDraft() {
- const [draft, setDraft] = useState('');
- return (
- <input
- aria-label="PR draft"
- value={draft}
- onChange={(event) => setDraft(event.target.value)}
- />
- );
- },
- };
-});
-
-const filesProps = vi.hoisted(() => ({
- current: undefined as { deviceId?: string; workingDirectory: string } | undefined,
-}));
-
-const reviewState = vi.hoisted(() => ({
- repoType: undefined as string | undefined,
- setRepoType: undefined as ((repoType?: string) => void) | undefined,
- showTree: false,
- workingDirectory: undefined as string | undefined,
-}));
-
-const businessTabs = vi.hoisted(() => ({
- current: [] as { key: string; label: string; pane: ReactNode }[],
-}));
-
-const paramsSectionState = vi.hoisted(() => ({
- pending: new Promise<never>(() => undefined),
- suspend: false,
-}));
-
-const browserPanes = vi.hoisted(() => ({
- current: [] as {
- composerTarget: ComposerTarget;
- onMetadataChange?: (metadata: { faviconUrl?: string; title: string; url: string }) => void;
- sessionId: string;
- }[],
-}));
-
-const renderedReview = vi.hoisted(() => ({
- current: undefined as { composerTarget: ComposerTarget } | undefined,
-}));
-
-const localStorageState = vi.hoisted(() => ({
- openTabsByContext: {} as Record<string, string[]>,
- pinnedTabsByAgent: {} as Record<string, string[]>,
-}));
-
-const dropdownMenuState = vi.hoisted(() => ({
- items: [] as any[],
- onOpenChangeComplete: undefined as ((open: boolean) => void) | undefined,
-}));
-
-const workspace = vi.hoisted(() => ({ id: undefined as string | undefined }));
-
-const chatStore = vi.hoisted(() => ({
- activeAgentId: undefined as string | undefined,
- activeGroupId: undefined as string | undefined,
- activeThreadId: undefined as string | undefined,
- activeTopicId: undefined as string | undefined,
- openTopicComments: vi.fn(),
- portalStack: [] as Array<{ startMessageId?: string; threadId?: string; type: string }>,
- showPortal: false,
- threadMaps: {} as Record<string, any[]>,
- // read by the real topicSelectors.currentTopicMetadata (sourcePath resolution)
- topicDataMap: {} as Record<string, unknown>,
- topicDetailMap: {} as Record<string, unknown>,
-}));
-
-const globalStore = vi.hoisted(() => ({
- openWorkingSidebar: vi.fn(),
- updateSystemStatus: vi.fn(),
- toggleRightPanel: vi.fn(),
- toggleTerminalPanel: vi.fn(),
- setWorkingSidebarTab: vi.fn(),
- status: {
- portalWidth: 400 as number | undefined,
- portalWidths: undefined as Record<string, number> | undefined,
- showRightPanel: true,
- showWorkingOverview: true as boolean | undefined,
- workingSidebarTab: 'params' as string | undefined,
- workingSidebarTabRequest: undefined as { nonce: number; tab: string } | undefined,
- workingSidebarWidth: 360 as number | undefined,
- },
-}));
-
-vi.mock('motion/react', () => ({
- AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('motion/react-m', () => ({
- div: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
-}));
-
-vi.mock('@/features/RightPanel', () => ({
- default: (props: CapturedRightPanelProps) => {
- rightPanel.current = props;
- return (
- <div data-testid="right-panel" style={props.style}>
- {props.children}
- </div>
- );
- },
-}));
-
-// โ”€โ”€โ”€ stub every downstream dependency so the sidebar renders deterministically โ”€โ”€
-
-vi.mock('../Files', () => ({
- default: (props: { deviceId?: string; workingDirectory: string }) => {
- filesProps.current = props;
- return <div data-testid="files" />;
- },
-}));
-vi.mock('../Review', () => ({
- default: (props: { composerTarget: ComposerTarget }) => {
- renderedReview.current = props;
- return <div data-testid="review" />;
- },
-}));
-vi.mock('../ProgressSection', () => ({ default: () => <div /> }));
-vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));
-vi.mock('@/features/NavPanel/components/SkeletonList', () => ({ default: () => <div /> }));
-vi.mock('../ParamsSection', () => ({
- default: () => {
- if (paramsSectionState.suspend) throw paramsSectionState.pending;
- return <div data-testid="params-section" />;
- },
-}));
-vi.mock('../WorksSection', () => ({ default: () => <div /> }));
-vi.mock('../Browser', () => ({
- default: (props: (typeof browserPanes.current)[number]) => {
- browserPanes.current.push(props);
- return <div data-testid={`browser-pane-${props.sessionId}`} />;
- },
-}));
-vi.mock('../Overview', () => ({
- default: ({
- environmentAvailable,
- onOpenTab,
- pullRequest,
- workingDirectory,
- }: {
- environmentAvailable: boolean;
- onOpenTab: (tab: string) => void;
- pullRequest?: { number: number };
- workingDirectory?: string;
- }) => (
- <>
- <button type="button" onClick={() => onOpenTab('review')}>
- Open Review from Overview
- </button>
- {pullRequest && (
- <button type="button" onClick={() => onOpenTab('pr')}>
- Open Pull Request from Overview
- </button>
- )}
- {environmentAvailable && <span>Workspace environment</span>}
- {workingDirectory && <span>{workingDirectory}</span>}
- </>
- ),
-}));
-vi.mock('@/features/Portal/TopicComments/Sidebar', () => ({
- default: () => <div data-testid="comments" />,
-}));
-
-vi.mock('@/store/agent', () => ({
- getAgentStoreState: () => agentStore,
- useAgentStore: (selector: (s: typeof agentStore) => unknown) => selector(agentStore),
-}));
-vi.mock('@/store/agent/selectors', () => ({
- agentByIdSelectors: {
- getAgencyConfigById: () => () => agentStore.rawAgencyConfig,
- isWorkspaceAgentById: () => () => false,
- },
- agentSelectors: {
- isCurrentAgentHeterogeneous: () => agentStore.isHeterogeneous,
- },
- chatConfigByIdSelectors: {
- isChatModeById: () => () => false,
- },
-}));
-vi.mock('@/store/global', () => ({
- useGlobalStore: (selector: (s: typeof globalStore) => unknown) => selector(globalStore),
-}));
-vi.mock('@/store/global/selectors', () => ({
- systemStatusSelectors: {
- portalWidth: (s: typeof globalStore) => s.status.portalWidth || 400,
- portalWidths: (s: typeof globalStore) => s.status.portalWidths,
- showWorkingOverview: (s: typeof globalStore) =>
- s.status.showWorkingOverview ?? !s.status.showRightPanel,
- workingSidebarWidth: (s: typeof globalStore) => s.status.workingSidebarWidth || 360,
- },
-}));
-vi.mock('@/store/electron', () => ({ useElectronStore: () => undefined }));
-vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: typeof chatStore) => unknown) => selector(chatStore),
-}));
-
-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- useActiveWorkspaceId: () => workspace.id,
-}));
-
-vi.mock('@/business/client/features/WorkingSidebarTabs', () => ({
- useBusinessWorkingSidebarTabs: () => businessTabs.current,
-}));
-
-vi.mock('@/features/ChatInput/ControlBar/useRepoType', async () => {
- const { useState } = await import('react');
-
- return {
- useRepoType: () => {
- const [repoType, setRepoType] = useState(reviewState.repoType);
- reviewState.setRepoType = setRepoType;
- return repoType;
- },
- };
-});
-vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({
- useEffectiveWorkingDirectory: () => reviewState.workingDirectory,
-}));
-vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
- useEffectiveAgencyConfig: () => ({
- agencyConfig: effectiveConfig.agencyConfig,
- workspaceScoped: effectiveConfig.workspaceScoped,
- }),
-}));
-vi.mock('@/hooks/useLocalStorageState', async () => {
- const { useState } = await import('react');
-
- return {
- useLocalStorageState: (key: string) =>
- useState(
- key === 'lobechat-review-tree'
- ? reviewState.showTree
- : key === 'lobechat-working-sidebar-pinned-tabs-v1'
- ? localStorageState.pinnedTabsByAgent
- : localStorageState.openTabsByContext,
- ),
- };
-});
-vi.mock('@/helpers/agentWorkingDirectory', () => ({ resolveTargetDeviceId: () => undefined }));
-vi.mock('@/helpers/executionTarget', () => ({
- resolveExecutionTarget: (
- agencyConfig: { executionTarget?: 'device' | 'local' } | undefined,
- options: { clientExecutionAvailable: boolean; workspaceScoped?: boolean },
- ) => {
- if (options.workspaceScoped) return 'device';
- const target = agencyConfig?.executionTarget;
- if (!options.clientExecutionAvailable && target === 'local') return 'sandbox';
- return target ?? (options.clientExecutionAvailable ? 'local' : 'none');
- },
-}));
-vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));
-vi.mock('@/const/version', () => ({
- get isDesktop() {
- return platform.isDesktop;
- },
-}));
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const actual = await importOriginal<Record<string, unknown>>();
- const factories: ((original: typeof importOriginal) => unknown)[] = [
- async (importOriginal) => ({
- ...(await importOriginal<object>()),
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button aria-label={title} type="button" onClick={onClick} />
- ),
- Skeleton: () => <div data-testid="params-loading" />,
- }),
- async (importOriginal) => {
- const { useState } = await import('react');
- const actual = (await importOriginal()) as Record<string, unknown>;
-
- return {
- ...actual,
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button aria-label={title} type="button" onClick={onClick} />
- ),
- ContextMenuTrigger: ({ children, items }: { children: ReactNode; items: any[] }) => {
- const [open, setOpen] = useState(false);
- const menuItems = items.filter((item) => item && item.type !== 'divider');
-
- return (
- <span
- onContextMenu={(event: MouseEvent) => {
- event.preventDefault();
- setOpen(true);
- }}
- >
- {children}
- {open &&
- menuItems.map((item) => (
- <button
- disabled={item.disabled}
- key={item.key}
- type="button"
- onClick={item.onClick}
- >
- {item.label}
- </button>
- ))}
- </span>
- );
- },
- DropdownMenu: ({
- children,
- items,
- onOpenChangeComplete,
- }: {
- children: ReactNode;
- items: any[] | (() => any[]);
- onOpenChangeComplete?: (open: boolean) => void;
- }) => {
- const [open, setOpen] = useState(false);
- const resolvedItems = typeof items === 'function' ? items() : items;
- const menuItems = resolvedItems.flatMap((item) => item.children ?? []);
- dropdownMenuState.items = resolvedItems;
- dropdownMenuState.onOpenChangeComplete = onOpenChangeComplete;
-
- return (
- <div>
- <span onClick={() => setOpen((value) => !value)}>{children}</span>
- {open &&
- menuItems.map((item) => (
- <button key={item.key} type="button" onClick={item.onClick}>
- {item.label}
- </button>
- ))}
- </div>
- );
- },
- Skeleton: {
- Text: () => <div data-testid="params-loading" />,
- },
- };
- },
- async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- createStaticStyles: () => () => ({}),
- };
- },
- ];
- const merged: Record<string, unknown> = { ...actual };
- for (const factory of factories) {
- const part = (await factory(importOriginal)) as Record<string, unknown>;
- for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
- }
- return merged;
-});
-
-beforeEach(() => {
- vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
- callback(0);
- return 1;
- });
- businessTabs.current = [];
- browserPanes.current = [];
- paramsSectionState.suspend = false;
- localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };
- localStorageState.pinnedTabsByAgent = {};
- workspace.id = undefined;
- chatStore.activeAgentId = undefined;
- chatStore.activeGroupId = undefined;
- chatStore.activeThreadId = undefined;
- chatStore.activeTopicId = undefined;
- chatStore.portalStack = [];
- chatStore.showPortal = false;
- chatStore.threadMaps = {};
- chatStore.openTopicComments.mockReset();
- agentStore.activeAgentId = undefined;
- agentStore.isHeterogeneous = false;
- agentStore.rawAgencyConfig = undefined;
- effectiveConfig.agencyConfig = undefined;
- effectiveConfig.workspaceScoped = false;
- platform.isDesktop = true;
- linkedPR.number = undefined;
- linkedPR.branch = 'feature';
- linkedPR.status = undefined;
- chatStore.topicDataMap = {};
- chatStore.topicDetailMap = {};
- filesProps.current = undefined;
- renderedReview.current = undefined;
- reviewState.repoType = undefined;
- reviewState.setRepoType = undefined;
- reviewState.showTree = false;
- reviewState.workingDirectory = undefined;
- dropdownMenuState.onOpenChangeComplete = undefined;
- dropdownMenuState.items = [];
- globalStore.status.workingSidebarWidth = 360;
- globalStore.status.showRightPanel = true;
- globalStore.status.showWorkingOverview = true;
- globalStore.status.workingSidebarTab = 'params';
- globalStore.status.workingSidebarTabRequest = undefined;
- globalStore.updateSystemStatus.mockReset();
- globalStore.openWorkingSidebar.mockReset();
- globalStore.toggleRightPanel.mockReset();
- globalStore.toggleTerminalPanel.mockReset();
- globalStore.setWorkingSidebarTab.mockReset();
-});
-
-afterEach(() => {
- rightPanel.current = undefined;
- vi.restoreAllMocks();
- vi.clearAllMocks();
+import {
+ agentStore,
+ browserPanes,
+ businessTabs,
+ chatStore,
+ dropdownMenuState,
+ effectiveConfig,
+ filesProps,
+ globalStore,
+ linkedPR,
+ localStorageState,
+ paramsSectionState,
+ platform,
+ renderedReview,
+ reviewState,
+ rightPanel,
+ workspace,
+} from './harness';
+
+// Loaded after the mock harness so module mocks are registered first.
+let AgentWorkingSidebar: ComponentType<{ availableWidth?: number }>;
+
+beforeAll(async () => {
+ AgentWorkingSidebar = (await import('../index')).default;
});
describe('AgentWorkingSidebar โ€” controlled panel width', () => {
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 48fdc598adf..27b798d0c89 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -56,7 +56,6 @@ import {
} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';
import { useSandboxMode } from '@/features/ChatInput/ControlBar/useSandboxMode';
-import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { getPortalViewWidth } from '@/features/Portal/portalWidth';
import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';
import RightPanel from '@/features/RightPanel';
@@ -82,7 +81,9 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';
-import Files from './Files';
+import DeferredSkeleton from './DeferredSkeleton';
+import FilesPane from './Files/FilesPane';
+import { useFilesPaneLocation } from './Files/useFilesPaneLocation';
import { sidebarWidthBudget } from './fitsBesidePortal';
import { MAX_PANEL_WIDTH, MIN_PANEL_WIDTH, OVERVIEW_PANEL_WIDTH } from './layout';
import Overview from './Overview';
@@ -408,27 +409,19 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const filesystemEnvironmentAvailable = isLocalExecution || isDeviceMode;
const environmentWorkingDirectory = filesystemEnvironmentAvailable ? workingDirectory : undefined;
const environmentRepoType = filesystemEnvironmentAvailable ? repoType : undefined;
- // Files tab is an agent-mode affordance โ€” in plain chat mode the working
- // directory is irrelevant to the user, so hide the tab even when one resolves.
- // Which directory the tree shows, and therefore whether there is a tree at
- // all. Kept as one value rather than a pair of conditions: the sandbox's root
- // is the empty string, so "has a directory" and "is truthy" part ways here,
- // and the tab's availability has to follow the value it will render.
- // A directory is only showable when something can actually read it: the
- // sandbox through its workspace API, a device or this machine through the
- // filesystem. A topic can carry a path persisted on a desktop the web client
- // has no way to reach, and that path is not a tree โ€” it is a string.
- // An instance is what makes a sandbox tree addressable. Persistent mode with
- // none picked is the workspace root, which the execution plane can only
- // resolve through a conversation โ€” so that one still waits for the topic.
- const filesDirectory =
- isSandboxExecution && (sandboxInstanceId || sandboxTopicId)
- ? sandboxDirectoryKnown
- ? sandboxDirectory
- : undefined
- : filesystemEnvironmentAvailable
- ? workingDirectory
- : undefined;
+ // Files is agent-mode only; the hook owns which directory (if any) is showable.
+ const { deviceId: filesDeviceId, directory: filesDirectory } = useFilesPaneLocation({
+ activeAgentId,
+ filesystemEnvironmentAvailable,
+ isSandboxExecution,
+ remoteDeviceId,
+ sandboxDirectory,
+ sandboxDirectoryKnown,
+ sandboxInstanceId,
+ sandboxTopicId,
+ topicId,
+ workingDirectory,
+ });
const filesAvailable = !isChatMode && filesDirectory !== undefined;
const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;
const snapshotConfig =
@@ -715,7 +708,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
},
[availableTabs, updateOpenedTabs, updatePinnedTabs],
);
-
const unpinTab = useCallback(
(tab: string) => {
// A tab restored only through its agent pin should remain open in the
@@ -725,7 +717,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
},
[updateOpenedTabs, updatePinnedTabs],
);
-
const closeTabs = useCallback(
(tabs: string[], fallbackTab = 'overview') => {
const removableTabs = new Set(tabs.filter((tab) => !pinnedTabsSet.has(tab)));
@@ -1124,7 +1115,20 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
/>
</Flexbox>
<Flexbox className={styles.body} width={'100%'}>
- {!contentReady && <SkeletonList paddingBlock={8} paddingInline={8} rows={6} />}
+ {!contentReady && storedTab !== 'files' && activeTab !== 'files' && (
+ <DeferredSkeleton />
+ )}
+ <FilesPane
+ active={!!showRightPanel && activeTab === 'files'}
+ available={filesAvailable}
+ className={styles.pane}
+ contentReady={contentReady || (activeTab === 'files' && filesAvailable)}
+ deviceId={filesDeviceId}
+ directory={filesDirectory}
+ prefetch={activeTab === 'files' && (!showRightPanel || !contentReady)}
+ sandboxInstanceId={isSandboxExecution ? sandboxInstanceId : undefined}
+ sandboxTopicId={sandboxTopicId}
+ />
{contentReady && (
<>
{commentsAvailable && (
@@ -1173,18 +1177,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
</Flexbox>
</Activity>
)}
- {filesAvailable && (
- <Activity mode={showRightPanel && activeTab === 'files' ? 'visible' : 'hidden'}>
- <Flexbox className={styles.pane}>
- <Files
- deviceId={remoteDeviceId}
- sandboxInstanceId={isSandboxExecution ? sandboxInstanceId : undefined}
- sandboxTopicId={sandboxTopicId}
- workingDirectory={filesDirectory}
- />
- </Flexbox>
- </Activity>
- )}
{browserAvailable &&
openedTabs.filter(isBrowserTab).map((tab) => {
const sessionId =
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index 23b9e6bfcbf..5c913a24531 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -89,11 +89,13 @@ export const cacheScope: ReplicaScope = {
export type ReplicaStorageKind = 'indexedDB' | 'localStorage' | 'memory';
-type AppStorageOption<TData> = ReplicaStorageKind | ReplicaStorage<TData>;
+type AppStorageOption<TData> =
+ ReplicaStorageKind | ReplicaStorage<TData> | ((namespace: string) => ReplicaStorage<TData>);
const resolveStorage =
<TData>(storage: AppStorageOption<TData> = 'indexedDB') =>
(namespace: string): ReplicaStorage<TData> | undefined => {
+ if (typeof storage === 'function') return storage(namespace);
if (typeof storage === 'object') return storage;
if (storage === 'indexedDB') return new IndexedDBQueryProjectionStorage<TData>({ namespace });
if (storage === 'localStorage')
diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.ts
index 5d09957b4f7..979e4846b25 100644
--- a/src/libs/swr/useCacheScope.ts
+++ b/src/libs/swr/useCacheScope.ts
@@ -180,3 +180,9 @@ export const getCacheScope = (): string => {
* anonymous scope is a legitimate durable context there).
*/
export const isScopeTrusted = (): boolean => isIdentityResolved(getUserStoreState());
+
+/**
+ * Reactive form of {@link isScopeTrusted}: re-renders the caller when the
+ * identity round-trip lands, even if the scope string itself did not change.
+ */
+export const useIsScopeTrusted = (): boolean => useUserStore(isIdentityResolved);
diff --git a/src/store/projectFile/action.ts b/src/store/projectFile/action.ts
new file mode 100644
index 00000000000..bbd8ee36681
--- /dev/null
+++ b/src/store/projectFile/action.ts
@@ -0,0 +1,67 @@
+import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
+import type { ReplicaSyncOptions } from '@lobechat/replica/zustand';
+
+import type { ReplicaSyncResult } from '@/libs/replica';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { initialProjectFileState, type ProjectFileState } from './initialState';
+import { ProjectFilePrivateAction } from './privateAction';
+import {
+ type FilesLocation,
+ type FilesLocationParams,
+ type GitWorkingTreeFilesParams,
+ type ProjectIndexParams,
+} from './projection';
+import { useProjectFileStore } from './store';
+
+const n = setNamespace('projectFile');
+
+type Setter = StoreSetter<ProjectFileState>;
+
+/** SWR schedule fields the replica driver forwards as is. */
+type SyncOptions<TFetched, TData> = ReplicaSyncOptions<TFetched, TData> & {
+ shouldRetryOnError?: boolean;
+};
+
+export class ProjectFileActionImpl {
+ readonly #private: ProjectFilePrivateAction;
+ readonly #set: Setter;
+
+ constructor(set: Setter, _get: () => ProjectFileState, privateAction: ProjectFilePrivateAction) {
+ void _get;
+ this.#set = set;
+ this.#private = privateAction;
+ }
+
+ /** Remember where a conversation's Files tab settled, for the next cold start. */
+ rememberFilesLocation = (contextKey: string, location: FilesLocation): void => {
+ this.#private.filesLocation.update(contextKey, () => location);
+ };
+
+ reset = (): void => {
+ this.#set(initialProjectFileState, false, n('reset'));
+ };
+
+ /** Reads the remembered location; there is nothing to fetch. */
+ useFetchFilesLocation = (params: FilesLocationParams | null): ReplicaSyncResult =>
+ this.#private.filesLocation.useSync(params);
+
+ useFetchGitWorkingTreeFiles = (
+ params: GitWorkingTreeFilesParams | null,
+ options?: SyncOptions<GitWorkingTreeFiles | null | undefined, GitWorkingTreeFiles>,
+ ): ReplicaSyncResult => this.#private.gitWorkingTreeFiles.useSync(params, options);
+
+ useFetchProjectIndex = (
+ params: ProjectIndexParams | null,
+ options?: SyncOptions<ProjectFileIndexResult | null | undefined, ProjectFileIndexResult>,
+ ): ReplicaSyncResult => this.#private.projectIndex.useSync(params, options);
+}
+
+const { getState, setState } = useProjectFileStore;
+
+export const projectFileActions = new ProjectFileActionImpl(
+ setState,
+ getState,
+ new ProjectFilePrivateAction(setState, getState),
+);
diff --git a/src/store/projectFile/codec.test.ts b/src/store/projectFile/codec.test.ts
new file mode 100644
index 00000000000..17f5f046013
--- /dev/null
+++ b/src/store/projectFile/codec.test.ts
@@ -0,0 +1,218 @@
+import type { ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
+import { describe, expect, it } from 'vitest';
+
+import { REPLICA_INDEX_KEY, type ReplicaRow, type ReplicaStorage } from '@/libs/replica';
+
+import {
+ decodeProjectIndex,
+ encodeProjectIndex,
+ GIT_WORKING_TREE_PERSIST_MAX_PATHS,
+ gitWorkingTreeFilesCodec,
+ isPersistedPartialIndex,
+ projectIndexCodec,
+ withPersistCodec,
+} from './codec';
+
+const index: ProjectFileIndexResult = {
+ entries: [
+ { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
+ {
+ isDirectory: false,
+ name: 'index.ts',
+ path: '/repo/src/index.ts',
+ relativePath: 'src/index.ts',
+ },
+ {
+ collapsed: true,
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'node_modules',
+ path: '/repo/node_modules',
+ relativePath: 'node_modules/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.env',
+ path: '/repo/.env',
+ relativePath: '.env',
+ },
+ ],
+ indexedAt: '2026-10-12T00:00:00.000Z',
+ root: '/repo',
+ source: 'git',
+};
+
+describe('project index codec', () => {
+ it('round-trips an index losslessly while dropping derivable fields', () => {
+ const encoded = encodeProjectIndex(index);
+
+ expect(encoded.entries).toEqual([
+ ['src/', 1],
+ ['src/index.ts', 0],
+ ['node_modules/', 7],
+ ['.env', 2],
+ ]);
+ expect(decodeProjectIndex(encoded)).toEqual(index);
+ });
+
+ it('keeps paths and names a host did not derive from the root', () => {
+ const windows: ProjectFileIndexResult = {
+ entries: [
+ { isDirectory: true, name: 'src', path: 'C:\\repo\\src', relativePath: 'src/' },
+ { isDirectory: false, name: 'a.ts', path: 'C:\\repo\\src\\a.ts', relativePath: 'src/a.ts' },
+ ],
+ indexedAt: 'now',
+ root: 'C:\\repo',
+ source: 'glob',
+ };
+ const sandbox: ProjectFileIndexResult = {
+ entries: [
+ {
+ isDirectory: false,
+ name: 'Report',
+ path: '/workspace/out/report.md',
+ relativePath: 'report.md',
+ },
+ ],
+ indexedAt: 'now',
+ root: '',
+ source: 'sandbox',
+ truncated: true,
+ };
+
+ expect(encodeProjectIndex(windows).entries).toEqual([
+ ['src/', 1],
+ ['src/a.ts', 0],
+ ]);
+ expect(decodeProjectIndex(encodeProjectIndex(windows))).toEqual(windows);
+ expect(decodeProjectIndex(encodeProjectIndex(sandbox))).toEqual(sandbox);
+ });
+
+ it('keeps the shallowest entries, in order, when the tree is past the cap', () => {
+ const decoded = decodeProjectIndex(encodeProjectIndex(index, 3));
+
+ expect(decoded.entries.map((entry) => entry.relativePath)).toEqual([
+ 'src/',
+ 'node_modules/',
+ '.env',
+ ]);
+ });
+
+ it('caps a large index in source order without reordering the tree', () => {
+ const entries = Array.from({ length: 25_050 }, (_, index) => {
+ const relativePath = `${'deep/'.repeat(index % 5)}f${index}`;
+
+ return {
+ isDirectory: false,
+ name: `f${index}`,
+ path: `/repo/${relativePath}`,
+ relativePath,
+ };
+ });
+
+ const encoded = encodeProjectIndex({ ...index, entries }, 20_000);
+ const keptPaths = encoded.entries.map(([relativePath]) => relativePath as string);
+
+ expect(keptPaths).toHaveLength(20_000);
+ // Every root-level entry survives, and the retained entries keep the
+ // source order the tree renders in.
+ const rootPaths = entries.filter((entry) => !entry.relativePath.includes('/'));
+ for (const entry of rootPaths) expect(keptPaths).toContain(entry.relativePath);
+ const sourceIndex = new Map(entries.map((entry, i) => [entry.relativePath, i]));
+ const keptIndexes = keptPaths.map((path) => sourceIndex.get(path)!);
+ expect(keptIndexes).toEqual([...keptIndexes].sort((a, b) => a - b));
+ });
+
+ it('marks a capped tree as partial, and keeps it partial when written back', () => {
+ expect(isPersistedPartialIndex(decodeProjectIndex(encodeProjectIndex(index)))).toBe(false);
+
+ const restored = decodeProjectIndex(encodeProjectIndex(index, 3));
+ expect(isPersistedPartialIndex(restored)).toBe(true);
+ // Under the cap now, but it is still the cut-down copy, not the full tree.
+ expect(isPersistedPartialIndex(decodeProjectIndex(encodeProjectIndex(restored)))).toBe(true);
+ });
+
+ it('decodes only rows it encoded', () => {
+ expect(projectIndexCodec.decode(projectIndexCodec.encode(index))).toEqual(index);
+ // A raw (unencoded) value is an older shape: a miss, not a broken tree.
+ expect(projectIndexCodec.decode(index)).toBeUndefined();
+ });
+});
+
+describe('git working tree codec', () => {
+ it('stores the dirty-file lists and skips oversized overlays', () => {
+ const files = { added: ['a.ts'], deleted: [], modified: ['b.ts'] };
+ expect(gitWorkingTreeFilesCodec.decode(gitWorkingTreeFilesCodec.encode(files))).toEqual(files);
+
+ const huge = {
+ added: Array.from({ length: GIT_WORKING_TREE_PERSIST_MAX_PATHS + 1 }, (_, i) => `f${i}`),
+ deleted: [],
+ modified: [],
+ };
+ expect(gitWorkingTreeFilesCodec.encode(huge)).toBeUndefined();
+ });
+});
+
+const memoryStorage = () => {
+ const rows = new Map<string, ReplicaRow<unknown>>();
+ const id = ({ queryKey, scope }: { queryKey: string; scope: string }) => `${scope}|${queryKey}`;
+ const storage: ReplicaStorage<unknown> = {
+ get: async (key) => rows.get(id(key)),
+ getStrict: async (key) => rows.get(id(key)),
+ remove: async (key) => {
+ rows.delete(id(key));
+ },
+ set: async (key, row) => {
+ rows.set(id(key), row);
+ },
+ };
+ return { rows, storage };
+};
+
+describe('withPersistCodec', () => {
+ const key = { queryKey: '["local","/repo"]', scope: 'u1:personal' };
+
+ it('stores the encoded row and reads the decoded value back', async () => {
+ const { rows, storage } = memoryStorage();
+ const codecStorage = withPersistCodec(storage, projectIndexCodec);
+
+ await codecStorage.set(key, { data: index, updatedAt: 1 });
+
+ expect((rows.get(`u1:personal|${key.queryKey}`)?.data as any).entries).toEqual([
+ ['src/', 1],
+ ['src/index.ts', 0],
+ ['node_modules/', 7],
+ ['.env', 2],
+ ]);
+ expect(await codecStorage.get(key)).toEqual({ data: index, updatedAt: 1 });
+ expect(await codecStorage.getStrict!(key)).toEqual({ data: index, updatedAt: 1 });
+ });
+
+ it('passes the replica index row through untouched', async () => {
+ const { storage } = memoryStorage();
+ const codecStorage = withPersistCodec(storage, projectIndexCodec);
+ const indexKey = { queryKey: REPLICA_INDEX_KEY, scope: 'u1:personal' };
+
+ await codecStorage.set(indexKey, { data: ['a', 'b'] as any, updatedAt: 1 });
+
+ expect(await codecStorage.get(indexKey)).toEqual({ data: ['a', 'b'], updatedAt: 1 });
+ });
+
+ it('drops the old row when a value is too large to keep', async () => {
+ const { rows, storage } = memoryStorage();
+ const codecStorage = withPersistCodec(storage, gitWorkingTreeFilesCodec);
+ const small = { added: ['a.ts'], deleted: [], modified: [] };
+ await codecStorage.set(key, { data: small, updatedAt: 1 });
+
+ const huge = {
+ added: Array.from({ length: GIT_WORKING_TREE_PERSIST_MAX_PATHS + 1 }, (_, i) => `f${i}`),
+ deleted: [],
+ modified: [],
+ };
+ await codecStorage.set(key, { data: huge, updatedAt: 2 });
+
+ expect(rows.size).toBe(0);
+ expect(await codecStorage.get(key)).toBeUndefined();
+ });
+});
diff --git a/src/store/projectFile/codec.ts b/src/store/projectFile/codec.ts
new file mode 100644
index 00000000000..3806c926d70
--- /dev/null
+++ b/src/store/projectFile/codec.ts
@@ -0,0 +1,260 @@
+/**
+ * Persisted shapes of the Files tab replicas (project tree / git overlay).
+ *
+ * A project index is a flat list of every file in a repo, and each entry
+ * repeats what the root and its own relative path already say (`path`,
+ * `name`). Stored verbatim a large monorepo is megabytes per directory, so
+ * these codecs store the entries as compact tuples, keep only what the first
+ * paint can show when a tree is past the cap, and refuse to persist anything
+ * that would still be too large โ€” the network refresh that follows hydration
+ * is what makes the tree whole again.
+ */
+import type {
+ GitWorkingTreeFiles,
+ ProjectFileIndexEntry,
+ ProjectFileIndexResult,
+} from '@lobechat/electron-client-ipc';
+
+import {
+ REPLICA_INDEX_KEY,
+ type ReplicaRow,
+ type ReplicaRowKey,
+ type ReplicaStorage,
+} from '@/libs/replica';
+
+/**
+ * Entries beyond this many are not persisted. The default first paint expands
+ * the project root only, so the shallowest entries are the ones worth keeping.
+ */
+export const PROJECT_INDEX_PERSIST_MAX_ENTRIES = 20_000;
+
+/** A dirty-file overlay this large is not worth a stale first paint. */
+export const GIT_WORKING_TREE_PERSIST_MAX_PATHS = 5000;
+
+/**
+ * Directories whose tree / overlay stay persisted (`persist.maxEntries`); the
+ * least recently used are evicted, so storage holds the recent projects a user
+ * is likely to reopen, not every directory they ever looked at.
+ */
+export const PROJECT_INDEX_PERSIST_MAX_ROWS = 10;
+export const GIT_WORKING_TREE_PERSIST_MAX_ROWS = 20;
+
+const ENCODED_PROJECT_INDEX = 'projectIndex@1';
+
+const FLAG_DIRECTORY = 1;
+const FLAG_GIT_IGNORED = 2;
+const FLAG_COLLAPSED = 4;
+
+/**
+ * `[relativePath, flags, path?, name?]` โ€” `path` and `name` are only present
+ * when they differ from what the root and relative path derive.
+ */
+type EncodedEntry = [string, number] | [string, number, string | null, string?];
+
+interface EncodedProjectIndex {
+ __codec: typeof ENCODED_PROJECT_INDEX;
+ /** Entries past the persist cap were dropped from this row. */
+ capped?: boolean;
+ entries: EncodedEntry[];
+ indexedAt: string;
+ root: string;
+ source: ProjectFileIndexResult['source'];
+ truncated?: boolean;
+}
+
+const trimTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
+
+const deriveName = (relativePath: string) => {
+ const cleaned = trimTrailingSlash(relativePath);
+ return cleaned.slice(cleaned.lastIndexOf('/') + 1);
+};
+
+/** The absolute path a host would produce for `relativePath` under `root`. */
+const derivePath = (root: string, relativePath: string) => {
+ const separator = root.includes('\\') && !root.includes('/') ? '\\' : '/';
+ const relative = trimTrailingSlash(relativePath).split('/').join(separator);
+ if (!root) return relative;
+ return root.endsWith(separator) ? `${root}${relative}` : `${root}${separator}${relative}`;
+};
+
+const depthOf = (relativePath: string) => trimTrailingSlash(relativePath).split('/').length;
+
+const encodeEntry = (root: string, entry: ProjectFileIndexEntry): EncodedEntry => {
+ const flags =
+ (entry.isDirectory ? FLAG_DIRECTORY : 0) |
+ (entry.gitIgnored ? FLAG_GIT_IGNORED : 0) |
+ (entry.collapsed ? FLAG_COLLAPSED : 0);
+ const path = entry.path === derivePath(root, entry.relativePath) ? null : entry.path;
+ const name = entry.name === deriveName(entry.relativePath) ? undefined : entry.name;
+
+ if (name !== undefined) return [entry.relativePath, flags, path, name];
+ if (path !== null) return [entry.relativePath, flags, path];
+ return [entry.relativePath, flags];
+};
+
+const decodeEntry = (root: string, encoded: EncodedEntry): ProjectFileIndexEntry => {
+ const [relativePath, flags, path, name] = encoded;
+ return {
+ ...(flags & FLAG_COLLAPSED ? { collapsed: true } : {}),
+ ...(flags & FLAG_GIT_IGNORED ? { gitIgnored: true } : {}),
+ isDirectory: Boolean(flags & FLAG_DIRECTORY),
+ name: name ?? deriveName(relativePath),
+ path: path ?? derivePath(root, relativePath),
+ relativePath,
+ };
+};
+
+/**
+ * Keep the shallowest `max` entries, in their original order. A tree cut by
+ * depth still renders every visible top-level row correctly; one cut by list
+ * position would drop whole sibling folders from the root.
+ *
+ * Linear in the entry count: a repository can hold hundreds of thousands of
+ * paths, and sorting the whole index on the renderer after every revalidation
+ * would cost more than the read it is trying to make cheap. Count by depth,
+ * find the depth that fills the cap, then take the entries in source order.
+ */
+const keepShallowest = (entries: ProjectFileIndexEntry[], max: number) => {
+ if (entries.length <= max) return entries;
+
+ const depths = new Uint32Array(entries.length);
+ let maxDepth = 0;
+ for (let i = 0; i < entries.length; i++) {
+ const depth = depthOf(entries[i].relativePath);
+ depths[i] = depth;
+ if (depth > maxDepth) maxDepth = depth;
+ }
+
+ const counts = new Uint32Array(maxDepth + 1);
+ for (let i = 0; i < depths.length; i++) counts[depths[i]] += 1;
+
+ let remaining = max;
+ let cutoff = 0;
+ while (cutoff <= maxDepth && counts[cutoff] < remaining) {
+ remaining -= counts[cutoff];
+ cutoff += 1;
+ }
+
+ const kept: ProjectFileIndexEntry[] = [];
+ for (let i = 0; i < entries.length && kept.length < max; i++) {
+ const depth = depths[i];
+ if (depth < cutoff) kept.push(entries[i]);
+ else if (depth === cutoff && remaining > 0) {
+ kept.push(entries[i]);
+ remaining -= 1;
+ }
+ }
+ return kept;
+};
+
+/**
+ * A tree restored from a capped row: its deepest entries were not persisted.
+ * It paints the first screen correctly, but it is not the whole project until
+ * the network read replaces it โ€” which is what the Files tab has to say when
+ * that read does not come.
+ */
+export type PersistedProjectIndex = ProjectFileIndexResult & { persistedPartial?: true };
+
+export const isPersistedPartialIndex = (data: ProjectFileIndexResult | undefined): boolean =>
+ !!(data as PersistedProjectIndex | undefined)?.persistedPartial;
+
+export const encodeProjectIndex = (
+ data: PersistedProjectIndex,
+ maxEntries = PROJECT_INDEX_PERSIST_MAX_ENTRIES,
+): EncodedProjectIndex => {
+ const kept = keepShallowest(data.entries, maxEntries);
+ return {
+ __codec: ENCODED_PROJECT_INDEX,
+ // A restored partial tree written back before its refresh lands is still partial.
+ ...(kept.length < data.entries.length || data.persistedPartial ? { capped: true } : {}),
+ entries: kept.map((entry) => encodeEntry(data.root, entry)),
+ indexedAt: data.indexedAt,
+ root: data.root,
+ source: data.source,
+ ...(data.truncated ? { truncated: true } : {}),
+ };
+};
+
+export const decodeProjectIndex = (encoded: EncodedProjectIndex): PersistedProjectIndex => ({
+ entries: encoded.entries.map((entry) => decodeEntry(encoded.root, entry)),
+ indexedAt: encoded.indexedAt,
+ ...(encoded.capped ? { persistedPartial: true as const } : {}),
+ root: encoded.root,
+ source: encoded.source,
+ ...(encoded.truncated ? { truncated: true } : {}),
+});
+
+const isEncodedProjectIndex = (value: unknown): value is EncodedProjectIndex =>
+ !!value &&
+ typeof value === 'object' &&
+ (value as EncodedProjectIndex).__codec === ENCODED_PROJECT_INDEX &&
+ Array.isArray((value as EncodedProjectIndex).entries);
+
+const isGitWorkingTreeFiles = (value: unknown): value is GitWorkingTreeFiles =>
+ !!value &&
+ typeof value === 'object' &&
+ Array.isArray((value as GitWorkingTreeFiles).added) &&
+ Array.isArray((value as GitWorkingTreeFiles).modified) &&
+ Array.isArray((value as GitWorkingTreeFiles).deleted);
+
+export const isGitWorkingTreeFilesPersistable = (data: GitWorkingTreeFiles): boolean =>
+ data.added.length + data.deleted.length + data.modified.length <=
+ GIT_WORKING_TREE_PERSIST_MAX_PATHS;
+
+/**
+ * The overlay as stored: only the three buckets, and nothing at all past the
+ * cap โ€” a huge dirty set is not worth a stale first paint.
+ */
+export const encodeGitWorkingTreeFiles = (
+ data: GitWorkingTreeFiles,
+): GitWorkingTreeFiles | undefined => {
+ if (!isGitWorkingTreeFilesPersistable(data)) return undefined;
+ const { added, deleted, modified } = data;
+ return { added, deleted, modified };
+};
+
+interface PersistCodec<TData, TStored> {
+ decode: (stored: unknown) => TData | undefined;
+ /** `undefined`: the value is not worth a row; the key's old row is dropped. */
+ encode: (data: TData) => TStored | undefined;
+}
+
+/**
+ * A replica storage that reshapes entry rows on the way in and out. The
+ * engine's per-scope index row passes through untouched; a row that no longer
+ * decodes (an older shape) reads as a miss.
+ */
+export const withPersistCodec = <TData, TStored>(
+ inner: ReplicaStorage<any>,
+ { decode, encode }: PersistCodec<TData, TStored>,
+): ReplicaStorage<TData> => {
+ const read = (row: ReplicaRow<unknown> | undefined, key: ReplicaRowKey) => {
+ if (!row || key.queryKey === REPLICA_INDEX_KEY) return row as ReplicaRow<TData> | undefined;
+ const data = decode(row.data);
+ return data === undefined ? undefined : { data, updatedAt: row.updatedAt };
+ };
+
+ return {
+ get: async (key) => read(await inner.get(key), key),
+ getStrict: inner.getStrict && (async (key) => read(await inner.getStrict!(key), key)),
+ remove: (key) => inner.remove(key),
+ set: (key, row) => {
+ if (key.queryKey === REPLICA_INDEX_KEY) return inner.set(key, row);
+ const data = encode(row.data);
+ // Too large to keep: drop what an earlier, smaller value left behind so
+ // a reload never paints it.
+ if (data === undefined) return inner.remove(key);
+ return inner.set(key, { data, updatedAt: row.updatedAt });
+ },
+ };
+};
+
+export const projectIndexCodec: PersistCodec<PersistedProjectIndex, EncodedProjectIndex> = {
+ decode: (stored) => (isEncodedProjectIndex(stored) ? decodeProjectIndex(stored) : undefined),
+ encode: (data) => encodeProjectIndex(data),
+};
+
+export const gitWorkingTreeFilesCodec: PersistCodec<GitWorkingTreeFiles, GitWorkingTreeFiles> = {
+ decode: (stored) => (isGitWorkingTreeFiles(stored) ? stored : undefined),
+ encode: encodeGitWorkingTreeFiles,
+};
diff --git a/src/store/projectFile/index.ts b/src/store/projectFile/index.ts
new file mode 100644
index 00000000000..5f4131b678d
--- /dev/null
+++ b/src/store/projectFile/index.ts
@@ -0,0 +1,12 @@
+export { projectFileActions } from './action';
+export { isPersistedPartialIndex } from './codec';
+export { type ProjectFileState } from './initialState';
+export {
+ type FilesLocation,
+ filesLocationResource,
+ gitWorkingTreeFilesResource,
+ peekFilesLocation,
+ projectIndexHost,
+ projectIndexResource,
+} from './projection';
+export { useProjectFileStore } from './store';
diff --git a/src/store/projectFile/initialState.ts b/src/store/projectFile/initialState.ts
new file mode 100644
index 00000000000..366f47360b2
--- /dev/null
+++ b/src/store/projectFile/initialState.ts
@@ -0,0 +1,26 @@
+import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { FilesLocation } from './projection';
+
+export interface ProjectFileState {
+ /** Last Files tab location, by conversation (`filesLocationResource` key). */
+ filesLocation: Record<string, FilesLocation>;
+ filesLocationReplica: ReplicaState<FilesLocation>;
+ /** Git dirty-file overlays, by `gitWorkingTreeFilesResource` key. */
+ gitWorkingTreeFiles: Record<string, GitWorkingTreeFiles>;
+ gitWorkingTreeFilesReplica: ReplicaState<GitWorkingTreeFiles>;
+ /** Project trees, by `projectIndexResource` key. */
+ projectIndex: Record<string, ProjectFileIndexResult>;
+ projectIndexReplica: ReplicaState<ProjectFileIndexResult>;
+}
+
+export const initialProjectFileState: ProjectFileState = {
+ filesLocation: {},
+ filesLocationReplica: createReplicaState(),
+ gitWorkingTreeFiles: {},
+ gitWorkingTreeFilesReplica: createReplicaState(),
+ projectIndex: {},
+ projectIndexReplica: createReplicaState(),
+};
diff --git a/src/store/projectFile/privateAction.ts b/src/store/projectFile/privateAction.ts
new file mode 100644
index 00000000000..2efa3521353
--- /dev/null
+++ b/src/store/projectFile/privateAction.ts
@@ -0,0 +1,81 @@
+import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
+
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { gitService } from '@/services/git';
+import { projectFileService } from '@/services/projectFile';
+import type { StoreSetter } from '@/store/types';
+
+import { isGitWorkingTreeFilesPersistable } from './codec';
+import { type ProjectFileState } from './initialState';
+import {
+ type FilesLocation,
+ filesLocationResource,
+ gitWorkingTreeFilesResource,
+ projectIndexResource,
+} from './projection';
+
+type Setter = StoreSetter<ProjectFileState>;
+
+export class ProjectFilePrivateAction {
+ readonly filesLocation;
+ readonly gitWorkingTreeFiles;
+ readonly projectIndex;
+
+ constructor(set: Setter, get: () => ProjectFileState) {
+ this.projectIndex = createReplicaSlice(projectIndexResource, {
+ actionPrefix: 'projectFile/projectIndex',
+ // An absent result is a terminal "nothing to read there", not a dropped
+ // response: the engine skips `isMissing` for `undefined` heads.
+ fetcher: async ({ deviceId, dirPath, sandboxInstanceId, sandboxTopicId }) => {
+ const result = await projectFileService.getProjectFileIndex({
+ deviceId,
+ sandboxInstanceId,
+ sandboxTopicId,
+ scope: dirPath,
+ });
+ // A remote read that yields nothing is a transport failure, not a
+ // confirmed empty directory: the device router collapses offline /
+ // timeout to `null`. Throw so the replica keeps its cached tree and
+ // exposes the refresh error instead of deleting the saved row.
+ if (deviceId && !sandboxInstanceId && !sandboxTopicId && !result) {
+ throw new Error('The device did not return a project index');
+ }
+ return result ?? null;
+ },
+ get,
+ // No tree from the host (nothing to read there) clears the saved one.
+ isMissing: (incoming) => incoming === null,
+ set,
+ stateKey: 'projectIndexReplica',
+ view: recordLens<ProjectFileState, ProjectFileIndexResult>('projectIndex'),
+ });
+ this.gitWorkingTreeFiles = createReplicaSlice(gitWorkingTreeFilesResource, {
+ actionPrefix: 'projectFile/gitWorkingTreeFiles',
+ fetcher: async ({ deviceId, dirPath }) => {
+ const result = await gitService.getGitWorkingTreeFiles({ deviceId, path: dirPath });
+ // Same remote contract as the tree: an absent overlay from a device is
+ // a transport failure, not a confirmed clean working tree. Throw so a
+ // hydrated overlay survives and `gitError` is exposed.
+ if (deviceId && !result) {
+ throw new Error('The device did not return a git overlay');
+ }
+ return result ?? null;
+ },
+ get,
+ isMissing: (incoming) => incoming === null,
+ set,
+ stateKey: 'gitWorkingTreeFilesReplica',
+ // An overlay past the cap is not persisted at all โ€” `null` also drops a
+ // row (and its bounded-index key) left by an earlier, smaller overlay.
+ toPersisted: (data) => (isGitWorkingTreeFilesPersistable(data) ? data : null),
+ view: recordLens<ProjectFileState, GitWorkingTreeFiles>('gitWorkingTreeFiles'),
+ });
+ this.filesLocation = createReplicaSlice(filesLocationResource, {
+ actionPrefix: 'projectFile/filesLocation',
+ get,
+ set,
+ stateKey: 'filesLocationReplica',
+ view: recordLens<ProjectFileState, FilesLocation>('filesLocation'),
+ });
+ }
+}
diff --git a/src/store/projectFile/projection.ts b/src/store/projectFile/projection.ts
new file mode 100644
index 00000000000..692ff90d664
--- /dev/null
+++ b/src/store/projectFile/projection.ts
@@ -0,0 +1,125 @@
+import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
+
+import {
+ IndexedDBQueryProjectionStorage,
+ LocalStorageQueryProjectionStorage,
+} from '@/libs/queryProjectionStorage';
+import { cacheScope, defineReplica } from '@/libs/replica';
+import { localFileKeys } from '@/libs/swr/keys';
+
+import {
+ GIT_WORKING_TREE_PERSIST_MAX_ROWS,
+ gitWorkingTreeFilesCodec,
+ PROJECT_INDEX_PERSIST_MAX_ROWS,
+ projectIndexCodec,
+ withPersistCodec,
+} from './codec';
+
+export interface ProjectIndexParams {
+ deviceId?: string;
+ dirPath: string;
+ sandboxInstanceId?: string;
+ sandboxTopicId?: string;
+}
+
+export interface GitWorkingTreeFilesParams {
+ deviceId?: string;
+ dirPath: string;
+}
+
+/**
+ * The host is part of the identity: the same path on a device and in the
+ * sandbox are different trees, and `undefined` already means "this machine".
+ * Keyed by the INSTANCE where there is one โ€” two conversations running the
+ * same instance are looking at one tree, and keying by topic would fetch it
+ * twice and let one go stale while the other refreshed.
+ */
+export const projectIndexHost = ({
+ deviceId,
+ sandboxInstanceId,
+ sandboxTopicId,
+}: Omit<ProjectIndexParams, 'dirPath'>): string | undefined =>
+ sandboxInstanceId || sandboxTopicId ? `sandbox:${sandboxInstanceId ?? sandboxTopicId}` : deviceId;
+
+const entryKey = (host: string | undefined, dirPath: string) =>
+ JSON.stringify([host ?? 'local', dirPath]);
+
+/**
+ * The Files tab project tree of one directory on one host (device / sandbox
+ * instance / this machine), partitioned by identity scope. Persisted slim
+ * (`projectIndexCodec`) and for the most recent directories only, so a reload
+ * paints the last tree while the host is asked again.
+ *
+ * The sync adopts the `localFile:projectIndex` key: file operations revalidate
+ * the tree through it (`refreshProjectFiles`).
+ */
+export const projectIndexResource = defineReplica<
+ ProjectIndexParams,
+ ProjectFileIndexResult,
+ ProjectFileIndexResult | undefined
+>({
+ key: (params) => entryKey(projectIndexHost(params), params.dirPath),
+ name: 'projectFileIndex',
+ persist: { maxEntries: PROJECT_INDEX_PERSIST_MAX_ROWS },
+ storage: (namespace) =>
+ withPersistCodec(new IndexedDBQueryProjectionStorage({ namespace }), projectIndexCodec),
+ syncKey: (params) => localFileKeys.projectIndex(projectIndexHost(params), params.dirPath),
+ version: 1,
+});
+
+/**
+ * The git dirty-file overlay of the Files tree for one directory on one host.
+ * The sync adopts `localFile:gitWorkingTreeFiles`, which file operations and
+ * the Review tab revalidate.
+ */
+export const gitWorkingTreeFilesResource = defineReplica<
+ GitWorkingTreeFilesParams,
+ GitWorkingTreeFiles,
+ GitWorkingTreeFiles | undefined
+>({
+ key: ({ deviceId, dirPath }) => entryKey(deviceId, dirPath),
+ name: 'gitWorkingTreeFiles',
+ persist: { maxEntries: GIT_WORKING_TREE_PERSIST_MAX_ROWS },
+ storage: (namespace) =>
+ withPersistCodec(new IndexedDBQueryProjectionStorage({ namespace }), gitWorkingTreeFilesCodec),
+ syncKey: ({ deviceId, dirPath }) => localFileKeys.gitWorkingTreeFiles(deviceId, dirPath),
+ version: 1,
+});
+
+export interface FilesLocation {
+ /** Remote device the tree is read from; undefined is this machine. */
+ deviceId?: string;
+ directory: string;
+}
+
+export interface FilesLocationParams {
+ /** `topic:<id>` / `agent:<id>`: the conversation the Files tab belongs to. */
+ contextKey: string;
+}
+
+/**
+ * Where the Files tab of a conversation last read its tree (host + directory),
+ * so a cold start opens that tree before the device list can resolve it. Local
+ * only (no fetcher): written once the live resolution settles. Kept in
+ * localStorage for the most recent conversations, per identity scope.
+ */
+export const filesLocationResource = defineReplica<FilesLocationParams, FilesLocation>({
+ key: ({ contextKey }) => contextKey,
+ name: 'filesLocation',
+ persist: { maxEntries: 100 },
+ storage: (namespace) => new LocalStorageQueryProjectionStorage<FilesLocation>({ namespace }),
+ version: 1,
+});
+
+/**
+ * The saved location of a conversation, read synchronously from the replica's
+ * own row. The replica hydrates asynchronously, and the frames in between
+ * would otherwise resolve the tree to the unsettled fallback directory.
+ */
+export const peekFilesLocation = (contextKey: string, scope: string): FilesLocation | undefined => {
+ if (!cacheScope.canHydrate?.()) return undefined;
+ const storage = filesLocationResource.storage as
+ LocalStorageQueryProjectionStorage<FilesLocation> | undefined;
+ return storage?.getSync({ queryKey: filesLocationResource.storageKey({ contextKey }), scope })
+ ?.data;
+};
diff --git a/src/store/projectFile/replica.test.ts b/src/store/projectFile/replica.test.ts
new file mode 100644
index 00000000000..516a672d13f
--- /dev/null
+++ b/src/store/projectFile/replica.test.ts
@@ -0,0 +1,300 @@
+/**
+ * The Files tab tree and its git overlay are replicas: a reload paints the
+ * last tree of a host + directory from storage, then the host is asked again.
+ * Each test "reloads" by re-importing every module (a fresh store, engine and
+ * SWR cache) over the same IndexedDB.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const services = vi.hoisted(() => ({
+ getGitWorkingTreeFiles: vi.fn(),
+ getProjectFileIndex: vi.fn(),
+}));
+const scope = vi.hoisted(() => ({ current: 'u1:personal' }));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { getProjectFileIndex: services.getProjectFileIndex },
+}));
+vi.mock('@/services/git', () => ({
+ gitService: { getGitWorkingTreeFiles: services.getGitWorkingTreeFiles },
+}));
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ isDesktop: true,
+}));
+vi.mock('@/store/chat', () => ({ useChatStore: () => false }));
+vi.mock('@/store/chat/selectors', () => ({ operationSelectors: {} }));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+
+const tree = (names: string[]) => ({
+ entries: names.map((name) => ({
+ isDirectory: false,
+ name,
+ path: `/repo/${name}`,
+ relativePath: name,
+ })),
+ indexedAt: 'now',
+ root: '/repo',
+ source: 'git' as const,
+});
+
+const never = () => new Promise<never>(() => {});
+
+/** A fresh page: new store, replica engine and (empty) SWR cache. */
+const boot = async (
+ initialProps: { deviceId?: string; dir: string } = { deviceId: 'device-1', dir: '/repo' },
+) => {
+ vi.resetModules();
+ const { useFilesTreeSources } =
+ await import('@/features/Conversation/WorkingSidebar/Files/useFilesTreeSources');
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ children,
+ );
+ return renderHook(
+ ({ deviceId, dir }: { deviceId?: string; dir: string }) => useFilesTreeSources(deviceId, dir),
+ { initialProps, wrapper },
+ );
+};
+
+const readRows = async () => {
+ const { localDatabase } = await import('@/libs/localDatabase');
+ await localDatabase.initialize();
+ return localDatabase;
+};
+
+beforeEach(() => {
+ scope.current = 'u1:personal';
+ services.getGitWorkingTreeFiles.mockReset();
+ services.getProjectFileIndex.mockReset();
+});
+
+afterEach(async () => {
+ const { localDatabase } = await import('@/libs/localDatabase');
+ await localDatabase.initialize();
+ await localDatabase.deleteByPrefix('query-projections', 'replica:');
+});
+
+describe('Files tab replicas', () => {
+ it('paints the last tree and overlay after a reload, then refreshes them', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts', 'b.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({
+ added: [],
+ deleted: [],
+ modified: ['a.ts'],
+ });
+
+ const first = await boot();
+ await waitFor(() => expect(first.result.current.project.data?.entries).toHaveLength(2));
+ await waitFor(() => expect(first.result.current.git.data?.modified).toEqual(['a.ts']));
+ first.unmount();
+
+ // Reload with a host that has not answered yet.
+ let resolveIndex!: (value: unknown) => void;
+ services.getProjectFileIndex.mockReturnValue(
+ new Promise((resolve) => {
+ resolveIndex = resolve;
+ }),
+ );
+ services.getGitWorkingTreeFiles.mockReturnValue(never());
+
+ const second = await boot();
+ await waitFor(() =>
+ expect(second.result.current.project.data?.entries.map((e) => e.name)).toEqual([
+ 'a.ts',
+ 'b.ts',
+ ]),
+ );
+ expect(second.result.current.project.isLoading).toBe(false);
+ expect(second.result.current.project.isValidating).toBe(true);
+ expect(second.result.current.git.data?.modified).toEqual(['a.ts']);
+
+ // The host answers: the saved tree is replaced in place.
+ await act(async () => {
+ resolveIndex(tree(['a.ts', 'b.ts', 'new-folder']));
+ });
+ await waitFor(() => expect(second.result.current.project.data?.entries).toHaveLength(3));
+ second.unmount();
+ });
+
+ it('clears the saved tree and overlay when the host reports nothing', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({
+ added: [],
+ deleted: [],
+ modified: ['a.ts'],
+ });
+
+ // This machine: an absent index is a confirmed "nothing to read there".
+ const view = await boot({ deviceId: undefined, dir: '/repo' });
+ await waitFor(() => expect(view.result.current.project.data?.entries).toHaveLength(1));
+ await waitFor(() => expect(view.result.current.git.data?.modified).toEqual(['a.ts']));
+
+ // The host has nothing to read there any more: both reads now resolve
+ // without a result, which must clear the visible tree and its saved row.
+ services.getProjectFileIndex.mockResolvedValue(undefined);
+ services.getGitWorkingTreeFiles.mockResolvedValue(undefined);
+ await act(async () => {
+ await view.result.current.project.mutate();
+ await view.result.current.git.mutate();
+ });
+
+ await waitFor(() => expect(view.result.current.project.data).toBeUndefined());
+ await waitFor(() => expect(view.result.current.git.data).toBeUndefined());
+
+ const db = await readRows();
+ const rows = await db.entriesByPrefix<{ data: unknown }>(
+ 'query-projections',
+ 'replica:projectFileIndex:v1:',
+ );
+ expect(rows.filter(({ key }) => !key.includes('__replica'))).toHaveLength(0);
+ view.unmount();
+ });
+
+ it('keeps a remote tree when the device read fails', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({ added: [], deleted: [], modified: [] });
+
+ const view = await boot();
+ await waitFor(() => expect(view.result.current.project.data?.entries).toHaveLength(1));
+
+ // Offline / RPC timeout: the device router normalizes the missing result to
+ // null. That is not a confirmed empty directory, so the cached tree and
+ // its saved row must stay, with the refresh error exposed.
+ services.getProjectFileIndex.mockResolvedValue(undefined);
+ await act(async () => {
+ await view.result.current.project.mutate().catch(() => {});
+ });
+
+ await waitFor(() => expect(view.result.current.project.error).toBeTruthy());
+ expect(view.result.current.project.data?.entries).toHaveLength(1);
+
+ const db = await readRows();
+ const rows = await db.entriesByPrefix<{ data: unknown }>(
+ 'query-projections',
+ 'replica:projectFileIndex:v1:',
+ );
+ expect(rows.filter(({ key }) => !key.includes('__replica'))).toHaveLength(1);
+ view.unmount();
+ });
+
+ it('keeps a remote overlay when the device read fails', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({
+ added: [],
+ deleted: [],
+ modified: ['a.ts'],
+ });
+
+ const view = await boot();
+ await waitFor(() => expect(view.result.current.git.data?.modified).toEqual(['a.ts']));
+
+ services.getGitWorkingTreeFiles.mockResolvedValue(undefined);
+ await act(async () => {
+ await view.result.current.git.mutate().catch(() => {});
+ });
+
+ await waitFor(() => expect(view.result.current.git.error).toBeTruthy());
+ expect(view.result.current.git.data?.modified).toEqual(['a.ts']);
+
+ const db = await readRows();
+ const rows = await db.entriesByPrefix<{ data: unknown }>(
+ 'query-projections',
+ 'replica:gitWorkingTreeFiles:v1:',
+ );
+ expect(rows.filter(({ key }) => !key.includes('__replica'))).toHaveLength(1);
+ view.unmount();
+ });
+
+ it('keeps trees apart per identity, device and directory', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({ added: [], deleted: [], modified: [] });
+ const first = await boot();
+ await waitFor(() => expect(first.result.current.project.data?.entries).toHaveLength(1));
+ first.unmount();
+
+ services.getProjectFileIndex.mockReturnValue(never());
+ services.getGitWorkingTreeFiles.mockReturnValue(never());
+
+ // Another identity on the same device + directory sees nothing saved.
+ scope.current = 'u2:personal';
+ const otherUser = await boot();
+ await waitFor(() => expect(otherUser.result.current.project.isValidating).toBe(true));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(otherUser.result.current.project.data).toBeUndefined();
+ expect(otherUser.result.current.project.isLoading).toBe(true);
+
+ // The same identity on another device, or another directory, neither.
+ scope.current = 'u1:personal';
+ otherUser.rerender({ deviceId: 'device-2', dir: '/repo' });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(otherUser.result.current.project.data).toBeUndefined();
+ otherUser.rerender({ deviceId: 'device-1', dir: '/other' });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(otherUser.result.current.project.data).toBeUndefined();
+
+ // And the original combination still restores.
+ otherUser.rerender({ deviceId: 'device-1', dir: '/repo' });
+ await waitFor(() => expect(otherUser.result.current.project.data?.entries).toHaveLength(1));
+ otherUser.unmount();
+ });
+
+ it('stores the tree slim, not through the SWR cache', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({ added: [], deleted: [], modified: [] });
+ const view = await boot();
+ await waitFor(() => expect(view.result.current.project.data?.entries).toHaveLength(1));
+
+ const db = await readRows();
+ const rows = () =>
+ db.entriesByPrefix<{ data: unknown }>('query-projections', 'replica:projectFileIndex:v1:');
+ await waitFor(async () =>
+ expect((await rows()).some(({ key }) => !key.includes('__replica'))).toBe(true),
+ );
+ const row = (await rows()).find(({ key }) => !key.includes('__replica'))!;
+ // `[relativePath, flags]`: path and name derive from the root.
+ expect((row.value.data as { entries: unknown[] }).entries).toEqual([['a.ts', 0]]);
+ view.unmount();
+ });
+
+ it('does not keep an overlay past the path cap in the bounded index', async () => {
+ services.getProjectFileIndex.mockResolvedValue(tree(['a.ts']));
+ services.getGitWorkingTreeFiles.mockResolvedValue({
+ added: [],
+ deleted: [],
+ modified: Array.from({ length: 5001 }, (_, index) => `f${index}.ts`),
+ });
+
+ const first = await boot();
+ await waitFor(() => expect(first.result.current.git.data?.modified).toHaveLength(5001));
+
+ // Nothing is stored: not the row, and not a ghost key in the index that
+ // would later evict a real overlay from the bounded LRU.
+ const db = await readRows();
+ const rows = () =>
+ db.entriesByPrefix<{ data: unknown }>('query-projections', 'replica:gitWorkingTreeFiles:v1:');
+ await waitFor(async () => {
+ const all = await rows();
+ expect(all.filter(({ key }) => !key.includes('__replica'))).toHaveLength(0);
+ const index = all.find(({ key }) => key.includes('__replica'));
+ expect((index?.value.data as string[] | undefined) ?? []).toEqual([]);
+ });
+ first.unmount();
+
+ // A reload has nothing to paint for that overlay.
+ services.getGitWorkingTreeFiles.mockReturnValue(never());
+ const second = await boot();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(second.result.current.git.data).toBeUndefined();
+ second.unmount();
+ });
+});
diff --git a/src/store/projectFile/store.ts b/src/store/projectFile/store.ts
new file mode 100644
index 00000000000..5cce63f40d3
--- /dev/null
+++ b/src/store/projectFile/store.ts
@@ -0,0 +1,15 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { expose } from '../middleware/expose';
+import { initialProjectFileState, type ProjectFileState } from './initialState';
+
+const devtools = createDevtools('projectFile');
+
+export const useProjectFileStore = createWithEqualityFn<ProjectFileState>()(
+ devtools(() => initialProjectFileState),
+ shallow,
+);
+
+expose('projectFile', useProjectFileStore);
diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.ts
index 523f49cc8ba..b9aa3488693 100644
--- a/src/store/utils/userDataStores.ts
+++ b/src/store/utils/userDataStores.ts
@@ -15,6 +15,7 @@ import { useKnowledgeBaseStore } from '@/store/library';
import { useMentionStore } from '@/store/mention';
import { useNotebookStore } from '@/store/notebook';
import { pageActions } from '@/store/page';
+import { projectFileActions } from '@/store/projectFile';
import { sandboxActions } from '@/store/sandbox';
import { useSessionStore } from '@/store/session';
import { useTaskStore } from '@/store/task';
@@ -49,7 +50,12 @@ const resetableStores: ResetableStoreApi[] = [
useVideoStore,
];
-const resetableActions: ResetableStore[] = [agentDocumentActions, pageActions, sandboxActions];
+const resetableActions: ResetableStore[] = [
+ agentDocumentActions,
+ pageActions,
+ projectFileActions,
+ sandboxActions,
+];
export interface StoreActions extends ResetableStore {}