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(agent): resolve working directory by target device instead of legacy-only (#15591)

Arvin Xucdbef3f72efe
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx
index 79731803d10..81dcdd75b7c 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx
@@ -6,6 +6,7 @@ import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { useElectronStore } from '@/store/electron';
import { isPathWithinScope } from '../../utils/path';
@@ -23,7 +24,10 @@ const OutOfScopeWarning = memo<OutOfScopeWarningProps>(({ paths }) => {
const { t } = useTranslation('tool');
const topicWorkingDir = useChatStore(topicSelectors.currentTopicWorkingDirectory);
- const agentWorkingDir = useAgentStore(agentSelectors.currentAgentWorkingDirectory);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
+ const agentWorkingDir = useAgentStore(
+ agentSelectors.currentAgentWorkingDirectory(currentDeviceId),
+ );
const workingDirectory = topicWorkingDir || agentWorkingDir;
// Find paths that are outside the working directory
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
index ef5045c39fd..be277cdac9b 100644
--- a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
+++ b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
@@ -6,6 +6,7 @@ import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { useElectronStore } from '@/store/electron';
import { useAgentId } from '../hooks/useAgentId';
import {
@@ -30,8 +31,9 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
const isLocalSystemEnabled = useAgentStore(
chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),
);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const agentWorkingDirectory = useAgentStore((s) =>
- agentByIdSelectors.getAgentWorkingDirectoryById(agentId)(s),
+ agentByIdSelectors.getAgentWorkingDirectoryById(agentId, currentDeviceId)(s),
);
const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
const workingDirectory = topicWorkingDirectory || agentWorkingDirectory;
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 6fd67757e50..202ceeab6ae 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -24,6 +24,7 @@ import {
mergeAgentRuntimeInitialContexts,
resolveActiveTopicDocumentInitialContext,
} from '@/store/chat/utils/activeTopicDocumentContext';
+import { getElectronStoreState } from '@/store/electron';
import { type Store as ConversationStore } from '../../action';
@@ -85,8 +86,11 @@ const runHeterogeneousFromExistingMessage = async (
const topic = context.topicId
? topicSelectors.getTopicById(context.topicId)(chatStore)
: undefined;
- const agentWorkingDirectory =
- agentByIdSelectors.getAgentWorkingDirectoryById(agentId)(getAgentStoreState());
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(
+ agentId,
+ currentDeviceId,
+ )(getAgentStoreState());
const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;
// Drops the saved sessionId when its bound cwd disagrees with the current
diff --git a/src/helpers/parserPlaceholder/index.test.ts b/src/helpers/parserPlaceholder/index.test.ts
index 6716cd66846..20fc7426daf 100644
--- a/src/helpers/parserPlaceholder/index.test.ts
+++ b/src/helpers/parserPlaceholder/index.test.ts
@@ -36,7 +36,7 @@ vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
currentAgentModel: () => 'gpt-4',
currentAgentModelProvider: () => 'openai',
- currentAgentWorkingDirectory: () => undefined,
+ currentAgentWorkingDirectory: () => () => undefined,
},
}));
diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.ts
index e524acfc2f9..005a775a6ed 100644
--- a/src/helpers/parserPlaceholder/index.ts
+++ b/src/helpers/parserPlaceholder/index.ts
@@ -5,6 +5,7 @@ import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { getElectronStoreState } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -161,7 +162,10 @@ export const VARIABLE_GENERATORS = {
const topicWorkingDir = topicSelectors.currentTopicWorkingDirectory(useChatStore.getState());
if (topicWorkingDir) return topicWorkingDir;
- const agentWorkingDir = agentSelectors.currentAgentWorkingDirectory(useAgentStore.getState());
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentWorkingDir = agentSelectors.currentAgentWorkingDirectory(currentDeviceId)(
+ useAgentStore.getState(),
+ );
return agentWorkingDir ?? '(not specified, use user Home directory as default)';
},
} as Record<string, () => string>;
diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
index d257b84ce82..22d54ced324 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
@@ -10,6 +10,7 @@ import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { useElectronStore } from '@/store/electron';
import HeaderActions from './HeaderActions';
import ParamsPanelToggle from './ParamsPanelToggle';
@@ -42,8 +43,11 @@ const headerStyles = createStaticStyles(({ css }) => ({
const Header = memo(() => {
const agentId = useChatStore((s) => s.activeAgentId);
const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const agentWorkingDirectory = useAgentStore((s) =>
- agentId ? agentByIdSelectors.getAgentWorkingDirectoryById(agentId)(s) : undefined,
+ agentId
+ ? agentByIdSelectors.getAgentWorkingDirectoryById(agentId, currentDeviceId)(s)
+ : undefined,
);
const isLocalSystemEnabled = useAgentStore((s) =>
agentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,
diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.ts
index ad3c2e8032e..612aae8066e 100644
--- a/src/store/agent/selectors/agentByIdSelectors.test.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts
@@ -1,11 +1,18 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';
import { agentByIdSelectors } from './agentByIdSelectors';
+// getAgentWorkingDirectoryById is desktop-only; force the desktop branch on.
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isDesktop: true,
+}));
+
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
@@ -56,4 +63,64 @@ describe('agentByIdSelectors', () => {
});
});
});
+
+ describe('getAgentWorkingDirectoryById', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const stateWith = (config: Record<string, any>, localMap: Record<string, string> = {}) =>
+ createState({
+ agentMap: { 'agent-1': config },
+ localAgentWorkingDirectoryMap: localMap,
+ });
+
+ it('reads the per-device choice for the current (local) device', () => {
+ vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
+ const state = stateWith({
+ agencyConfig: { workingDirByDevice: { 'device-A': '/repos/agent-gateway' } },
+ });
+
+ expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
+ '/repos/agent-gateway',
+ );
+ });
+
+ it('reads the bound device choice when the agent targets a device', () => {
+ vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
+ const state = stateWith({
+ agencyConfig: {
+ boundDeviceId: 'device-B',
+ executionTarget: 'device',
+ workingDirByDevice: { 'device-A': '/repos/local', 'device-B': '/repos/remote' },
+ },
+ });
+
+ // currentDeviceId is the local machine, but executionTarget=device β†’ device-B wins
+ expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
+ '/repos/remote',
+ );
+ });
+
+ it('falls back to the legacy per-agent value when no device choice exists', () => {
+ vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
+ const state = stateWith({ agencyConfig: {} }, { 'agent-1': '/repos/legacy' });
+
+ expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
+ '/repos/legacy',
+ );
+ });
+
+ it('falls back to desktop/home path when nothing is set', () => {
+ vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({
+ desktopPath: '/home/me/Desktop',
+ homePath: '/home/me',
+ });
+ const state = stateWith({ agencyConfig: {} });
+
+ expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
+ '/home/me/Desktop',
+ );
+ });
+ });
});
diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.ts
index ef209054334..f382415e752 100644
--- a/src/store/agent/selectors/agentByIdSelectors.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.ts
@@ -8,6 +8,7 @@ import {
type RuntimeEnvConfig,
} from '@lobechat/types';
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { type AgentStoreState } from '../initialState';
@@ -85,15 +86,35 @@ const getAgentRuntimeEnvConfigById =
agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig?.runtimeEnv;
/**
- * Get working directory by agentId
+ * Get the agent-level working directory by agentId.
+ *
+ * Precedence (the agent-owned slice only β€” topic overrides and device defaults
+ * are layered on by callers):
+ *
+ * agent's per-device choice (`agencyConfig.workingDirByDevice[targetDeviceId]`)
+ * > legacy per-agent localStorage value (pre-migration fallback)
+ * > desktop path > home path
+ *
+ * `currentDeviceId` is passed in (not read cross-store) so hook callers stay
+ * reactive to device changes. The target device is resolved from it via
+ * `resolveTargetDeviceId`, so a device-bound agent reads its bound device's
+ * choice rather than the local machine's.
*/
const getAgentWorkingDirectoryById =
- (agentId: string) =>
+ (agentId: string, currentDeviceId?: string) =>
(s: AgentStoreState): string | undefined => {
if (!isDesktop) return;
const ctx = globalAgentContextManager.getContext();
- return s.localAgentWorkingDirectoryMap[agentId] ?? ctx.desktopPath ?? ctx.homePath;
+ const agencyConfig = agentSelectors.getAgentConfigById(agentId)(s)?.agencyConfig;
+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
+ const agentChoice = targetDeviceId
+ ? agencyConfig?.workingDirByDevice?.[targetDeviceId]
+ : undefined;
+
+ return (
+ agentChoice ?? s.localAgentWorkingDirectoryMap[agentId] ?? ctx.desktopPath ?? ctx.homePath
+ );
};
/**
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index fde7ce03482..6be63cfcb31 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -20,6 +20,7 @@ import { KnowledgeType } from '@lobechat/types';
import { VoiceList } from '@lobehub/tts';
import { DEFAULT_OPENING_QUESTIONS } from '@/features/AgentSetting/store/selectors';
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { filterToolIds } from '@/helpers/toolFilters';
@@ -260,20 +261,34 @@ const currentAgentRuntimeEnvConfig = (s: AgentStoreState): RuntimeEnvConfig | un
currentAgentConfig(s)?.chatConfig?.runtimeEnv;
/**
- * Get current agent's working directory
+ * Get the active agent's agent-level working directory.
+ *
+ * Precedence mirrors `getAgentWorkingDirectoryById` (the agent-owned slice only;
+ * topic overrides are layered on by callers):
+ *
+ * agent's per-device choice (`agencyConfig.workingDirByDevice[targetDeviceId]`)
+ * > legacy per-agent localStorage value > home path
+ *
+ * `currentDeviceId` is passed in (not read cross-store) so the target device is
+ * resolved correctly for device-bound agents and hook callers stay reactive.
*/
-const currentAgentWorkingDirectory = (s: AgentStoreState): string | undefined =>
- (() => {
+const currentAgentWorkingDirectory =
+ (currentDeviceId?: string) =>
+ (s: AgentStoreState): string | undefined => {
if (!isDesktop) return;
+ const homePath = globalAgentContextManager.getContext().homePath;
const activeAgentId = s.activeAgentId;
- if (!activeAgentId) return globalAgentContextManager.getContext().homePath;
+ if (!activeAgentId) return homePath;
- return (
- s.localAgentWorkingDirectoryMap[activeAgentId] ??
- globalAgentContextManager.getContext().homePath
- );
- })();
+ const agencyConfig = currentAgentConfig(s)?.agencyConfig;
+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
+ const agentChoice = targetDeviceId
+ ? agencyConfig?.workingDirByDevice?.[targetDeviceId]
+ : undefined;
+
+ return agentChoice ?? s.localAgentWorkingDirectoryMap[activeAgentId] ?? homePath;
+ };
const isCurrentAgentExternal = (s: AgentStoreState): boolean => !currentAgentData(s)?.virtual;
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 9e12c3a42e5..87a5da9ecfc 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -59,7 +59,7 @@ vi.mock('@/services/electron/gatewayConnection', () => ({
vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));
vi.mock('@/store/agent/selectors', () => ({
- agentSelectors: { currentAgentWorkingDirectory: () => undefined },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
chatConfigByIdSelectors: { isLocalSystemEnabledById: () => () => mockRuntime.isLocal },
}));
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 2ca6f504ddb..74ae502bf24 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -54,6 +54,7 @@ import {
getCompressionCandidateMessageIds,
hasRunningCompressionOperation,
} from '@/store/chat/utils/compression';
+import { getElectronStoreState } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { type StoreSetter } from '@/store/types';
@@ -524,8 +525,11 @@ export class ConversationLifecycleActionImpl {
const existingTopic = operationContext.topicId
? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
: undefined;
- const agentWorkingDirectory =
- agentByIdSelectors.getAgentWorkingDirectoryById(agentId)(getAgentStoreState());
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(
+ agentId,
+ currentDeviceId,
+ )(getAgentStoreState());
const workingDirectory = existingTopic?.metadata?.workingDirectory || agentWorkingDirectory;
// Persist messages to DB first (same as client mode)
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 62d47587bf4..0851a619a0f 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -42,6 +42,7 @@ import {
notifyDesktopHumanApprovalRequired,
resolveNotificationNavigatePath,
} from '@/store/chat/utils/desktopNotification';
+import { getElectronStoreState } from '@/store/electron';
import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import { getTaskStoreState } from '@/store/task';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
@@ -331,7 +332,9 @@ export class StreamingExecutorActionImpl {
};
const topicWorkingDirectory = topicSelectors.currentTopicWorkingDirectory(this.#get());
- const agentWorkingDirectory = agentSelectors.currentAgentWorkingDirectory(getAgentStoreState());
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentWorkingDirectory =
+ agentSelectors.currentAgentWorkingDirectory(currentDeviceId)(getAgentStoreState());
const workingDirectory = topicWorkingDirectory ?? agentWorkingDirectory;
// Create initial state or use provided state