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(project-directory): drop the blocking device probe from the send path (#20628)

Arvin Xu6e7f82e84c54
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 30db522d1d3..8d4a12a70bd 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -23,6 +23,9 @@ const { mockDeviceProxy } = vi.hoisted(() => ({
isConfigured: false,
queryDeviceList: vi.fn().mockResolvedValue([]),
queryDeviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ // Present so a send-path regression that probes the device shows up as a
+ // failed assertion rather than a "not a function" crash.
+ statPath: vi.fn().mockResolvedValue({ exists: true, isDirectory: true }),
},
}));
@@ -751,6 +754,79 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(mockResolveProjectDirectoryForTopic).not.toHaveBeenCalled();
expect(mockCreateOperation).toHaveBeenCalled();
});
+
+ // Regression: the send path used to `await deviceGateway.statPath(...)` to
+ // pre-check the directory, putting a full device WebSocket round trip (up to
+ // its 8s timeout) in front of every message and rejecting the send when the
+ // device was merely slow to answer. Liveness is the dispatch's to discover.
+ it('routes a project-directory topic without a device round trip on the send path', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ topicMock.findById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { boundDeviceId: 'device-001', workingDirectory: '/repo' },
+ projectId: 'project-1',
+ projectWorkingDirectoryId: 'dir-1',
+ });
+ mockResolveProjectDirectoryForTopic.mockResolvedValueOnce({
+ deviceId: 'device-001',
+ path: '/repo',
+ permission: 'readWrite',
+ platform: 'darwin',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Keep working',
+ appContext: { topicId: 'topic-1' },
+ });
+
+ expect(mockDeviceProxy.statPath).not.toHaveBeenCalled();
+ expect(mockCreateOperation).toHaveBeenCalled();
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
+ });
+
+ // Regression: the directory lives on one device, so an offline device has to
+ // reject the send *before* the user/assistant rows are persisted. A
+ // rejection after persistence leaves a failed turn durable server-side while
+ // the client treats the send as unaccepted, rolls its optimistic pair back
+ // and keeps the draft β€” and retrying then stacks duplicate failed turns.
+ it('rejects an offline bound device before persisting the turn', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
+ topicMock.findById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { boundDeviceId: 'device-001', workingDirectory: '/repo' },
+ projectId: 'project-1',
+ projectWorkingDirectoryId: 'dir-1',
+ });
+ mockResolveProjectDirectoryForTopic.mockResolvedValueOnce({
+ deviceId: 'device-001',
+ path: '/repo',
+ permission: 'readWrite',
+ platform: 'darwin',
+ });
+ mockMessageCreate.mockClear();
+ mockCreateOperation.mockClear();
+
+ const error: unknown = await service
+ .execAgent({
+ agentId: 'agent-1',
+ prompt: 'Run a command',
+ appContext: { topicId: 'topic-1' },
+ })
+ .catch((thrown) => thrown);
+
+ // Asserted before the message so a post-persistence rejection fails here,
+ // on the divergence itself rather than on the error text.
+ expect(mockMessageCreate).not.toHaveBeenCalled();
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toBe(
+ 'Device is offline or working directory is unavailable',
+ );
+ });
});
describe('gateway not configured', () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index a93b01e1cbe..fb144b7a56e 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -28,7 +28,7 @@ import { resolveModelExtendParamsForUser } from '@/server/modules/AgentRuntime/a
import type { AgentConfigWithId } from '@/server/services/agent';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
-import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';
@@ -626,13 +626,22 @@ export const setupTurn = async (
agentConfig.agencyConfig.boundDeviceId !== directory.deviceId
)
throw new Error('Agent is fixed to another execution target');
- const stat = await deviceGateway.statPath({
- deviceId: directory.deviceId,
- path: directory.path,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- });
- if (!stat?.exists || !stat.isDirectory)
+ // The directory lives on one device, so only that device can honour the
+ // run. Reject an unavailable device *here*, before the user/assistant
+ // rows are persisted: the client treats a rejected send as never
+ // accepted, keeps the draft and rolls back its optimistic pair, so a
+ // later rejection would leave a failed turn durable server-side that the
+ // client disagrees with. Liveness comes from the gateway's device
+ // listing β€” not a device round trip β€” so the send path keeps the latency
+ // fix, and the dispatch remains the authority on whether the directory
+ // still exists on the device.
+ const { canUseDevice: canUseProjectDevice } = resolveDeviceAccessPolicy({ botContext });
+ const projectDevices = canUseProjectDevice
+ ? await getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId)
+ : [];
+ if (
+ !projectDevices.some((device) => device.deviceId === directory.deviceId && device.online)
+ )
throw new Error('Device is offline or working directory is unavailable');
resolvedRequestedDeviceId = directory.deviceId;
effectiveRequestedDeviceId = directory.deviceId;
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 1fd103b089e..169261e5266 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -372,8 +372,8 @@ const ChatInput = memo<ChatInputProps>(
if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0)
return;
- // A rejected directory preflight has no persisted message to recover from.
- // Keep the composer and attachments intact until the target is usable.
+ // A rejected preflight has no persisted message to recover from. Keep
+ // the composer and attachments intact until the target is usable.
const chatState = useChatStore.getState();
const sendContext = storeApi.getState().context;
const topic = sendContext.topicId
@@ -423,7 +423,13 @@ const ChatInput = memo<ChatInputProps>(
files: currentFileList,
message,
onPreflightFailure: () => {
- useFileStore.getState().restoreChatContextSelections(contextKey, currentContextList);
+ const store = useFileStore.getState();
+ // The composer was cleared up front; a send rejected before any
+ // message owned the content must hand every part of it back β€”
+ // uploads and context selections, not just the editor text the
+ // lifecycle restores on its own.
+ store.restoreChatUploadFileList(currentFileList);
+ store.restoreChatContextSelections(contextKey, currentContextList);
},
pageSelections,
});
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.test.ts b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
index 8406dcf2d7f..44e9195a67c 100644
--- a/src/features/Projects/WorkingDirectories/checkExecution.test.ts
+++ b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
@@ -8,26 +8,42 @@ import { checkProjectExecution } from './checkExecution';
afterEach(() => vi.restoreAllMocks());
const topic = { id: 'topic', projectWorkingDirectoryId: 'directory' } as ChatTopic;
+
describe('project send preflight', () => {
it('allows a plain conversation without a gateway', async () => {
await expect(checkProjectExecution(undefined, false)).resolves.toBeUndefined();
});
- it('rejects an unavailable gateway before resolving a device', async () => {
+
+ it('rejects an unavailable gateway before resolving the directory', async () => {
const resolve = vi.spyOn(projectWorkingDirectoryService, 'resolve');
await expect(checkProjectExecution(topic, false)).rejects.toThrow();
expect(resolve).not.toHaveBeenCalled();
});
- it('rejects offline devices and recovers only when the actual directory exists', async () => {
- vi.spyOn(projectWorkingDirectoryService, 'resolve').mockResolvedValue({
+
+ it('rejects a directory that was deleted, unlinked or made read-only while open', async () => {
+ vi.spyOn(projectWorkingDirectoryService, 'resolve').mockRejectedValue(
+ new Error('Project directory not found'),
+ );
+
+ // The composer is cleared only after this resolves, so the rejection is what
+ // keeps the user's text and uploads.
+ await expect(checkProjectExecution(topic, true)).rejects.toThrow('Project directory not found');
+ });
+
+ // Regression: the preflight used to probe the directory with
+ // `deviceService.statPath` on every send β€” a full device round trip (up to its
+ // 8s timeout) that could reject the message when the device was merely slow to
+ // answer. Liveness is the dispatch's to discover; only the DB resolve stays.
+ it('does not probe the device on the send path when the gateway is enabled', async () => {
+ const resolve = vi.spyOn(projectWorkingDirectoryService, 'resolve').mockResolvedValue({
data: { deviceId: 'pinned-device', path: '/project' },
success: true,
} as Awaited<ReturnType<typeof projectWorkingDirectoryService.resolve>>);
- const stat = vi
- .spyOn(deviceService, 'statPath')
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce({ exists: true, isDirectory: true });
- await expect(checkProjectExecution(topic, true)).rejects.toThrow();
- await expect(checkProjectExecution(topic, true)).resolves.toBeUndefined();
- expect(stat).toHaveBeenLastCalledWith('pinned-device', '/project');
+ const stat = vi.spyOn(deviceService, 'statPath');
+
+ await checkProjectExecution(topic, true);
+
+ expect(resolve).toHaveBeenCalledWith('directory');
+ expect(stat).not.toHaveBeenCalled();
});
});
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.ts b/src/features/Projects/WorkingDirectories/checkExecution.ts
index 0e2507d17c4..6b3d92f165a 100644
--- a/src/features/Projects/WorkingDirectories/checkExecution.ts
+++ b/src/features/Projects/WorkingDirectories/checkExecution.ts
@@ -1,17 +1,24 @@
import type { ChatTopic } from '@lobechat/types';
import { t } from 'i18next';
-import { deviceService } from '@/services/device';
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
-/** UI preflight only; the runtime revalidates the binding before every execution. */
+/**
+ * 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.
+ */
export async function checkProjectExecution(topic: ChatTopic | undefined, gatewayEnabled: boolean) {
if (!topic?.projectWorkingDirectoryId) return;
if (!gatewayEnabled) throw new Error(t('topics.gatewayUnavailable', { ns: 'project' }));
- const { data: directory } = await projectWorkingDirectoryService.resolve(
- topic.projectWorkingDirectoryId,
- );
- const stat = await deviceService.statPath(directory.deviceId, directory.path);
- if (!stat?.exists || !stat.isDirectory)
- throw new Error(t('settings.directoryUnavailable', { ns: 'project' }));
+ // Throws for a missing, disabled or read-only directory.
+ 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 1acb7dd364e..3a459166dd1 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -508,6 +508,49 @@ describe('ConversationLifecycle actions', () => {
expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeTruthy();
});
+ it('should fire onPreflightFailure when a gateway send is refused before acceptance', async () => {
+ // Regression: the composer is cleared (text, uploads, context
+ // selections) the instant Enter is pressed. A gateway send the server
+ // refuses before persisting anything β€” e.g. a project-directory topic
+ // whose bound device is offline, rejected in turn setup β€” restored
+ // only the editor text via `restoreComposerAfterFailedSend`, so the
+ // cleared attachments and selections vanished. The lifecycle must
+ // also fire `onPreflightFailure`, the callback the composer uses to
+ // restore them.
+ const { result } = renderHook(() => useChatStore());
+ const onPreflightFailure = vi.fn();
+ const executeGatewayAgentSpy = vi
+ .fn()
+ .mockRejectedValue(
+ new TRPCClientError('Device is offline or working directory is unavailable'),
+ );
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ mainInputEditor: {
+ getJSONState: vi.fn().mockReturnValue({ root: { children: [], type: 'root' } }),
+ setDocument: vi.fn(),
+ setJSONState: vi.fn(),
+ } as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ message: 'Send to an offline device',
+ onPreflightFailure,
+ });
+ });
+
+ // Prove the gateway branch actually ran and failed β€” otherwise a
+ // silent early bail would satisfy the assertion below by accident.
+ expect(executeGatewayAgentSpy).toHaveBeenCalled();
+ expect(onPreflightFailure).toHaveBeenCalledOnce();
+ });
+
it.each(['unchanged', 'edited', 'cleared'] as const)(
'preserves the %s live draft when a cancelled first send rolls back asynchronously',
async (change) => {
@@ -587,6 +630,7 @@ describe('ConversationLifecycle actions', () => {
it('should not restore the composer when gateway setup fails after message acceptance', async () => {
const { result } = renderHook(() => useChatStore());
+ const onPreflightFailure = vi.fn();
const setDocument = vi.fn();
const setJSONState = vi.fn();
const executeGatewayAgentSpy = vi.fn().mockImplementation(async (params) => {
@@ -610,6 +654,7 @@ describe('ConversationLifecycle actions', () => {
await result.current.sendMessage({
context: createTestContext(),
message: 'Already persisted',
+ onPreflightFailure,
});
});
@@ -619,6 +664,9 @@ describe('ConversationLifecycle actions', () => {
expect(executeGatewayAgentSpy).toHaveBeenCalledOnce();
expect(setDocument).not.toHaveBeenCalled();
expect(setJSONState).not.toHaveBeenCalled();
+ // The message was accepted, so nothing the composer cleared is
+ // orphaned β€” restoring it would duplicate the persisted turn's data.
+ expect(onPreflightFailure).not.toHaveBeenCalled();
expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeUndefined();
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index afcd1d498ed..ca3082f5d65 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -988,6 +988,12 @@ export class ConversationLifecycleActionImpl {
} else {
targetInputEditor?.setDocument('markdown', message);
}
+
+ // The editor snapshot covers only text. A send rejected after the composer
+ // was cleared (e.g. the server refusing an offline bound device) would
+ // otherwise still swallow the cleared uploads and context selections β€”
+ // hand them back to the caller that captured them before clearing.
+ onPreflightFailure?.();
};
const restoreUnacceptedVoiceMessageContext = () => {
if (!optimisticUserMessageId || hasNotifiedMessageAccepted) return;
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index 4cf80fc25af..fd7f1d98a20 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -219,6 +219,26 @@ describe('useFileStore:chat', () => {
expect(result.current.chatUploadFileList).toEqual([newerFile]);
});
+ it('restoreChatUploadFileList puts cleared uploads back without duplicating newer drafts', () => {
+ const { result } = renderHook(() => useStore());
+ const submittedFile = { id: 'submitted', status: 'success' };
+ const newerFile = { id: 'new', status: 'uploading' };
+
+ // The composer cleared everything on send; a fresh draft arrived while the
+ // rejected send was still unwinding.
+ act(() => {
+ useStore.setState({ chatUploadFileList: [newerFile] as any });
+ result.current.restoreChatUploadFileList([submittedFile, newerFile] as any);
+ });
+
+ expect(result.current.chatUploadFileList).toEqual([newerFile, submittedFile]);
+
+ act(() => {
+ result.current.restoreChatUploadFileList([]);
+ });
+ expect(result.current.chatUploadFileList).toEqual([newerFile, submittedFile]);
+ });
+
it('uploadChatFiles should reject unsupported files before upload in chat mode', async () => {
// chat mode: agent mode disabled and not a heterogeneous agent
mockAgentMode({ enableAgentMode: false, heterogeneous: false });
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index 6214160e59e..62f26a7df53 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -126,6 +126,22 @@ export class FileActionImpl {
this.#set({ chatUploadFileList }, false, n('clearChatUploadFileList'));
};
+ /**
+ * Put captured upload items back into the composer list after a send was
+ * rejected before any message owned them (e.g. the server refused the turn
+ * up front). Items already in the list are skipped by id so a concurrent
+ * draft does not end up with duplicates.
+ */
+ restoreChatUploadFileList = (files: UploadFileItem[]): void => {
+ if (files.length === 0) return;
+
+ const currentIds = new Set(this.#get().chatUploadFileList.map((file) => file.id));
+ const restored = files.filter((file) => !currentIds.has(file.id));
+ if (restored.length === 0) return;
+
+ this.#get().dispatchChatUploadFileList({ files: restored, type: 'addFiles' });
+ };
+
dispatchChatUploadFileList = (payload: UploadFileListDispatch): void => {
const nextValue = uploadFileListReducer(this.#get().chatUploadFileList, payload);
if (nextValue === this.#get().chatUploadFileList) return;