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(chat): render project sends optimistically without awaiting directory resolve (#20897)

Arvin Xude65b23b466e
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.test.ts b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
index 44e9195a67c..0ca058652c7 100644
--- a/src/features/Projects/WorkingDirectories/checkExecution.test.ts
+++ b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { deviceService } from '@/services/device';
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+import { type ProjectDirectory, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { checkProjectExecution } from './checkExecution';
@@ -46,4 +47,59 @@ describe('project send preflight', () => {
expect(resolve).toHaveBeenCalledWith('directory');
expect(stat).not.toHaveBeenCalled();
});
+
+ // Regression: the DB resolve held every project send behind a network round
+ // trip before the composer even cleared. The sidebar's directory replica
+ // already carries the binding, so a loaded row is checked locally.
+ describe('with the directory row in the local replica', () => {
+ const row = {
+ deviceId: 'pinned-device',
+ environmentId: 'env',
+ id: 'directory',
+ instanceId: 'instance',
+ permission: 'readWrite',
+ projectId: 'project',
+ } as ProjectDirectory;
+
+ afterEach(() => useProjectDirectoryStore.setState({ directoriesMap: {} }));
+
+ it('passes without resolving over the network', async () => {
+ useProjectDirectoryStore.setState({ directoriesMap: { all: [row] } });
+ const resolve = vi.spyOn(projectWorkingDirectoryService, 'resolve');
+
+ await expect(checkProjectExecution(topic, true)).resolves.toBeUndefined();
+ expect(resolve).not.toHaveBeenCalled();
+ });
+
+ // Regression: a cached unlinked/read-only row was rejected locally, but the
+ // replica can lag a change (`attachEnvironment` refreshes only environments),
+ // so a send the server would accept was blocked. Negative states re-resolve.
+ it.each([
+ ['unlinked', { environmentId: null, instanceId: null }],
+ ['read-only', { permission: 'read' }],
+ ])('re-resolves a cached %s row and passes when the server accepts it', async (_, patch) => {
+ useProjectDirectoryStore.setState({
+ directoriesMap: { all: [{ ...row, ...patch } as ProjectDirectory] },
+ });
+ const resolve = vi
+ .spyOn(projectWorkingDirectoryService, 'resolve')
+ .mockResolvedValue({ data: row, success: true } as any);
+
+ await expect(checkProjectExecution(topic, true)).resolves.toBeUndefined();
+ expect(resolve).toHaveBeenCalledWith('directory');
+ });
+
+ it('rejects a cached negative row the server still refuses', async () => {
+ useProjectDirectoryStore.setState({
+ directoriesMap: { all: [{ ...row, permission: 'read' } as ProjectDirectory] },
+ });
+ vi.spyOn(projectWorkingDirectoryService, 'resolve').mockRejectedValue(
+ new Error('This directory is read-only'),
+ );
+
+ await expect(checkProjectExecution(topic, true)).rejects.toThrow(
+ 'This directory is read-only',
+ );
+ });
+ });
});
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.ts b/src/features/Projects/WorkingDirectories/checkExecution.ts
index 6b3d92f165a..974c3c02218 100644
--- a/src/features/Projects/WorkingDirectories/checkExecution.ts
+++ b/src/features/Projects/WorkingDirectories/checkExecution.ts
@@ -2,23 +2,30 @@ import type { ChatTopic } from '@lobechat/types';
import { t } from 'i18next';
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+import { findProjectDirectory } from '@/store/projectWorkingDirectory';
/**
* UI preflight for a project-directory conversation, run before the composer is
* cleared so a rejected send keeps the user's text and uploads.
*
- * Resolves the binding (DB only) so a directory that was deleted, unlinked or
- * made read-only while the conversation was open still rejects up front. It
- * deliberately does NOT probe the device with `deviceService.statPath`: that
- * round trip sat in front of every send — up to its 8s timeout — and rejected
- * the message when the device was merely slow to answer. Whether the directory
- * still exists on the device is discovered by the dispatch that follows, which
- * is the single source of truth for liveness; the runtime revalidates the
- * binding before every execution.
+ * Checks the binding so a directory that was deleted, unlinked or made
+ * read-only while the conversation was open still rejects up front. A usable
+ * row in the sidebar's directory replica passes without a network round trip —
+ * a resolve here sat in front of every send. The replica only ever lets a send
+ * through: it can lag a change (linking an environment refreshes environments,
+ * not directories), so a missing or negative cached row asks the server, which
+ * throws for a missing, disabled or read-only directory. The runtime still
+ * revalidates the full binding before every execution, and a rejected dispatch
+ * restores the composer itself. It deliberately does NOT probe the device with
+ * `deviceService.statPath`: whether the directory still exists on the device
+ * is discovered by the dispatch that follows.
*/
export async function checkProjectExecution(topic: ChatTopic | undefined, gatewayEnabled: boolean) {
if (!topic?.projectWorkingDirectoryId) return;
if (!gatewayEnabled) throw new Error(t('topics.gatewayUnavailable', { ns: 'project' }));
- // Throws for a missing, disabled or read-only directory.
+
+ const directory = findProjectDirectory(topic.projectWorkingDirectoryId);
+ if (directory?.instanceId && directory.environmentId && directory.permission === 'readWrite')
+ return;
await projectWorkingDirectoryService.resolve(topic.projectWorkingDirectoryId);
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index a4c95dbbaa3..9d473122232 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -24,6 +24,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { useDeviceStore } from '@/store/device';
import { fileChatSelectors, useFileStore } from '@/store/file';
+import { type ProjectDirectory, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { getSessionStoreState } from '@/store/session';
import * as toolStoreModule from '@/store/tool';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
@@ -482,6 +483,104 @@ describe('ConversationLifecycle actions', () => {
);
});
+ // Regression: every project send awaited `projectWorkingDirectory.resolve`
+ // before the optimistic pair was dispatched, so the message only appeared
+ // after a network round trip. The directory replica already holds the row.
+ describe('project directory read from the local replica', () => {
+ const directoryRow = {
+ deviceId: 'device-85',
+ environmentId: 'env-85',
+ id: 'dir-85',
+ instanceId: 'inst-85',
+ projectId: 'prj-1',
+ } as ProjectDirectory;
+
+ afterEach(() => {
+ useProjectDirectoryStore.setState({ directoriesMap: {} });
+ });
+
+ const sendWithPendingGateway = async (context: ReturnType<typeof createTestContext>) => {
+ const { projectWorkingDirectoryService } =
+ await import('@/services/projectWorkingDirectory');
+ const resolveSpy = vi.spyOn(projectWorkingDirectoryService, 'resolve');
+ let releaseGateway!: () => void;
+ const executeGatewayAgentSpy = vi.fn(
+ () =>
+ new Promise((resolve) => {
+ releaseGateway = () => resolve({ topicId: 'tpc_new' });
+ }),
+ );
+ useProjectDirectoryStore.setState({ directoriesMap: { all: [directoryRow] } });
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy as any,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ let sendPromise!: Promise<unknown>;
+ await act(async () => {
+ sendPromise = result.current.sendMessage({ context, message: 'Project send' });
+ });
+ await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalled());
+
+ const optimisticUser = Object.values(useChatStore.getState().dbMessagesMap)
+ .flat()
+ .find((message) => message.role === 'user' && message.content === 'Project send');
+
+ await act(async () => {
+ releaseGateway();
+ await sendPromise;
+ });
+
+ return { executeGatewayAgentSpy, optimisticUser, resolveSpy };
+ };
+
+ it('dispatches a staged-directory send without awaiting resolve', async () => {
+ act(() => {
+ useChatStore.setState({
+ pendingNewTopicDirectory: {
+ agentId: TEST_IDS.SESSION_ID,
+ projectWorkingDirectoryId: 'dir-85',
+ },
+ });
+ });
+
+ const { executeGatewayAgentSpy, optimisticUser, resolveSpy } =
+ await sendWithPendingGateway(createTestContext());
+
+ expect(resolveSpy).not.toHaveBeenCalled();
+ expect(optimisticUser).toBeDefined();
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ projectWorkingDirectoryId: 'dir-85' }),
+ );
+ });
+
+ it('dispatches a send in a directory-bound topic without awaiting resolve', async () => {
+ act(() => {
+ useChatStore.setState({
+ topicDetailMap: {
+ tpc_bound: {
+ createdAt: Date.now(),
+ id: 'tpc_bound',
+ projectWorkingDirectoryId: 'dir-85',
+ title: 'Bound',
+ updatedAt: Date.now(),
+ } as any,
+ },
+ });
+ });
+
+ const { executeGatewayAgentSpy, optimisticUser, resolveSpy } =
+ await sendWithPendingGateway({ ...createTestContext(), topicId: 'tpc_bound' });
+
+ expect(resolveSpy).not.toHaveBeenCalled();
+ expect(optimisticUser).toBeDefined();
+ expect(executeGatewayAgentSpy).toHaveBeenCalled();
+ });
+ });
+
it('should restore the pre-send editor snapshot when a gateway send fails', async () => {
// Regression: the composer is cleared the instant Enter is pressed, and
// only the client-runtime branch put the text back. The gateway branch
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 922371c0c10..9d0c5bcb1ed 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -110,6 +110,7 @@ import { getElectronStoreState } from '@/store/electron';
import { getFileStoreState } from '@/store/file/store';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { findProjectDirectory } from '@/store/projectWorkingDirectory';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { type StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
@@ -512,7 +513,13 @@ export class ConversationLifecycleActionImpl {
const projectDirectoryId = boundTopic?.projectWorkingDirectoryId ?? stagedDirectoryId;
let stagedDirectory: { id: string; projectId: string } | undefined;
if (projectDirectoryId) {
- const { data: directory } = await projectWorkingDirectoryService.resolve(projectDirectoryId);
+ // The sidebar's directory replica already holds the row; read it locally
+ // so the optimistic pair is not held behind a network round trip. The
+ // server re-validates the directory (environment link, enabled state,
+ // permission) when it starts the run. Only a cold replica pays for resolve.
+ const directory =
+ findProjectDirectory(projectDirectoryId) ??
+ (await projectWorkingDirectoryService.resolve(projectDirectoryId)).data;
if (stagedDirectoryId) stagedDirectory = directory;
if (!isGatewayMode)
throw new Error('Enable Gateway Mode to run in a project working directory');
diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.ts
index 1f4b8e6e66b..0247435f473 100644
--- a/src/store/projectWorkingDirectory/index.test.ts
+++ b/src/store/projectWorkingDirectory/index.test.ts
@@ -4,7 +4,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
-import { PROJECT_TOPICS_POLL_INTERVAL, useProjectDirectoryStore } from './index';
+import {
+ findProjectDirectory,
+ PROJECT_TOPICS_POLL_INTERVAL,
+ type ProjectDirectory,
+ useProjectDirectoryStore,
+} from './index';
vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
@@ -167,3 +172,78 @@ describe('projectWorkingDirectory store', () => {
});
});
});
+
+describe('findProjectDirectory', () => {
+ const stale = { id: 'dir-1', permission: 'read', projectId: 'project-1' } as ProjectDirectory;
+ const fresh = { ...stale, permission: 'readWrite' } as ProjectDirectory;
+
+ afterEach(() => {
+ useProjectDirectoryStore.setState({
+ directoriesMap: {},
+ directoriesReplica: { entries: {} } as any,
+ });
+ });
+
+ const seed = (projections: [key: string, row: ProjectDirectory, updatedAt: number][]) =>
+ useProjectDirectoryStore.setState({
+ directoriesMap: Object.fromEntries(projections.map(([key, row]) => [key, [row]])),
+ directoriesReplica: {
+ entries: Object.fromEntries(
+ projections.map(([key, , updatedAt]) => [
+ key,
+ { pending: [], source: 'network', updatedAt },
+ ]),
+ ),
+ } as any,
+ });
+
+ // Regression: the lookup returned whichever projection was loaded first, so a
+ // stale scope-wide copy could shadow a per-project copy refreshed after a
+ // permission change (and the reverse).
+ it('returns the most recently confirmed copy regardless of load order', () => {
+ seed([
+ ['all', stale, 1000],
+ ['project-1', fresh, 2000],
+ ]);
+ expect(findProjectDirectory('dir-1')?.permission).toBe('readWrite');
+
+ seed([
+ ['project-1', stale, 1000],
+ ['all', fresh, 2000],
+ ]);
+ expect(findProjectDirectory('dir-1')?.permission).toBe('readWrite');
+ });
+
+ // Regression: a newer projection that dropped the row (directory deleted) was
+ // skipped, so a stale copy in an older projection still passed the preflight.
+ it('treats a newer covering projection that omits the row as authoritative', () => {
+ useProjectDirectoryStore.setState({
+ directoriesMap: { 'all': [fresh], 'project-1': [] },
+ directoriesReplica: {
+ entries: {
+ 'all': { pending: [], source: 'network', updatedAt: 1000 },
+ 'project-1': { pending: [], source: 'network', updatedAt: 2000 },
+ },
+ } as any,
+ });
+ expect(findProjectDirectory('dir-1')).toBeUndefined();
+ });
+
+ it('ignores another project projection that would never list the row', () => {
+ useProjectDirectoryStore.setState({
+ directoriesMap: { 'all': [fresh], 'project-2': [] },
+ directoriesReplica: {
+ entries: {
+ 'all': { pending: [], source: 'network', updatedAt: 1000 },
+ 'project-2': { pending: [], source: 'network', updatedAt: 2000 },
+ },
+ } as any,
+ });
+ expect(findProjectDirectory('dir-1')?.permission).toBe('readWrite');
+ });
+
+ it('returns undefined when no projection holds the row', () => {
+ seed([['all', fresh, 1000]]);
+ expect(findProjectDirectory('missing')).toBeUndefined();
+ });
+});
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
index 40310bbb569..ce0ffc95e3a 100644
--- a/src/store/projectWorkingDirectory/index.ts
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -328,6 +328,27 @@ export const useProjectDirectories = (projectId?: string) =>
rowsOf(state.directoriesMap, projectId ?? ALL_PROJECTS_KEY, EMPTY_DIRECTORIES),
);
+/**
+ * One directory row, outside React. Only the scope-wide (`all`) projection and
+ * the row's own project projection would list it; they revalidate
+ * independently, so the most recently confirmed of them decides — including
+ * when it no longer lists the row (the directory was deleted), which returns
+ * `undefined` so callers fall back to the server.
+ */
+export const findProjectDirectory = (id: string): ProjectDirectory | undefined => {
+ const { directoriesMap, directoriesReplica } = useProjectDirectoryStore.getState();
+ const projectId = Object.values(directoriesMap)
+ .flat()
+ .find((row) => row.id === id)?.projectId;
+ if (!projectId) return undefined;
+
+ const freshness = (key: string) => directoriesReplica.entries[key]?.updatedAt ?? 0;
+ const newestKey = [ALL_PROJECTS_KEY, projectId]
+ .filter((key) => directoriesMap[key])
+ .reduce((newest, key) => (freshness(key) > freshness(newest) ? key : newest));
+ return directoriesMap[newestKey].find((row) => row.id === id);
+};
+
/** Environments of one project, or every environment of the scope. */
export const useProjectEnvironments = (projectId?: string) =>
useProjectDirectoryStore((state) =>