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(chat): bind a new topic to the directory its run executes in (#18453)

Arvin Xu6371604f915e
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
new file mode 100644
index 00000000000..434947e6c5e
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
@@ -0,0 +1,308 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+/**
+ * A device-bound run resolves its working directory server-side (for
+ * `{{workingDirectory}}`, the tool cwd, and the workspace scan) β€” but the topic
+ * it creates has to be PINNED to that directory too, otherwise By-Project files
+ * the conversation under "No directory" and every later turn silently re-resolves
+ * the agent-level default.
+ *
+ * This used to happen only inside the heterogeneous device-dispatch branch, so a
+ * native agent bound to the very same device left its topics unbound.
+ */
+const {
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockFindByDeviceId,
+ mockGenerateToolsDetailed,
+ mockGetAgentConfig,
+ mockGetEnabledPluginManifests,
+ mockInitWorkspace,
+ mockMessageCreate,
+ mockPluginQuery,
+ mockQueryDeviceList,
+ mockTopicFindById,
+ mockUpdateDevice,
+ mockUpdateTopicMetadata,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn(),
+ mockFindByDeviceId: vi.fn(),
+ mockGenerateToolsDetailed: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetEnabledPluginManifests: vi.fn(),
+ mockInitWorkspace: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockPluginQuery: vi.fn(),
+ mockQueryDeviceList: vi.fn(),
+ mockTopicFindById: vi.fn(),
+ mockUpdateDevice: vi.fn(),
+ mockUpdateTopicMetadata: vi.fn(),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(() => ({
+ findByDeviceId: mockFindByDeviceId,
+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),
+ queryPersonal: vi.fn().mockResolvedValue([]),
+ queryWorkspaceDevices: vi.fn().mockResolvedValue([]),
+ queryWorkspaceHiddenDeviceIds: vi.fn().mockResolvedValue([]),
+ update: mockUpdateDevice,
+ })),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({
+ getAgentConfig: mockGetAgentConfig,
+ })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({
+ query: mockPluginQuery,
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ findById: mockTopicFindById,
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ updateMetadata: mockUpdateTopicMetadata,
+ })),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ createOperation: mockCreateOperation,
+ })),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(() => ({
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ uploadFromUrl: vi.fn(),
+ })),
+}));
+
+vi.mock('@/server/modules/Mecha', () => {
+ mockGenerateToolsDetailed.mockReturnValue({ enabledToolIds: [], tools: [] });
+ mockGetEnabledPluginManifests.mockReturnValue(new Map());
+ mockCreateServerAgentToolsEngine.mockReturnValue({
+ generateToolsDetailed: mockGenerateToolsDetailed,
+ getEnabledPluginManifests: mockGetEnabledPluginManifests,
+ });
+
+ return {
+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+ };
+});
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ initWorkspace: mockInitWorkspace,
+ get isConfigured() {
+ return true;
+ },
+ queryDeviceList: mockQueryDeviceList,
+ queryDeviceSystemInfo: vi.fn().mockResolvedValue(null),
+ },
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+const DEVICE_ID = 'dev-1';
+const SOURCE_PATH = '/repo/lobehub';
+const WORKTREE_PATH = '/repo/lobehub/.worktrees/feat';
+
+const createAgentConfig = (agencyConfig: Record<string, any>) => ({
+ agencyConfig,
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+});
+
+describe('AiAgentService.execAgent - topic working directory binding', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+ const userId = 'test-user-id';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockPluginQuery.mockResolvedValue([]);
+ mockGenerateToolsDetailed.mockReturnValue({ enabledToolIds: [], tools: [] });
+ mockGetEnabledPluginManifests.mockReturnValue(new Map());
+ mockQueryDeviceList.mockResolvedValue([
+ { deviceId: DEVICE_ID, hostname: 'My Mac', online: true, platform: 'darwin' },
+ ]);
+ mockFindByDeviceId.mockResolvedValue({ deviceId: DEVICE_ID, workingDirs: [] });
+ mockTopicFindById.mockResolvedValue(null);
+ mockInitWorkspace.mockResolvedValue({ instructions: [], skills: [] });
+ mockUpdateDevice.mockResolvedValue(undefined);
+ mockUpdateTopicMetadata.mockResolvedValue(undefined);
+
+ service = new AiAgentService(mockDb, userId);
+ });
+
+ it('binds a new topic to the agent per-device working directory', async () => {
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({
+ boundDeviceId: DEVICE_ID,
+ executionTarget: 'device',
+ workingDirByDevice: {
+ [DEVICE_ID]: {
+ git: { activeWorktree: WORKTREE_PATH },
+ path: SOURCE_PATH,
+ repoType: 'github',
+ },
+ },
+ }),
+ );
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+
+ // `workingDirectory` is the EFFECTIVE path the run executes in; the config
+ // keeps the SOURCE repo, which is what By-Project groups on.
+ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ workingDirectory: WORKTREE_PATH,
+ workingDirectoryConfig: {
+ git: { activeWorktree: WORKTREE_PATH },
+ path: SOURCE_PATH,
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('falls back to the bound device default cwd', async () => {
+ mockFindByDeviceId.mockResolvedValue({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: [],
+ });
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+
+ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ workingDirectory: '/repo/default',
+ workingDirectoryConfig: { path: '/repo/default' },
+ });
+ });
+
+ it('never rewrites a topic that is already pinned to a directory', async () => {
+ // The historical pin is the contract: an old conversation must not follow
+ // the agent's current default when that default changes later.
+ mockTopicFindById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: {
+ workingDirectory: '/repo/other',
+ workingDirectoryConfig: { path: '/repo/other' },
+ },
+ });
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({
+ boundDeviceId: DEVICE_ID,
+ executionTarget: 'device',
+ workingDirByDevice: { [DEVICE_ID]: { path: SOURCE_PATH } },
+ }),
+ );
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Hello',
+ });
+
+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ workingDirectory: expect.anything() }),
+ );
+ });
+
+ it('leaves the topic unbound when neither the agent nor the device has a directory', async () => {
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+
+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ workingDirectory: expect.anything() }),
+ );
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 7ee91e546af..a543b87fa1a 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -76,6 +76,7 @@ import type {
ScheduleAgentRunParams,
ScheduleAgentRunResult,
UserInterventionConfig,
+ WorkingDirConfig,
WorkspaceInitResult,
} from '@lobechat/types';
import {
@@ -197,10 +198,7 @@ import {
} from './deviceToolRegistry';
import { ingestAttachment } from './ingestAttachment';
import { pruneRegeneratedBranch } from './pruneRegeneratedBranch';
-import {
- resolveDeviceWorkingDirectory,
- resolveDeviceWorkingDirectoryConfig,
-} from './resolveDeviceWorkingDirectory';
+import { resolveDeviceWorkingDirectoryConfig } from './resolveDeviceWorkingDirectory';
import { resolveServerSearchDecision } from './searchDecision';
import { acquireTopicStartReservation } from './topicStartReservation';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache';
@@ -562,6 +560,18 @@ interface InternalExecAgentParams extends ExecAgentParams {
*/
interface ResolvedWorkspaceInit {
boundCwd?: string;
+ /**
+ * The full config behind {@link boundCwd} (source path + repoType + the
+ * active worktree). Callers persist THIS onto the topic, not the flat path:
+ * project grouping keys off `config.path` (the source repo), so a run inside
+ * a linked worktree must still file under its repo.
+ */
+ boundCwdConfig?: WorkingDirConfig;
+ /**
+ * The cwd the topic was ALREADY pinned to, so a caller can tell a first-time
+ * binding from a no-op rewrite without re-reading the topic row.
+ */
+ topicWorkingDirectory?: string;
workspace: WorkspaceInitResult;
}
@@ -871,14 +881,17 @@ export class AiAgentService {
// caller so the system prompt's {{workingDirectory}} reflects the same
// bound directory the workspace scan used.
const topic = await this.topicModel.findById(topicId);
- const boundCwd = resolveDeviceWorkingDirectory({
+ const topicWorkingDirectory = topic?.metadata?.workingDirectory;
+ const boundCwdConfig = resolveDeviceWorkingDirectoryConfig({
deviceDefaultCwd: device.defaultCwd,
deviceId: activeDeviceId,
- topicWorkingDirectory: topic?.metadata?.workingDirectory,
+ topicWorkingDirectory,
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
workingDirByDevice: agencyConfig?.workingDirByDevice,
});
+ const boundCwd = getWorkingDirEffectivePath(boundCwdConfig);
if (!boundCwd) return { workspace: empty };
+ const resolved = { boundCwd, boundCwdConfig, topicWorkingDirectory };
const workingDirs = device.workingDirs ?? [];
const cached = workingDirs.find(
@@ -887,7 +900,7 @@ export class AiAgentService {
if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {
log('execAgent: reusing cached workspace init for %s', boundCwd);
- return { boundCwd, workspace: cached.workspace };
+ return { ...resolved, workspace: cached.workspace };
}
const scanned = await deviceGateway.initWorkspace({
@@ -901,9 +914,9 @@ export class AiAgentService {
// cache rather than dropping the project's skills + instructions.
if (cached?.workspace) {
log('execAgent: workspace init scan failed, using stale cache for %s', boundCwd);
- return { boundCwd, workspace: cached.workspace };
+ return { ...resolved, workspace: cached.workspace };
}
- return { boundCwd, workspace: empty };
+ return { ...resolved, workspace: empty };
}
// Persist the fresh scan back onto `workingDirs` (update in place or prepend
@@ -930,13 +943,51 @@ export class AiAgentService {
}
log('execAgent: scanned and cached workspace init for %s', boundCwd);
- return { boundCwd, workspace: scanned };
+ return { ...resolved, workspace: scanned };
} catch (error) {
log('execAgent: resolveWorkspaceInit failed: %O', error);
return { workspace: empty };
}
}
+ /**
+ * Pin a topic to the directory its run actually executes in.
+ *
+ * A topic created by a device-bound run starts with no cwd of its own: the
+ * directory was only ever recorded at agent level
+ * (`agencyConfig.workingDirByDevice`) or on the device (`defaultCwd`). Without
+ * this write the topic stays unbound β€” By-Project grouping files it under "No
+ * directory", and every later turn re-resolves from the agent config, so
+ * changing the agent's directory silently moves an old conversation to a new
+ * project (and makes hetero `--resume` unsafe).
+ *
+ * Shared by BOTH execution paths β€” hetero device dispatch and the normal
+ * agent runtime β€” so a native agent bound to a device gets the same binding a
+ * CLI agent does. Purely additive: a topic that already carries a cwd (the
+ * client resolved one and sent it as `initialTopicMetadata`, or an earlier
+ * turn bound it) is never rewritten, so the historical pin always wins.
+ */
+ private async bindTopicWorkingDirectory(params: {
+ config?: WorkingDirConfig;
+ currentWorkingDirectory?: string;
+ topicId: string;
+ }): Promise<void> {
+ const { config, currentWorkingDirectory, topicId } = params;
+ if (currentWorkingDirectory || !config) return;
+ const path = getWorkingDirEffectivePath(config);
+ if (!path) return;
+
+ try {
+ await this.topicModel.updateMetadata(topicId, {
+ workingDirectory: path,
+ workingDirectoryConfig: config,
+ });
+ } catch (err) {
+ // Metadata bookkeeping must never fail a run that is otherwise fine.
+ log('execAgent: bindTopicWorkingDirectory failed (non-fatal): %O', err);
+ }
+ }
+
/**
* Execute a single agent step against this service's runtime.
*
@@ -1943,7 +1994,6 @@ export class AiAgentService {
// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existing
let topicId = appContext?.topicId;
- const isNewTopic = !topicId;
const isFixedExecutionTargetSelection =
!!this.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
const isFixedDeviceTarget =
@@ -2817,16 +2867,15 @@ export class AiAgentService {
});
const deviceCwd = getWorkingDirEffectivePath(deviceCwdConfig);
- // A brand-new topic has no pinned cwd yet: the directory was only
+ // An unbound topic has no pinned cwd yet: the directory was only
// recorded at agent level (`workingDirByDevice`) when no topic existed.
// Persist the resolved cwd onto the topic so the sidebar groups it
// under the right project and the next turn reuses the same directory.
- if (isNewTopic && deviceCwd && deviceCwd !== topic?.metadata?.workingDirectory) {
- await this.topicModel.updateMetadata(topicId, {
- workingDirectory: deviceCwd,
- ...(deviceCwdConfig ? { workingDirectoryConfig: deviceCwdConfig } : {}),
- });
- }
+ await this.bindTopicWorkingDirectory({
+ config: deviceCwdConfig,
+ currentWorkingDirectory: topic?.metadata?.workingDirectory,
+ topicId,
+ });
// Build only device-relevant context instead of reusing the cloud-sandbox one
// (which describes an ephemeral /workspace + pre-cloned repos and would mislead
@@ -4493,6 +4542,41 @@ export class AiAgentService {
Object.keys(toolManifestMap).length,
);
+ // Project skills + the root AGENTS.md are discovered server-side by
+ // scanning the device's bound project directory ("workspace init"), cached
+ // on `devices.workingDirs` and reused within the TTL. Skills surface in
+ // `<available_skills>` (metadata only β€” SKILL.md bodies are read lazily at
+ // activation via `local-system` readFile, which `serverRuntimes/skills.ts`
+ // re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md
+ // path) flows through; the directory tree is enumerated lazily, keeping the
+ // op-param payload small.
+ const workspaceInit = await this.resolveWorkspaceInit({
+ activeDeviceId,
+ agencyConfig: agentConfig.agencyConfig ?? undefined,
+ topicId,
+ });
+
+ // Feed the bound directory (resolved from the persisted device row) into
+ // the local-system tool's {{workingDirectory}} placeholder β€” the channel
+ // the model uses to know where it is and reach for absolute paths β€” and,
+ // downstream, the runCommand cwd / search scope (RuntimeExecutors reads
+ // state.metadata.deviceSystemInfo.workingDirectory). Resume-safe via the
+ // existing deviceSystemInfo plumbing (computeDeviceContext).
+ if (workspaceInit.boundCwd) {
+ deviceSystemInfo.workingDirectory = workspaceInit.boundCwd;
+ }
+
+ // Bind the topic to that very directory. A native (non-hetero) agent
+ // routed to a device used to resolve its cwd here for the prompt and the
+ // tools, but never write it back β€” so its topics stayed unbound while the
+ // run itself executed in the right place. Awaited (not fire-and-forget):
+ // the tool layer reads the topic's cwd on the same run.
+ await this.bindTopicWorkingDirectory({
+ config: workspaceInit.boundCwdConfig,
+ currentWorkingDirectory: workspaceInit.topicWorkingDirectory,
+ topicId,
+ });
+
// 18. Build OperationSkillSet via SkillEngine
// Combines builtin skills + user DB skills + agent-document skill bundles,
// filters by platform via enableChecker, and pairs with agent's enabled
@@ -4559,30 +4643,6 @@ export class AiAgentService {
name: skill.name,
}));
- // Project skills + the root AGENTS.md are discovered server-side by
- // scanning the device's bound project directory ("workspace init"), cached
- // on `devices.workingDirs` and reused within the TTL. Skills surface in
- // `<available_skills>` (metadata only β€” SKILL.md bodies are read lazily at
- // activation via `local-system` readFile, which `serverRuntimes/skills.ts`
- // re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md
- // path) flows through; the directory tree is enumerated lazily, keeping the
- // op-param payload small.
- const workspaceInit = await this.resolveWorkspaceInit({
- activeDeviceId,
- agencyConfig: agentConfig.agencyConfig ?? undefined,
- topicId,
- });
-
- // Feed the bound directory (resolved from the persisted device row) into
- // the local-system tool's {{workingDirectory}} placeholder β€” the channel
- // the model uses to know where it is and reach for absolute paths β€” and,
- // downstream, the runCommand cwd / search scope (RuntimeExecutors reads
- // state.metadata.deviceSystemInfo.workingDirectory). Resume-safe via the
- // existing deviceSystemInfo plumbing (computeDeviceContext).
- if (workspaceInit.boundCwd) {
- deviceSystemInfo.workingDirectory = workspaceInit.boundCwd;
- }
-
const projectMetas = workspaceInit.workspace.skills.map((s) => ({
description: s.description ?? '',
identifier: `${s.scope === 'device' ? 'device' : 'project'}:${s.name}`,
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 c2a226b798b..498dab24df2 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -19,6 +19,7 @@ import type {
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
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 { getSessionStoreState } from '@/store/session';
import * as toolStoreModule from '@/store/tool';
@@ -92,6 +93,11 @@ afterEach(() => {
executeHeterogeneousAgentMock.mockReset();
mockConstEnv.isDesktop = false;
setPendingTopicRepos(TEST_IDS.SESSION_ID, []);
+ // Zustand state and the window-backed agent context survive `restoreAllMocks`,
+ // so a cwd test that seeds a device (or a desktop path) would otherwise leak
+ // a working directory into every later send in this file.
+ useDeviceStore.setState({ devices: [] });
+ delete window.__LOBE_GLOBAL_AGENT_CONTEXT__;
vi.restoreAllMocks();
});
@@ -1730,6 +1736,381 @@ describe('ConversationLifecycle actions', () => {
});
});
+ // A native (non-hetero) agent bound to a device resolves its cwd for the
+ // run (tools, {{workingDirectory}}) but used to leave the new topic
+ // unbound β€” By Project filed every such conversation under "No directory",
+ // and later turns re-resolved the agent-level default, so changing the
+ // agent's directory silently moved old topics to another project.
+ it('should bind a new gateway topic to a native agent device working directory', async () => {
+ mockConstEnv.isDesktop = true;
+ const deviceId = 'device-1';
+ const sourcePath = '/repo/lobehub';
+ const worktreePath = '/repo/lobehub/.worktrees/feat';
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: deviceId,
+ executionTarget: 'local',
+ workingDirByDevice: {
+ [deviceId]: {
+ git: { activeWorktree: worktreePath },
+ path: sourcePath,
+ repoType: 'github',
+ },
+ },
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const topicKey = topicMapKey({ agentId });
+ let resolveGateway!: () => void;
+ const gatewayPromise = new Promise<any>((resolve) => {
+ resolveGateway = () =>
+ resolve({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'gateway-op-cwd',
+ topicId: TEST_IDS.NEW_TOPIC_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+ });
+ const executeGatewayAgentSpy = vi.fn().mockReturnValue(gatewayPromise);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ topicDataMap: {
+ [topicKey]: {
+ currentPage: 0,
+ hasMore: false,
+ isExpandingPageSize: false,
+ isLoadingMore: false,
+ items: [],
+ pageSize: 20,
+ total: 0,
+ },
+ },
+ });
+ });
+
+ let sendPromise!: ReturnType<typeof result.current.sendMessage>;
+ act(() => {
+ sendPromise = result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Bind me to the project',
+ });
+ });
+
+ await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalled());
+
+ // `workingDirectory` is the EFFECTIVE path (the checked-out worktree the
+ // run executes in); the config keeps the SOURCE repo, which is what
+ // By-Project groups on.
+ const expectedMetadata = {
+ workingDirectory: worktreePath,
+ workingDirectoryConfig: {
+ git: { activeWorktree: worktreePath },
+ path: sourcePath,
+ repoType: 'github',
+ },
+ };
+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]).toEqual(
+ expect.objectContaining({ metadata: expectedMetadata }),
+ );
+ // Rides along to the server, which owns the real topic row.
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ optimisticTopic: expect.objectContaining({ metadata: expectedMetadata }),
+ }),
+ );
+
+ await act(async () => {
+ resolveGateway();
+ await sendPromise;
+ });
+ });
+
+ it('should fall back to the bound device default cwd when the agent has no pick', async () => {
+ mockConstEnv.isDesktop = true;
+ const deviceId = 'device-1';
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: { boundDeviceId: deviceId, executionTarget: 'device' },
+ },
+ });
+ act(() => {
+ useDeviceStore.setState({
+ devices: [{ defaultCwd: '/repo/default', deviceId, name: 'Mac' }] as any,
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'gateway-op-default-cwd',
+ topicId: TEST_IDS.NEW_TOPIC_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Use the device default',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ optimisticTopic: expect.objectContaining({
+ metadata: {
+ workingDirectory: '/repo/default',
+ workingDirectoryConfig: { path: '/repo/default' },
+ },
+ }),
+ }),
+ );
+ });
+
+ // Client mode creates the topic itself (`sendMessageInServer`), so nothing
+ // downstream would ever write the cwd back β€” the metadata has to ride on
+ // the create call.
+ it('should bind a client-runtime new topic to the resolved working directory', async () => {
+ mockConstEnv.isDesktop = true;
+ const deviceId = 'device-1';
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: deviceId,
+ executionTarget: 'local',
+ workingDirByDevice: { [deviceId]: { path: '/repo/lobehub' } },
+ },
+ },
+ });
+
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topicId: TEST_IDS.NEW_TOPIC_ID,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ const { result } = renderHook(() => useChatStore());
+ act(() => {
+ useChatStore.setState({ isGatewayModeEnabled: () => false });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: null },
+ message: 'Bind me too',
+ });
+ });
+
+ expect(sendMessageInServerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ newTopic: expect.objectContaining({
+ metadata: {
+ workingDirectory: '/repo/lobehub',
+ workingDirectoryConfig: { path: '/repo/lobehub' },
+ },
+ }),
+ }),
+ expect.any(AbortController),
+ );
+ });
+
+ it('should leave a plain-chat agent topic unbound', async () => {
+ mockConstEnv.isDesktop = true;
+ const deviceId = 'device-1';
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: deviceId,
+ executionTarget: 'local',
+ workingDirByDevice: { [deviceId]: { path: '/repo/lobehub' } },
+ },
+ // No execution environment at all β€” a directory would be noise, and
+ // By Project would file plain chats under a project they never used.
+ chatConfig: { ...createMockAgentConfig().chatConfig, enableAgentMode: false },
+ },
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'gateway-op-chat',
+ topicId: TEST_IDS.NEW_TOPIC_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Just chatting',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ optimisticTopic: expect.not.objectContaining({ metadata: expect.anything() }),
+ }),
+ );
+ });
+
+ // The device `defaultCwd` level was added to the SEND path by the same
+ // change that started binding native topics, and it sits BETWEEN the
+ // legacy per-agent slot and the desktop/home fallback. A local
+ // heterogeneous CLI keys its sessions off the cwd
+ // (`~/.claude/projects/<encoded-cwd>/`), so reordering these levels moves
+ // an agent's whole session bucket and silently drops `--resume` β€” pin the
+ // order for the hetero path, which the native-agent cases above don't
+ // exercise (they never reach the desktop/home fallback at all).
+ describe('heterogeneous cwd precedence', () => {
+ const HETERO_DEVICE_ID = 'device-1';
+ const DESKTOP_PATH = '/Users/me/Desktop';
+
+ const setupHeteroRun = (agencyConfig: Record<string, any> = {}) => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: HETERO_DEVICE_ID,
+ executionTarget: 'local',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ ...agencyConfig,
+ },
+ },
+ });
+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);
+
+ return vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topicId: TEST_IDS.NEW_TOPIC_ID,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ };
+
+ const sendHeteroMessage = async () => {
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ message: TEST_CONTENT.USER_MESSAGE,
+ });
+ });
+ };
+
+ beforeEach(() => {
+ // The desktop/home fallback is always available for a hetero CLI, so
+ // every case below has something to lose to.
+ window.__LOBE_GLOBAL_AGENT_CONTEXT__ = { desktopPath: DESKTOP_PATH };
+ });
+
+ it('prefers the bound device defaultCwd over the desktop fallback', async () => {
+ const sendMessageInServerSpy = setupHeteroRun();
+ act(() => {
+ useDeviceStore.setState({
+ devices: [
+ { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },
+ ] as any,
+ });
+ });
+
+ await sendHeteroMessage();
+
+ // The CLI actually spawns here β€” a regression sends it to ~/Desktop
+ // and the `--resume` session bucket moves with it.
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ workingDirectory: '/repo/device-default',
+ workingDirectoryConfig: { path: '/repo/device-default' },
+ }),
+ );
+ // …and the topic is born pinned to the same directory.
+ expect(sendMessageInServerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ newTopic: expect.objectContaining({
+ metadata: {
+ workingDirectory: '/repo/device-default',
+ workingDirectoryConfig: { path: '/repo/device-default' },
+ },
+ }),
+ }),
+ expect.any(AbortController),
+ );
+ });
+
+ it('keeps the agent per-device pick above the device defaultCwd', async () => {
+ setupHeteroRun({
+ workingDirByDevice: { [HETERO_DEVICE_ID]: { path: '/repo/agent-pick' } },
+ });
+ act(() => {
+ useDeviceStore.setState({
+ devices: [
+ { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },
+ ] as any,
+ });
+ });
+
+ await sendHeteroMessage();
+
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ workingDirectory: '/repo/agent-pick' }),
+ );
+ });
+
+ it('still falls back to the desktop path when neither the agent nor the device has one', async () => {
+ setupHeteroRun();
+
+ await sendHeteroMessage();
+
+ // Inserting the defaultCwd level must not swallow the last resort: a
+ // hetero CLI always spawns somewhere, so an unconfigured agent still
+ // needs a directory (unlike a native one, which stays unbound).
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ workingDirectory: DESKTOP_PATH }),
+ );
+ });
+ });
+
it('should rollback an optimistic topic if the create response resolves without a topic id', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 4def3a43b7e..75dbbf3bc9b 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -31,8 +31,13 @@ import { type ChatInputEditor } from '@/features/ChatInput';
import {
resolveAgentWorkingDirectory,
resolveAgentWorkingDirectoryConfig,
+ resolveTargetDeviceId,
} from '@/helpers/agentWorkingDirectory';
-import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';
+import {
+ resolveExecutionTarget,
+ resolveToolMode,
+ resolveWorkspaceScoped,
+} from '@/helpers/executionTarget';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { agentService } from '@/services/agent';
import { aiAgentService } from '@/services/aiAgent';
@@ -82,6 +87,7 @@ import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+import { deviceSelectors, getDeviceStoreState } from '@/store/device';
import { getElectronStoreState } from '@/store/electron';
import { getFileStoreState } from '@/store/file/store';
import { useGlobalStore } from '@/store/global';
@@ -1009,45 +1015,65 @@ export class ConversationLifecycleActionImpl {
topicId: willCreateNewTopic ? undefined : operationContext.topicId,
});
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
- // Resolve the cwd for every hetero-provider run that lands on a MACHINE
- // (in-process `hetero` runtime, or a gateway dispatch whose effective
- // target routes to a device) β€” the server can only honour a cwd the client
- // resolved (per-user legacy slot included) if it rides along as the new
- // topic's initial metadata. Sandbox/none targets must NOT resolve one: the
- // desktop/home fallback is a local machine path that doesn't exist in an
- // ephemeral cloud sandbox and would pollute the topic's metadata.
- const heteroEffectiveTarget = heterogeneousProvider
- ? resolveExecutionTarget(agencyConfig, {
- clientExecutionAvailable: isDesktop,
- isHetero: true,
- workspaceScoped,
- })
+ // Resolve the cwd for every run that lands on a MACHINE β€” a hetero CLI
+ // (in-process `hetero` runtime) and a NATIVE agent alike, as long as the
+ // effective target routes to a device. The server can only honour a cwd the
+ // client resolved (per-user legacy slot included) if it rides along as the
+ // new topic's initial metadata, and a topic that is born unbound renders
+ // under "No directory" while every later turn re-resolves the agent-level
+ // default. Sandbox/none targets must NOT resolve one: the desktop/home
+ // fallback is a local machine path that doesn't exist in an ephemeral cloud
+ // sandbox and would pollute the topic's metadata. Plain-chat agents have no
+ // execution environment at all, so they stay unbound too.
+ const isHeteroRun = !!heterogeneousProvider;
+ const runEffectiveTarget =
+ isHeteroRun || resolveToolMode(agentConfig?.chatConfig) !== 'chat'
+ ? resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ // A web client can't run tools in-process, but its backend may still
+ // route a bound `local` target to the user's machine β€” where the cwd
+ // does apply.
+ deviceRoutingAvailable: isGatewayMode,
+ isHetero: isHeteroRun,
+ workspaceScoped,
+ })
+ : undefined;
+ const resolvesRunCwd =
+ runEffectiveTarget === 'local' ||
+ runEffectiveTarget === 'device' ||
+ runEffectiveTarget === 'auto';
+ // Same precedence as `useEffectiveWorkingDirectory` (and the server's
+ // `resolveDeviceWorkingDirectoryConfig`), but over the MERGED config β€” the
+ // agent selector reads the raw shared row internally, which could fall back
+ // to a cwd registered for another member's device.
+ const runCwdDeviceId = resolvesRunCwd
+ ? resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped })
: undefined;
- const resolvesHeteroCwd =
- !!heterogeneousProvider &&
- (heteroEffectiveTarget === 'local' ||
- heteroEffectiveTarget === 'device' ||
- heteroEffectiveTarget === 'auto');
- // Same precedence as `getAgentWorkingDirectoryById`, but over the MERGED
- // config β€” the selector reads the raw shared row internally, which could
- // fall back to a cwd registered for another member's device. Desktop/home
- // is the only neutral last resort.
+ // Desktop/home is the last resort for hetero CLIs ONLY: they always spawn in
+ // some directory, so an unconfigured agent still needs one. A native agent
+ // with nothing configured stays unbound instead β€” pinning it to `~/Desktop`
+ // would file every desktop conversation under a project the user never
+ // picked.
const heteroCwdContext =
- resolvesHeteroCwd && isDesktop ? globalAgentContextManager.getContext() : undefined;
- const heteroCwdParams = resolvesHeteroCwd
+ resolvesRunCwd && isHeteroRun && isDesktop
+ ? globalAgentContextManager.getContext()
+ : undefined;
+ const runCwdParams = resolvesRunCwd
? {
agencyConfig,
currentDeviceId,
+ deviceDefaultCwd:
+ deviceSelectors.getDeviceDefaultCwd(runCwdDeviceId)(getDeviceStoreState()),
fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,
legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
workspaceScoped,
}
: undefined;
- const agentWorkingDirectory = heteroCwdParams
- ? resolveAgentWorkingDirectory(heteroCwdParams)
+ const agentWorkingDirectory = runCwdParams
+ ? resolveAgentWorkingDirectory(runCwdParams)
: undefined;
- const agentWorkingDirectoryConfig = heteroCwdParams
- ? resolveAgentWorkingDirectoryConfig(heteroCwdParams)
+ const agentWorkingDirectoryConfig = runCwdParams
+ ? resolveAgentWorkingDirectoryConfig(runCwdParams)
: undefined;
// Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd
// (`~/.claude/projects/<encoded-cwd>/`). Anchor their session cwd to the
@@ -1739,6 +1765,11 @@ export class ConversationLifecycleActionImpl {
...newTopicModelSnapshot,
// Same id the optimistic sidebar row already uses.
id: optimisticTopic?.id,
+ // Born bound to the directory this run resolved β€” the client
+ // runtime creates the topic here, so nothing downstream would
+ // ever write the cwd back (the server-side binding only exists
+ // on the gateway path).
+ metadata: optimisticTopicMetadata,
topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
title: newTopicTitle,
}