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.

🐛 fix(project): run a project topic in its project directory instead of the agent default (#21079)

Arvin Xu9ee393a94060
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
new file mode 100644
index 00000000000..9d25aff9763
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
@@ -0,0 +1,233 @@
+import type * as LobechatConstModule from '@lobechat/const';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
+import { type ProjectDirectory, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { createMockAgentConfig, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+const mockConstEnv = vi.hoisted(() => ({ isDesktop: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<typeof LobechatConstModule>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockConstEnv.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/services/resourcePermission', () => ({
+ resourcePermissionService: { getGeneralAccess: vi.fn() },
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },
+ },
+}));
+
+const DEVICE_ID = 'device-85';
+const PROJECT_PATH = '/repo/project';
+const AGENT_DEFAULT_PATH = '/repo/agent-default';
+
+const directoryRow = {
+ deviceId: DEVICE_ID,
+ environmentId: 'env-85',
+ id: 'dir-85',
+ instanceId: 'inst-85',
+ path: PROJECT_PATH,
+ projectId: 'prj-1',
+} as ProjectDirectory;
+
+beforeEach(() => {
+ resetTestEnvironment();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ useUserStore.setState({ workspaceUserPreference: {} });
+ useProjectDirectoryStore.setState({ directoriesMap: { all: [directoryRow] } });
+
+ act(() => {
+ useChatStore.setState({
+ executeClientAgent: vi.fn(),
+ mainInputEditor: null,
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+});
+
+afterEach(() => {
+ mockConstEnv.isDesktop = false;
+ setPendingTopicRepos(TEST_IDS.SESSION_ID, []);
+ useProjectDirectoryStore.setState({ directoriesMap: {} });
+ vi.restoreAllMocks();
+});
+
+describe('sendMessage in a project directory', () => {
+ // Regression: the new topic's optimistic metadata took the agent's own
+ // per-device directory, and the send-time git snapshot wrote that config back
+ // over the server's project binding — the composer then showed another repo's
+ // branch, and the next turn was refused for a mismatched directory.
+ it('seeds the new topic with the project directory, not the agent default', async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: DEVICE_ID,
+ executionTarget: 'device',
+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
+ },
+ },
+ });
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
+ const agentId = TEST_IDS.SESSION_ID;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ pendingNewTopicDirectory: { agentId, projectWorkingDirectoryId: 'dir-85' },
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Start in the project',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ optimisticTopic: expect.objectContaining({
+ metadata: expect.objectContaining({
+ workingDirectory: PROJECT_PATH,
+ workingDirectoryConfig: { path: PROJECT_PATH },
+ }),
+ }),
+ projectWorkingDirectoryId: 'dir-85',
+ }),
+ );
+ });
+
+ // A cloud repo picked in the composer before the project "+" would otherwise
+ // win both metadata paths, binding the topic to one directory but starting it
+ // in another.
+ it('lets the staged project directory win over a pending cloud repo pick', async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: { agencyConfig: { boundDeviceId: DEVICE_ID, executionTarget: 'device' } },
+ });
+ const agentId = TEST_IDS.SESSION_ID;
+ setPendingTopicRepos(agentId, ['lobehub/cloud-repo']);
+ let pendingAtDispatch: string[] | undefined;
+ const executeGatewayAgentSpy = vi.fn().mockImplementation(async () => {
+ pendingAtDispatch = getPendingTopicRepos(agentId);
+ return { topicId: 'tpc_new' };
+ });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ pendingNewTopicDirectory: { agentId, projectWorkingDirectoryId: 'dir-85' },
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Start in the project',
+ });
+ });
+
+ const params = executeGatewayAgentSpy.mock.calls[0][0];
+ expect(params.projectWorkingDirectoryId).toBe('dir-85');
+ expect(params.optimisticTopic.metadata).not.toHaveProperty('repos');
+ expect(params.optimisticTopic.metadata).toEqual(
+ expect.objectContaining({ workingDirectoryConfig: { path: PROJECT_PATH } }),
+ );
+ expect(pendingAtDispatch).toEqual([]);
+ });
+
+ // `/newTopic` from a project topic creates a topic outside the project, so it
+ // must not inherit the directory it was sent from.
+ it('keeps a /newTopic sent from a project topic on the agent default', async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: DEVICE_ID,
+ executionTarget: 'device',
+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
+ },
+ },
+ });
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
+ const agentId = TEST_IDS.SESSION_ID;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ topicDetailMap: {
+ tpc_bound: {
+ createdAt: Date.now(),
+ id: 'tpc_bound',
+ projectWorkingDirectoryId: 'dir-85',
+ title: 'Bound',
+ updatedAt: Date.now(),
+ } as any,
+ },
+ });
+ });
+
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ { actionCategory: 'command', actionType: 'newTopic', type: 'action-tag' },
+ { text: ' Start fresh', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: 'tpc_bound' },
+ editorData,
+ message: 'Start fresh',
+ });
+ });
+
+ const params = executeGatewayAgentSpy.mock.calls[0][0];
+ expect(params.projectWorkingDirectoryId).toBeUndefined();
+ expect(params.optimisticTopic.metadata).toEqual(
+ expect.objectContaining({
+ workingDirectory: AGENT_DEFAULT_PATH,
+ workingDirectoryConfig: { path: AGENT_DEFAULT_PATH },
+ }),
+ );
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 7bb3203ec22..f147a9f2cdf 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -66,7 +66,7 @@ import {
} from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';
-import { getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
+import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import {
dbMessageSelectors,
displayMessageSelectors,
@@ -511,7 +511,7 @@ export class ConversationLifecycleActionImpl {
? pendingDirectory.projectWorkingDirectoryId
: undefined;
const projectDirectoryId = boundTopic?.projectWorkingDirectoryId ?? stagedDirectoryId;
- let stagedDirectory: { id: string; projectId: string } | undefined;
+ let stagedDirectory: { id: string; path: string; projectId: string } | undefined;
if (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
@@ -521,6 +521,7 @@ export class ConversationLifecycleActionImpl {
findProjectDirectory(projectDirectoryId) ??
(await projectWorkingDirectoryService.resolve(projectDirectoryId)).data;
if (stagedDirectoryId) stagedDirectory = directory;
+ if (stagedDirectory) consumePendingTopicRepos(ownerAgentId); // a cloud repo pick conflicts
if (!isGatewayMode)
throw new Error('Enable Gateway Mode to run in a project working directory');
if (
@@ -1286,15 +1287,14 @@ export class ConversationLifecycleActionImpl {
deviceSelectors.getDeviceDefaultCwd(runCwdDeviceId)(getDeviceStoreState()),
fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,
legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
+ // A project's staged directory, not the agent default, is the new topic's cwd.
+ topicWorkingDirectory: stagedDirectory?.path,
workspaceScoped,
}
: undefined;
- const agentWorkingDirectory = runCwdParams
- ? resolveAgentWorkingDirectory(runCwdParams)
- : undefined;
- const agentWorkingDirectoryConfig = runCwdParams
- ? resolveAgentWorkingDirectoryConfig(runCwdParams)
- : undefined;
+ const agentWorkingDirectory = runCwdParams && resolveAgentWorkingDirectory(runCwdParams);
+ const agentWorkingDirectoryConfig =
+ runCwdParams && resolveAgentWorkingDirectoryConfig(runCwdParams);
// Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd
// (`~/.claude/projects/<encoded-cwd>/`). Anchor their session cwd to the
// SOURCE repo, NOT the selected worktree, so switching worktree keeps cwd +