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(portal): smoother artifact open and stable sidebar tree on reveal (#21583)

YuTengjing2c759f545c13
diff --git a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
index 119e3f72724..4863e0063a1 100644
--- a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
@@ -78,6 +78,25 @@ describe('useReviewPatches', () => {
);
});
+ it('keeps the last diff without reading while the review tab is inactive', async () => {
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({
+ patches: [{ path: 'kept.ts' }],
+ } as any);
+ const { result, rerender } = renderHook(
+ ({ active }) => useReviewPatches('/kept-repo', 'unstaged', undefined, undefined, active),
+ { initialProps: { active: true }, wrapper },
+ );
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ const data = result.current.data;
+ const reads = vi.mocked(gitService.getGitWorkingTreePatches).mock.calls.length;
+
+ rerender({ active: false });
+ expect(result.current.data).toBe(data);
+ expect(result.current.isLoading).toBe(false);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(gitService.getGitWorkingTreePatches).toHaveBeenCalledTimes(reads);
+ });
+
it('does not request local git patches from a web client without a target device', async () => {
platform.isDesktop = false;
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
index 8d2b5cc9440..b9cb60195c7 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
@@ -107,7 +107,7 @@ const browserPanes = vi.hoisted(() => ({
}));
const renderedReview = vi.hoisted(() => ({
- current: undefined as { composerTarget: ComposerTarget } | undefined,
+ current: undefined as { active: boolean; composerTarget: ComposerTarget } | undefined,
}));
const localStorageState = vi.hoisted(() => ({
@@ -189,7 +189,7 @@ vi.mock('../Files/FilesPrefetch', () => ({
},
}));
vi.mock('../Review', () => ({
- default: (props: { composerTarget: ComposerTarget }) => {
+ default: (props: { active: boolean; composerTarget: ComposerTarget }) => {
renderedReview.current = props;
return <div data-testid="review" />;
},
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index d4695f80980..a49081a5bcc 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -696,6 +696,50 @@ describe('AgentWorkingSidebar — tab strip', () => {
expect(screen.queryByTestId('review')).not.toBeInTheDocument();
});
+ it('keeps the active Review mounted while the panel is collapsed', () => {
+ agentStore.activeAgentId = 'agent';
+ reviewState.repoType = 'git';
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = { 'draft:agent:/repo': ['review'] };
+ globalStore.status.workingSidebarTab = 'review';
+
+ // A new `availableWidth` on each rerender gets past the sidebar's `memo`.
+ const { rerender } = render(<AgentWorkingSidebar availableWidth={1600} />);
+ const review = screen.getByTestId('review');
+ expect(renderedReview.current?.active).toBe(true);
+
+ globalStore.status.showRightPanel = false;
+ rerender(<AgentWorkingSidebar availableWidth={1601} />);
+ expect(review).toBeInTheDocument();
+
+ globalStore.status.showRightPanel = true;
+ rerender(<AgentWorkingSidebar availableWidth={1602} />);
+ expect(screen.getByTestId('review')).toBe(review);
+ expect(renderedReview.current?.active).toBe(true);
+ });
+
+ it('releases Review once the panel stays collapsed', () => {
+ vi.useFakeTimers();
+ try {
+ agentStore.activeAgentId = 'agent';
+ reviewState.repoType = 'git';
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = { 'draft:agent:/repo': ['review'] };
+ globalStore.status.workingSidebarTab = 'review';
+
+ const { rerender } = render(<AgentWorkingSidebar availableWidth={1600} />);
+ globalStore.status.showRightPanel = false;
+ rerender(<AgentWorkingSidebar availableWidth={1601} />);
+ act(() => vi.advanceTimersByTime(29_000));
+ expect(screen.getByTestId('review')).toBeInTheDocument();
+
+ act(() => vi.advanceTimersByTime(1000));
+ expect(screen.queryByTestId('review')).not.toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('opens Skills and Documents by default for a new workspace context', () => {
localStorageState.openTabsByContext = {};
globalStore.status.workingSidebarTab = 'overview';
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 6d5cd5cfc78..948d9588498 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -90,6 +90,7 @@ import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
import { TopicSearchPane } from './Search';
+import { useRetainAfterHide } from './useRetainAfterHide';
import { useSandboxFilesDirectory } from './useSandboxFilesDirectory';
import { useTabContextMenuItems } from './useTabContextMenuItems';
import WorkspaceTab from './WorkspaceTab';
@@ -187,6 +188,8 @@ const PINNED_TABS_STORAGE_KEY = 'lobechat-working-sidebar-pinned-tabs-v1';
const OVERVIEW_TRANSITION = { duration: 0.25, ease: [0.32, 0.72, 0, 1] } as const;
// Two-pane Review (diff list + file-tree rail) is cramped below this.
const TWO_PANE_MIN_WIDTH = 560;
+/** How long a collapsed panel keeps Review mounted for a quick reopen. */
+const REVIEW_RETAIN_MS = 30_000;
interface AgentWorkingSidebarProps {
/**
@@ -830,6 +833,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
portalWidth: portalOpen ? portalWidth : 0,
});
const fits = widthBudget >= minDisplayWidth;
+ const panelVisible = !!showRightPanel && fits;
+ const retainReview = useRetainAfterHide(panelVisible, REVIEW_RETAIN_MS);
const overviewFits = widthBudget >= MIN_PANEL_WIDTH;
const renderWidth = Math.min(displayWidth, Math.max(widthBudget, minDisplayWidth));
// Also cap the drag range so releasing a drag can never persist a width that
@@ -1080,17 +1085,23 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
</Suspense>
</Flexbox>
)}
- {reviewAvailable && showRightPanel && fits && activeTab === 'review' && (
- <Flexbox className={styles.pane}>
- <Review
- active
- composerTarget={composerTarget}
- deviceId={remoteDeviceId}
- showTree={showReviewTree}
- workingDirectory={workingDirectory}
- onToggleTree={() => setShowReviewTree((v) => !v)}
- />
- </Flexbox>
+ {/* Switching tabs unmounts Review to release its diff DOM (#18984).
+ Collapsing the panel hides it for REVIEW_RETAIN_MS first: remounting
+ all diffs and the tree on a quick reopen stalls the open animation
+ for ~200ms. */}
+ {reviewAvailable && activeTab === 'review' && retainReview && (
+ <Activity mode={panelVisible ? 'visible' : 'hidden'}>
+ <Flexbox className={styles.pane}>
+ <Review
+ active={panelVisible}
+ composerTarget={composerTarget}
+ deviceId={remoteDeviceId}
+ showTree={showReviewTree}
+ workingDirectory={workingDirectory}
+ onToggleTree={() => setShowReviewTree((v) => !v)}
+ />
+ </Flexbox>
+ </Activity>
)}
{pullRequest && workingDirectory && (
<Activity mode={showRightPanel && activeTab === 'pr' ? 'visible' : 'hidden'}>
diff --git a/src/features/Conversation/WorkingSidebar/useRetainAfterHide.ts b/src/features/Conversation/WorkingSidebar/useRetainAfterHide.ts
new file mode 100644
index 00000000000..753802f410b
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/useRetainAfterHide.ts
@@ -0,0 +1,21 @@
+import { useEffect, useState } from 'react';
+
+/**
+ * Returns `true` while `visible`, and for `delay` ms after it turns `false`.
+ * Lets a hidden subtree stay mounted for a quick reopen, then release its DOM
+ * when it stays hidden.
+ */
+export const useRetainAfterHide = (visible: boolean, delay: number): boolean => {
+ const [retained, setRetained] = useState(visible);
+
+ useEffect(() => {
+ if (visible) {
+ setRetained(true);
+ return;
+ }
+ const timer = setTimeout(() => setRetained(false), delay);
+ return () => clearTimeout(timer);
+ }, [visible, delay]);
+
+ return visible || retained;
+};
diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
index 360fd5a2eb2..8de16adf4c2 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
@@ -1,7 +1,7 @@
import { AGENT_DOCUMENT_CATEGORY, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
import type { RefObject } from 'react';
-import { useRef } from 'react';
+import { Activity, useRef } from 'react';
import { MemoryRouter } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
@@ -558,3 +558,26 @@ describe('ExplorerTree sort', () => {
);
});
});
+
+describe('ExplorerTree inside a hidden Activity', () => {
+ // The working sidebar keeps its panes mounted in <Activity>; hiding it runs
+ // effect cleanups without unmounting the tree.
+ it('keeps rows added before the tree was hidden and shown again', async () => {
+ const nodes: ExplorerTreeNode[] = [{ id: 'a', isFolder: false, name: 'a.md', parentId: null }];
+ const added = [...nodes, { id: 'b', isFolder: false, name: 'b.md', parentId: null }];
+ const renderIn = (mode: 'hidden' | 'visible', treeNodes: ExplorerTreeNode[]) => (
+ <Activity mode={mode}>
+ <ExplorerTree nodes={treeNodes} />
+ </Activity>
+ );
+
+ const view = render(renderIn('visible', nodes));
+ view.rerender(renderIn('visible', added));
+ await waitFor(() => expect(getSortedRowPaths(view.container)).toEqual(['a.md', 'b.md']));
+
+ view.rerender(renderIn('hidden', added));
+ view.rerender(renderIn('visible', added));
+
+ await waitFor(() => expect(getSortedRowPaths(view.container)).toEqual(['a.md', 'b.md']));
+ });
+});
diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsx
index 5377803eff2..6fb0dc79514 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx
@@ -1,12 +1,13 @@
'use client';
-import type {
- FileTreeDirectoryHandle,
- FileTreeItemHandle,
- FileTreeOptions,
- FileTreeRowDecoration,
+import {
+ FileTree as FileTreeModel,
+ type FileTreeDirectoryHandle,
+ type FileTreeItemHandle,
+ type FileTreeOptions,
+ type FileTreeRowDecoration,
} from '@pierre/trees';
-import { FileTree as PierreFileTree, useFileTree, useFileTreeSelection } from '@pierre/trees/react';
+import { FileTree as PierreFileTree, useFileTreeSelection } from '@pierre/trees/react';
import debug from 'debug';
import type { DragEvent, ForwardedRef, KeyboardEvent, MouseEvent } from 'react';
import {
@@ -43,8 +44,6 @@ const asDirectory = (
): FileTreeDirectoryHandle | null =>
handle && handle.isDirectory() ? (handle as FileTreeDirectoryHandle) : null;
-type FileTreeModel = ReturnType<typeof useFileTree>['model'];
-
// @pierre/trees walks a lookup path segment by segment and asks for each
// intermediate node's directory child index *before* checking that the node is
// a directory, so looking up `a/b` while `a` is a file throws
@@ -293,7 +292,12 @@ function ExplorerTreeInner<TData>(
}, []);
const renamingNodeRef = useRef<ExplorerTreeNode<TData> | null>(null);
- const { model } = useFileTree(initialOptions);
+ // Not `useFileTree`: it destroys the model in an effect cleanup, which also
+ // runs when an <Activity> ancestor hides the tree (the working sidebar). On
+ // reveal the tree kept using the destroyed model and fell back to the paths it
+ // was created with. The model holds no global listeners, so garbage collection
+ // releases it after a real unmount, and <PierreFileTree> detaches its DOM.
+ const model = useSingleton(() => new FileTreeModel(initialOptions));
// Drops whatever the tree applied optimistically (rename, drop, new row) by
// re-applying the current nodes, keeping expansion, selection and focus.
diff --git a/src/features/Portal/Home/Body/Files/FileList/index.tsx b/src/features/Portal/Home/Body/Files/FileList/index.tsx
index 93c13e38fa8..632d38dc5c2 100644
--- a/src/features/Portal/Home/Body/Files/FileList/index.tsx
+++ b/src/features/Portal/Home/Body/Files/FileList/index.tsx
@@ -1,8 +1,8 @@
import { Avatar, Center, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { InboxIcon } from 'lucide-react';
+import type { CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
-import Balancer from 'react-wrap-balancer';
import SkeletonLoading from '@/components/Loading/SkeletonLoading';
import { useChatStore } from '@/store/chat';
@@ -10,6 +10,13 @@ import { chatSelectors } from '@/store/chat/selectors';
import FileItem from './Item';
+/**
+ * Native balancing instead of react-wrap-balancer: this empty state is pre-rendered
+ * inside the hidden portal, and the library's layout-effect binary search forced
+ * ~20 synchronous page layouts in the commit that opens an artifact.
+ */
+const BALANCED_TEXT: CSSProperties = { textWrap: 'balance' };
+
const FileList = () => {
const { t } = useTranslation('portal');
const files = useChatStore(chatSelectors.currentUserFiles, isEqual);
@@ -31,9 +38,9 @@ const FileList = () => {
shape={'square'}
size={48}
/>
- <Balancer>
- <Text type={'secondary'}>{t('emptyKnowledgeList')}</Text>
- </Balancer>
+ <Text style={BALANCED_TEXT} type={'secondary'}>
+ {t('emptyKnowledgeList')}
+ </Text>
</Center>
) : (
<Flexbox gap={12} paddingInline={12}>
diff --git a/src/features/Portal/Home/Body/Plugins/ArtifactList/index.tsx b/src/features/Portal/Home/Body/Plugins/ArtifactList/index.tsx
index bebb933df93..74c5ff51e72 100644
--- a/src/features/Portal/Home/Body/Plugins/ArtifactList/index.tsx
+++ b/src/features/Portal/Home/Body/Plugins/ArtifactList/index.tsx
@@ -1,14 +1,21 @@
import { Avatar, Center, cssVar, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { Origami } from 'lucide-react';
+import type { CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
-import Balancer from 'react-wrap-balancer';
import { useChatStore } from '@/store/chat';
import { dbMessageSelectors, displayMessageSelectors } from '@/store/chat/selectors';
import ArtifactItem from './Item';
+/**
+ * Native balancing instead of react-wrap-balancer: this empty state is pre-rendered
+ * inside the hidden portal, and the library's layout-effect binary search forced
+ * ~20 synchronous page layouts in the commit that opens an artifact.
+ */
+const BALANCED_TEXT: CSSProperties = { textWrap: 'balance' };
+
const ArtifactList = () => {
const { t } = useTranslation('portal');
const messages = useChatStore(dbMessageSelectors.dbToolMessages, isEqual);
@@ -32,9 +39,9 @@ const ArtifactList = () => {
shape={'square'}
size={48}
/>
- <Balancer>
- <Text type={'secondary'}>{t('emptyArtifactList')}</Text>
- </Balancer>
+ <Text style={BALANCED_TEXT} type={'secondary'}>
+ {t('emptyArtifactList')}
+ </Text>
</Center>
) : (
<Flexbox gap={12} paddingInline={12}>
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 84e437c40cf..ffe24c6ecba 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -142,6 +142,8 @@ const useGitReviewReplica = <TParams, TStored>(
toKey: (params: TParams) => string,
params: TParams | null,
schedule: GitReplicaSyncOptions<TStored>,
+ /** Params to sync; `null` pauses syncing while `params` still reads the stored row. */
+ syncParams: TParams | null = params,
) => {
const key = params ? toKey(params) : undefined;
const stored = useGitReviewStore((s) => (key ? selectMap(s)[key] : undefined));
@@ -151,12 +153,12 @@ const useGitReviewReplica = <TParams, TStored>(
// unreachable device, missing `gh`) is not retried, like the SWR hooks these replaced.
const { error, isHydrated, isValidating, revalidate } = pick(
useGitReviewStore.getState().slices,
- ).useSync(params, { ...schedule, shouldRetryOnError: false });
+ ).useSync(syncParams, { ...schedule, shouldRetryOnError: false });
return {
error,
isConfirmed,
- isLoading: !!params && stored === undefined && !error && (!isHydrated || isValidating),
+ isLoading: !!syncParams && stored === undefined && !error && (!isHydrated || isValidating),
isValidating,
mutate: revalidate,
stored,
@@ -195,7 +197,7 @@ export const useReviewPatches = (
deviceId?: string,
active = true,
): GitReplicaReadResult<ReviewPatchesData> => {
- const enabled = active && isEnabled(deviceId, dirPath);
+ const enabled = isEnabled(deviceId, dirPath);
const params = useMemo(
() => (enabled ? { baseRef, deviceId, mode, path: dirPath! } : null),
[enabled, baseRef, deviceId, mode, dirPath],
@@ -213,6 +215,9 @@ export const useReviewPatches = (
revalidateOnFocus: true,
revalidateOnReconnect: true,
},
+ // Inactive callers (a collapsed Review panel) keep the last diff instead of
+ // dropping to undefined, so reopening does not re-render every file from empty.
+ active ? params : null,
);
return { ...rest, data: stored };
};