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): keep sub-agents and working directories on the parent's device (#19974)

Arvin Xu827a68ff87aa
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index d4b5c279c83..bb24531c82d 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -26,6 +26,13 @@ vi.mock('node:child_process', () => ({
spawn: vi.fn(),
}));
+// The shared runner checks cwd exists before spawning; `spawn` is mocked, so
+// treat the fixture cwd (`/repo`) as a real directory.
+vi.mock('node:fs/promises', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('node:fs/promises')>()),
+ stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),
+}));
+
vi.mock('../CliCtr', () => ({
default: class CliCtr {},
}));
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentDevice.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentDevice.test.ts
new file mode 100644
index 00000000000..f24bdc520ad
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentDevice.test.ts
@@ -0,0 +1,91 @@
+import { type AgentState } from '@lobechat/agent-runtime';
+import { type ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { resolveExecutionPlan } from '@/helpers/executionTarget';
+
+import { type RuntimeExecutorContext } from '../context';
+import { buildServerVirtualSubAgentRunner } from '../executorHelpers';
+
+/**
+ * A `callSubAgent` child used to re-route from scratch. With no device of its
+ * own, an agent in `local` mode fell back to the agent-level `boundDeviceId` β€”
+ * a value written by whichever machine last picked "this device" β€” so with two
+ * desktops online every parent ran on one machine and every child on the other.
+ * The child must run on the device its parent is actually bound to.
+ */
+describe('buildServerVirtualSubAgentRunner device inheritance', () => {
+ // The desktop the parent run executes on (it sends its own id).
+ const PARENT_DEVICE = '838d6e154b6dbf342b9410cf58857a9d';
+ // A second online desktop left in `agencyConfig.boundDeviceId` by an earlier pick.
+ const STALE_BOUND_DEVICE = '1aab3a739730a7db2f070246daa68be4';
+ const agencyConfig = {
+ boundDeviceId: STALE_BOUND_DEVICE,
+ executionTarget: 'local' as const,
+ workingDirByDevice: { [PARENT_DEVICE]: { path: 'D:\\Sourcecode\\JuLink.W001' } },
+ };
+ const onlineDeviceIds = [PARENT_DEVICE, STALE_BOUND_DEVICE];
+
+ const buildRunner = () => {
+ const execVirtualSubAgent = vi.fn().mockResolvedValue({ operationId: 'child-op' });
+ const ctx = {
+ execVirtualSubAgent,
+ messageModel: { create: vi.fn().mockResolvedValue({ id: 'placeholder-id' }) },
+ operationId: 'parent-op',
+ topicId: 'topic-1',
+ } as unknown as RuntimeExecutorContext;
+
+ const runner = buildServerVirtualSubAgentRunner(
+ ctx,
+ {
+ binding: { device: { id: PARENT_DEVICE } },
+ operationId: 'parent-op',
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ plan: { execution: { deviceId: PARENT_DEVICE, kind: 'device', target: 'local' } },
+ world: { agent: { agencyConfig } as any },
+ } as unknown as AgentState,
+ { id: 'tool-call-1' } as ChatToolPayload,
+ 'parent-message-1',
+ );
+
+ return { execVirtualSubAgent, runner };
+ };
+
+ it('[R1] parent and callSubAgent child resolve to the same device', async () => {
+ const { execVirtualSubAgent, runner } = buildRunner();
+
+ await runner!.run({ description: 'task', instruction: 'run hostname' });
+
+ const forwarded = execVirtualSubAgent.mock.calls[0][0];
+ const parentPlan = resolveExecutionPlan({
+ agencyConfig,
+ clientExecutionAvailable: true,
+ localDeviceId: PARENT_DEVICE,
+ onlineDeviceIds,
+ requestedDeviceId: PARENT_DEVICE,
+ });
+ const childPlan = resolveExecutionPlan({
+ agencyConfig,
+ clientExecutionAvailable: true,
+ localDeviceId: forwarded.localDeviceId,
+ onlineDeviceIds,
+ requestedDeviceId: forwarded.deviceId,
+ });
+
+ expect(childPlan).toEqual(parentPlan);
+ expect(childPlan).toMatchObject({ deviceId: PARENT_DEVICE, kind: 'device' });
+ });
+
+ it('forwards the parent device to a named callAgent target only as its "local" device', async () => {
+ const { execVirtualSubAgent, runner } = buildRunner();
+
+ await runner!.run({ agentId: 'target-agent', description: 'task', instruction: 'do it' });
+
+ // A named agent keeps its own execution target (it may be sandbox-only), so
+ // the parent device must not force it onto a device; it only answers what
+ // "this machine" means for a target that is `local`.
+ expect(execVirtualSubAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: undefined, localDeviceId: PARENT_DEVICE }),
+ );
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 8d41d6b3ab0..2016062b05e 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -24,6 +24,7 @@ import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archi
import { buildWorkVersionCumulativeUsage } from '@/utils/workCumulativeUsage';
import { type RuntimeExecutorContext } from './context';
+import { resolveRunActiveDeviceId } from './executors/resolveRunActiveDeviceId';
export const log = debug('lobe-server:agent-runtime:streaming-executors');
export const timing = debug('lobe-server:agent-runtime:timing');
@@ -237,6 +238,14 @@ export const buildServerVirtualSubAgentRunner = (
// keeps the topic-pinned model only in `modelRuntimeConfig` while the
// world config retains the agent default.
const parentEffectiveModel = state.modelRuntimeConfig ?? parentAgentConfig;
+ // The device the parent run executes on. The child re-resolves its own
+ // execution plan, and without this it falls back to the agent-level
+ // `boundDeviceId` β€” whichever machine last picked "this device" β€” so with two
+ // desktops online the parent and the child land on different machines. An
+ // anonymous `callSubAgent` clone requests this device outright; a named
+ // `callAgent` target only takes it as its `local` device, keeping its own
+ // execution target.
+ const parentDeviceId = resolveRunActiveDeviceId(state);
return {
run: async ({ agentId: targetAgentId, description, instruction, timeout }) => {
@@ -281,8 +290,10 @@ export const buildServerVirtualSubAgentRunner = (
const result = (await execVirtualSubAgent({
agentId: targetAgentId ?? agentId,
chatConfig: subAgentChatConfig,
+ deviceId: targetAgentId ? undefined : parentDeviceId,
groupId: state.origin?.groupId ?? undefined,
instruction,
+ localDeviceId: parentDeviceId,
model: subAgentModel?.model,
parentMessageId: placeholder.id,
parentOperationId: ctx.operationId,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
index 98aea267109..d5dd579abab 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
@@ -256,8 +256,10 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
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.
+ // keeps the SOURCE repo, which is what By-Project groups on. The device is
+ // stamped with it so another device does not inherit this path.
expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ boundDeviceId: DEVICE_ID,
workingDirectory: WORKTREE_PATH,
workingDirectoryConfig: {
git: { activeWorktree: WORKTREE_PATH },
@@ -280,6 +282,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ boundDeviceId: DEVICE_ID,
workingDirectory: '/repo/default',
workingDirectoryConfig: { path: '/repo/default' },
});
@@ -315,6 +318,31 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
);
});
+ it("does not give a topic bound to another device this device's directory", async () => {
+ mockTopicFindById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { boundDeviceId: 'other-device' },
+ });
+ 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' }),
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index 40a9bfaa6c2..5b9058261e0 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -298,6 +298,27 @@ describe('AiAgentService.execSubAgent', () => {
);
});
+ it('[R2] forwards the parent device of a callSubAgent child to execAgent', async () => {
+ const PARENT_DEVICE = '838d6e154b6dbf342b9410cf58857a9d';
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+
+ await service.execVirtualSubAgent({
+ agentId: 'agent-1',
+ deviceId: PARENT_DEVICE,
+ instruction: 'run hostname',
+ localDeviceId: PARENT_DEVICE,
+ parentMessageId: 'tool-msg-1',
+ parentOperationId: 'parent-op-1',
+ topicId: 'topic-1',
+ } as any);
+
+ expect(execAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: PARENT_DEVICE, localDeviceId: PARENT_DEVICE }),
+ );
+ });
+
it('should store operationId and startedAt in Thread metadata', async () => {
vi.spyOn(service, 'execAgent').mockResolvedValue({
agentId: 'agent-1',
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 40b0eed0dfa..4dfb633c289 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -11,7 +11,6 @@ import type {
ScheduleAgentRunParams,
ScheduleAgentRunResult,
UserInterventionConfig,
- WorkingDirConfig,
} from '@lobechat/types';
import { getWorkingDirEffectivePath, RequestTrigger } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
@@ -70,7 +69,11 @@ import { applyShareGateToAgentConfig } from './shareGate';
import type { SubAgentRunDeps } from './subAgentRuns';
import { execAgentMember, execAgentThreadRun } from './subAgentRuns';
import { acquireTopicStartReservation } from './topicStartReservation';
-import type { ExecRunContext, InternalExecAgentParams } from './types';
+import type {
+ BindTopicWorkingDirectoryParams,
+ ExecRunContext,
+ InternalExecAgentParams,
+} from './types';
const log = debug('lobe-server:ai-agent-service');
@@ -265,19 +268,23 @@ export class AiAgentService {
* 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.
+ *
+ * The pin is a bare path that only holds on the machine it came from, so the
+ * device is stamped alongside it (`boundDeviceId`, unless the topic already
+ * names one) β€” that is what lets another device skip it. A topic already
+ * bound to a different device is left unpinned rather than given this
+ * device's path.
*/
- private async bindTopicWorkingDirectory(params: {
- config?: WorkingDirConfig;
- currentWorkingDirectory?: string;
- topicId: string;
- }): Promise<void> {
- const { config, currentWorkingDirectory, topicId } = params;
+ private async bindTopicWorkingDirectory(params: BindTopicWorkingDirectoryParams): Promise<void> {
+ const { config, currentDeviceId, currentWorkingDirectory, deviceId, topicId } = params;
if (currentWorkingDirectory || !config) return;
+ if (currentDeviceId && deviceId && currentDeviceId !== deviceId) return;
const path = getWorkingDirEffectivePath(config);
if (!path) return;
try {
await this.topicModel.updateMetadata(topicId, {
+ ...(deviceId && !currentDeviceId && { boundDeviceId: deviceId }),
workingDirectory: path,
workingDirectoryConfig: config,
});
@@ -1459,7 +1466,9 @@ export class AiAgentService {
execVirtualSubAgent = async (params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> =>
execAgentThreadRun(this.subAgentRunDeps, params, {
chatConfig: params.chatConfig,
+ deviceId: params.deviceId,
isSubAgent: true,
+ localDeviceId: params.localDeviceId,
logScope: 'execVirtualSubAgent',
// Sub-agent model is resolved at the spawn site (callSubAgent runner) from
// the parent agent's `agencyConfig.subagent` and threaded through here as an
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index c461226b57e..93fbcb70f0d 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -14,7 +14,6 @@ import type {
HeterogeneousTopicPin,
LobeAgentAgencyConfig,
RequestTrigger,
- WorkingDirConfig,
} from '@lobechat/types';
import {
applyTopicModelToHeterogeneousProvider,
@@ -54,17 +53,13 @@ import {
supportsCloudHeterogeneousSandbox,
} from '../helpers/heteroErrors';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
-import type { ExecRunContext } from '../types';
+import type { BindTopicWorkingDirectoryParams, ExecRunContext } from '../types';
import { heteroOperationCapabilities } from './heteroOperationCapabilities';
const log = debug('lobe-server:ai-agent-service');
export interface HeteroDispatchDeps {
- bindTopicWorkingDirectory: (params: {
- config?: WorkingDirConfig;
- currentWorkingDirectory?: string;
- topicId: string;
- }) => Promise<void>;
+ bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;
db: LobeChatDatabase;
getMarketService: () => Promise<MarketService>;
messageModel: MessageModel;
@@ -984,8 +979,10 @@ export const dispatchHeteroAgent = async (
const deviceCwdConfig = resolveDeviceWorkingDirectoryConfig({
deviceDefaultCwd: boundDevice?.defaultCwd,
deviceId: dispatchDeviceId,
+ devicePlatform: boundDevice?.platform,
initialWorkingDirectory: appContext?.initialTopicMetadata?.workingDirectory,
initialWorkingDirectoryConfig: appContext?.initialTopicMetadata?.workingDirectoryConfig,
+ topicDeviceId: topic?.metadata?.boundDeviceId,
topicWorkingDirectory: topic?.metadata?.workingDirectory,
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
workingDirByDevice: agentConfig.agencyConfig?.workingDirByDevice,
@@ -998,7 +995,9 @@ export const dispatchHeteroAgent = async (
// under the right project and the next turn reuses the same directory.
await deps.bindTopicWorkingDirectory({
config: deviceCwdConfig,
+ currentDeviceId: topic?.metadata?.boundDeviceId,
currentWorkingDirectory: topic?.metadata?.workingDirectory,
+ deviceId: dispatchDeviceId,
topicId,
});
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index f1e39249610..39097652e2b 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -7,7 +7,7 @@ import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import { assembleSkillPool } from '@lobechat/mecha';
import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';
-import type { LobeAgentAgencyConfig, WorkingDirConfig, WorkspaceInitResult } from '@lobechat/types';
+import type { LobeAgentAgencyConfig, WorkspaceInitResult } from '@lobechat/types';
import {
buildGoalOverviewContext,
getActivePluginIds,
@@ -32,7 +32,12 @@ import { FileService } from '@/server/services/file';
import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
import { applyShareGateToToolSet, filterSkillsByShareGate } from '../shareGate';
-import type { ExecRunContext, InternalExecAgentParams, ResolvedWorkspaceInit } from '../types';
+import type {
+ BindTopicWorkingDirectoryParams,
+ ExecRunContext,
+ InternalExecAgentParams,
+ ResolvedWorkspaceInit,
+} from '../types';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';
import type { ToolDiscoveryResult } from './toolDiscovery';
import type { RunAttachments } from './turnSetup';
@@ -162,11 +167,7 @@ export const createHistoryMessagesLoader = (
export interface OperationPrepDeps {
agentDocumentsService: AgentDocumentsService;
agentModel: AgentModel;
- bindTopicWorkingDirectory: (params: {
- config?: WorkingDirConfig;
- currentWorkingDirectory?: string;
- topicId: string;
- }) => Promise<void>;
+ bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;
db: LobeChatDatabase;
topicModel: TopicModel;
userId: string;
@@ -259,13 +260,20 @@ const resolveWorkspaceInit = async (
const boundCwdConfig = resolveDeviceWorkingDirectoryConfig({
deviceDefaultCwd: device.defaultCwd,
deviceId: activeDeviceId,
+ devicePlatform: device.platform,
+ topicDeviceId: topic?.metadata?.boundDeviceId,
topicWorkingDirectory,
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
workingDirByDevice: agencyConfig?.workingDirByDevice,
});
const boundCwd = getWorkingDirEffectivePath(boundCwdConfig);
if (!boundCwd) return { workspace: empty };
- const resolved = { boundCwd, boundCwdConfig, topicWorkingDirectory };
+ const resolved = {
+ boundCwd,
+ boundCwdConfig,
+ topicDeviceId: topic?.metadata?.boundDeviceId,
+ topicWorkingDirectory,
+ };
const workingDirs = device.workingDirs ?? [];
const cached = workingDirs.find(
@@ -695,7 +703,9 @@ export const prepareOperation = async (
// the tool layer reads the topic's cwd on the same run.
await deps.bindTopicWorkingDirectory({
config: workspaceInit.boundCwdConfig,
+ currentDeviceId: workspaceInit.topicDeviceId,
currentWorkingDirectory: workspaceInit.topicWorkingDirectory,
+ deviceId: activeDeviceId,
topicId,
});
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
index 055d8c85af6..8413efbab1f 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
@@ -93,6 +93,59 @@ describe('resolveDeviceWorkingDirectory', () => {
).toBe('/default');
});
+ describe('[R3] a topic pin only applies on the device it belongs to', () => {
+ const WELLS_LEGION = '838d6e154b6dbf342b9410cf58857a9d';
+ const ITZC = '1aab3a739730a7db2f070246daa68be4';
+ const UBUNTU = 'b06d4da75107ca3ed74ac3b35663d218';
+
+ it("does not carry a Windows topic pin onto a Linux device over the agent's pick for it", () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceId: UBUNTU,
+ devicePlatform: 'linux',
+ topicWorkingDirectory: 'E:\\androidproject\\vrplayer',
+ workingDirByDevice: { [UBUNTU]: { path: '/root/workspace/proxy' } },
+ }),
+ ).toBe('/root/workspace/proxy');
+ });
+
+ it('does not carry a pin from the device that bound the topic onto another device', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: 'C:\\Users\\260622',
+ deviceId: ITZC,
+ devicePlatform: 'win32',
+ topicDeviceId: WELLS_LEGION,
+ topicWorkingDirectory: 'D:\\Sourcecode\\JuLink.W001',
+ workingDirByDevice: { [WELLS_LEGION]: { path: 'D:\\Sourcecode\\JuLink.W001' } },
+ }),
+ ).toBe('C:\\Users\\260622');
+ });
+
+ it('keeps the pin on the device that bound the topic', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceId: WELLS_LEGION,
+ devicePlatform: 'win32',
+ topicDeviceId: WELLS_LEGION,
+ topicWorkingDirectory: 'D:\\Sourcecode\\JuLink.W001',
+ workingDirByDevice: { [WELLS_LEGION]: { path: 'D:\\other' } },
+ }),
+ ).toBe('D:\\Sourcecode\\JuLink.W001');
+ });
+
+ it('keeps a pin with no recorded device when its path fits the device platform', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceId: UBUNTU,
+ devicePlatform: 'linux',
+ topicWorkingDirectory: '/srv/app',
+ workingDirByDevice: { [UBUNTU]: '/root/workspace/proxy' },
+ }),
+ ).toBe('/srv/app');
+ });
+ });
+
it('treats null/undefined inputs as absent', () => {
expect(
resolveDeviceWorkingDirectory({
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
index dcea804a733..1d0bd12ef12 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
@@ -1,3 +1,5 @@
+import path from 'node:path';
+
import type { WorkingDirConfig, WorkingDirConfigValue } from '@lobechat/types';
import { getWorkingDirEffectivePath } from '@lobechat/types';
@@ -8,6 +10,29 @@ const toWorkingDirConfig = (
return typeof value === 'string' ? { path: value } : value;
};
+/**
+ * A topic's pinned cwd is a bare path recorded on one machine, so it only
+ * holds on that machine. `topicDeviceId` (`topic.metadata.boundDeviceId`) names
+ * it when known; for older topics without one, a Windows drive/UNC path on a
+ * non-Windows device is the tell-tale that the pin came from elsewhere.
+ */
+const topicPinFitsDevice = (
+ pinnedPath: string | undefined,
+ params: { deviceId?: string; devicePlatform?: string | null; topicDeviceId?: string },
+): boolean => {
+ if (params.deviceId && params.topicDeviceId && params.deviceId !== params.topicDeviceId)
+ return false;
+ if (
+ pinnedPath &&
+ params.devicePlatform &&
+ params.devicePlatform !== 'win32' &&
+ path.win32.isAbsolute(pinnedPath) &&
+ !path.posix.isAbsolute(pinnedPath)
+ )
+ return false;
+ return true;
+};
+
/**
* Resolve the working directory for a device-bound run.
*
@@ -20,7 +45,10 @@ const toWorkingDirConfig = (
* choice > device default.
*
* - `topicWorkingDirectory` β€” an existing topic's pinned cwd
- * (`topic.metadata.workingDirectory`); always wins once a conversation exists.
+ * (`topic.metadata.workingDirectory`); wins once a conversation exists, but
+ * only on the device it was pinned on (`topicDeviceId` / `devicePlatform`).
+ * Another device β€” a sub-agent, or the agent moved to a new machine β€” skips
+ * it and resolves its own directory from the sources below.
* - `initialWorkingDirectory` β€” only populated for a brand-new topic
* (`appContext.initialTopicMetadata.workingDirectory`, e.g. the primary repo).
* - `workingDirByDevice[deviceId]` β€” the agent's per-device pick from the picker
@@ -30,14 +58,18 @@ const toWorkingDirConfig = (
export const resolveDeviceWorkingDirectoryConfig = (params: {
deviceDefaultCwd?: string | null;
deviceId?: string;
+ devicePlatform?: string | null;
initialWorkingDirectory?: string;
initialWorkingDirectoryConfig?: WorkingDirConfig;
+ topicDeviceId?: string;
topicWorkingDirectory?: string;
topicWorkingDirectoryConfig?: WorkingDirConfig;
workingDirByDevice?: Record<string, WorkingDirConfigValue> | null;
}): WorkingDirConfig | undefined => {
- if (params.topicWorkingDirectoryConfig) return params.topicWorkingDirectoryConfig;
- if (params.topicWorkingDirectory) return { path: params.topicWorkingDirectory };
+ const topicPin =
+ params.topicWorkingDirectoryConfig ??
+ (params.topicWorkingDirectory ? { path: params.topicWorkingDirectory } : undefined);
+ if (topicPin && topicPinFitsDevice(topicPin.path, params)) return topicPin;
if (params.initialWorkingDirectoryConfig) return params.initialWorkingDirectoryConfig;
if (params.initialWorkingDirectory) return { path: params.initialWorkingDirectory };
diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.ts
index 2aedc8c361c..cca8bc770d3 100644
--- a/apps/server/src/services/aiAgent/subAgentRuns.ts
+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts
@@ -52,7 +52,14 @@ export interface ExecAgentThreadRunOptions {
* Only set by the callSubAgent path.
*/
chatConfig?: Partial<LobeAgentChatConfig> | null;
+ /**
+ * Device the spawned run inherits from its parent, forwarded to execAgent as
+ * `deviceId` / `localDeviceId`. Only set by the callSubAgent path; see
+ * {@link ExecVirtualSubAgentParams.deviceId}.
+ */
+ deviceId?: string;
isSubAgent: boolean;
+ localDeviceId?: string;
logScope: 'execSubAgent' | 'execVirtualSubAgent';
/**
* Explicit model/provider override for the spawned run. The callSubAgent
@@ -204,7 +211,9 @@ export const execAgentThreadRun = async (
appContext,
autoStart: true,
chatConfigOverride: options.chatConfig,
+ deviceId: options.deviceId,
hooks,
+ localDeviceId: options.localDeviceId,
// Explicit sub-agent model override resolved at the spawn site.
model: options.model,
parentOperationId,
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index a053f94b924..d35b8dadc17 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -308,6 +308,16 @@ export interface InternalExecAgentParams extends ExecAgentParams {
* project path placeholder (and the tool cwd/scope downstream) without re-loading
* the device + topic the scan already read.
*/
+export interface BindTopicWorkingDirectoryParams {
+ config?: WorkingDirConfig;
+ /** The topic's existing `metadata.boundDeviceId`, if any. */
+ currentDeviceId?: string;
+ currentWorkingDirectory?: string;
+ /** The device {@link config} was resolved for. */
+ deviceId?: string;
+ topicId: string;
+}
+
export interface ResolvedWorkspaceInit {
boundCwd?: string;
/**
@@ -317,6 +327,8 @@ export interface ResolvedWorkspaceInit {
* a linked worktree must still file under its repo.
*/
boundCwdConfig?: WorkingDirConfig;
+ /** The device the topic's cwd is pinned on (`topic.metadata.boundDeviceId`). */
+ topicDeviceId?: string;
/**
* 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.
diff --git a/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts b/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts
index bc8393120f6..19cc524c623 100644
--- a/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts
@@ -17,6 +17,17 @@ describe('resolveAgainstCwd', () => {
expect(resolveAgainstCwd('/etc/hosts', cwd)).toBe('/etc/hosts');
});
+ it('[R5] leaves a Windows absolute path untouched regardless of the host platform', () => {
+ expect(
+ resolveAgainstCwd(
+ 'E:\\androidproject\\vrplayer\\app\\build.gradle',
+ 'E:\\androidproject\\vrplayer',
+ ),
+ ).toBe('E:\\androidproject\\vrplayer\\app\\build.gradle');
+ expect(resolveAgainstCwd('C:/Users/me/a.txt', cwd)).toBe('C:/Users/me/a.txt');
+ expect(resolveAgainstCwd('\\\\server\\share\\a.txt', cwd)).toBe('\\\\server\\share\\a.txt');
+ });
+
it('expands ~ before considering cwd', () => {
expect(resolveAgainstCwd('~/notes.md', cwd)).toBe(path.join(os.homedir(), 'notes.md'));
});
diff --git a/packages/local-file-shell/src/file/expandTilde.ts b/packages/local-file-shell/src/file/expandTilde.ts
index 1a72770f7b4..627e658b90a 100644
--- a/packages/local-file-shell/src/file/expandTilde.ts
+++ b/packages/local-file-shell/src/file/expandTilde.ts
@@ -27,11 +27,14 @@ export const expandTilde = (input: string | undefined): string | undefined => {
* supplied by the model resolves against the daemon's `process.cwd()` (= `/`
* for a Finder/Dock-launched app) instead of the user's bound directory.
*/
-export const resolveAgainstCwd = (
- input: string | undefined,
- cwd?: string,
-): string | undefined => {
+export const resolveAgainstCwd = (input: string | undefined, cwd?: string): string | undefined => {
const expanded = expandTilde(input);
if (!expanded || !cwd) return expanded;
- return path.isAbsolute(expanded) ? expanded : path.join(cwd, expanded);
+ // A Windows path (`E:\repo\a.txt`, `\\server\share`) is absolute
+ // regardless of the host: on a POSIX device the host `path` calls it relative
+ // and would glue it onto cwd (`/cwd/E:\repo\a.txt`), hiding the real problem β€”
+ // the path belongs to another machine β€” behind a nonsensical one.
+ return path.isAbsolute(expanded) || path.win32.isAbsolute(expanded)
+ ? expanded
+ : path.join(cwd, expanded);
};
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
index d1c4aa05544..917e24b6de7 100644
--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
@@ -105,7 +105,7 @@ describe('runCommand', () => {
expect(result.stdout).toContain('/tmp');
});
- it('should report the real spawn error when cwd does not exist', async () => {
+ it('[R4] reports a missing cwd as a missing working directory, not as a missing shell', async () => {
const missingCwd = path.join(tmpDir, 'missing-worktree');
const result = await runCommand(
{ command: 'echo unreachable', cwd: missingCwd },
@@ -114,8 +114,23 @@ describe('runCommand', () => {
expect(result.success).toBe(false);
expect(result.exit_code).toBeUndefined();
- expect(result.error).toContain(`working directory: ${missingCwd}`);
- expect(result.error).toContain('ENOENT');
+ // Node blames the executable (`spawn /bin/sh ENOENT`) when cwd is missing,
+ // which sends the model off debugging a healthy shell.
+ expect(result.error).not.toMatch(/spawn \S+ ENOENT/);
+ expect(result.error).toContain(`Working directory does not exist on ${os.hostname()}`);
+ expect(result.error).toContain(missingCwd);
+ });
+
+ it('reports a cwd that is a file as not a directory', async () => {
+ const fileCwd = path.join(tmpDir, 'a-file');
+ fs.writeFileSync(fileCwd, '');
+ const result = await runCommand(
+ { command: 'echo unreachable', cwd: fileCwd },
+ { processManager },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain(`Working directory is not a directory on ${os.hostname()}`);
});
it('should merge env into child process environment', async () => {
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index cff7224bdf0..45bb47b1ccb 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -1,4 +1,6 @@
import { spawn } from 'node:child_process';
+import { stat } from 'node:fs/promises';
+import os from 'node:os';
import type { SandboxPolicy } from '@lobechat/device-sandbox';
@@ -30,6 +32,22 @@ export interface RunCommandOptions {
sandboxPolicy?: SandboxPolicy;
}
+/**
+ * Node reports a missing spawn cwd as `spawn <shell> ENOENT` β€” blaming the
+ * shell binary β€” so the model goes off debugging a healthy shell. Check the
+ * directory first and name the real problem, and the machine it happened on
+ * (a cwd pinned on another device is the usual cause).
+ */
+const checkWorkingDirectory = async (cwd: string): Promise<string | undefined> => {
+ try {
+ if ((await stat(cwd)).isDirectory()) return;
+ return `Working directory is not a directory on ${os.hostname()}: ${cwd}`;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return;
+ return `Working directory does not exist on ${os.hostname()}: ${cwd}. The shell is fine β€” run the command from a directory that exists on this device.`;
+ }
+};
+
export async function runCommand(
{
command,
@@ -48,6 +66,11 @@ export async function runCommand(
const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
+ if (cwd) {
+ const cwdError = await checkWorkingDirectory(cwd);
+ if (cwdError) return { error: cwdError, success: false };
+ }
+
const requestedEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;
// On Windows, rewrite env-var references the target shell cannot resolve
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 0981921bc3b..097b6c521f9 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -487,10 +487,22 @@ export interface ExecVirtualSubAgentParams {
* Merged over the executing agent's own chatConfig, skipping nulled keys.
*/
chatConfig?: Partial<LobeAgentChatConfig> | null;
+ /**
+ * Explicit device request for the child: the device the parent run is bound
+ * to. Set for an anonymous `callSubAgent` clone so it runs where its parent
+ * runs instead of re-routing through the agent-level `boundDeviceId`.
+ */
+ deviceId?: string;
/** The Group ID inherited from the parent operation, when present */
groupId?: string;
/** Instruction/prompt for the virtual sub-agent */
instruction: string;
+ /**
+ * What "this machine" means for the child: the parent run's device. Only
+ * consulted when the child's target is `local`, so a named `callAgent` target
+ * keeps its own execution target.
+ */
+ localDeviceId?: string;
/**
* Model the sub-agent should run on, resolved by the spawn site from the
* parent agent's `agencyConfig.subagent` (explicit override or the parent's
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
index 942b949b782..9aa20843082 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -11,7 +11,11 @@ const testState = vi.hoisted(() => ({
updateAgentConfigById: vi.fn(),
updateAgentRuntimeEnvConfigById: vi.fn(),
},
- chat: { activeTopicId: undefined as string | undefined, updateTopicMetadata: vi.fn() },
+ chat: {
+ activeTopicId: undefined as string | undefined,
+ topic: undefined as { metadata?: Record<string, unknown> } | undefined,
+ updateTopicMetadata: vi.fn(),
+ },
currentDeviceId: 'this-machine' as string | undefined,
effective: {
agencyConfig: undefined as Record<string, unknown> | undefined,
@@ -36,7 +40,7 @@ vi.mock('@/store/chat', () => ({
}));
vi.mock('@/store/chat/selectors', () => ({
- topicSelectors: { getTopicById: () => () => undefined },
+ topicSelectors: { getTopicById: () => (s: typeof testState.chat) => s.topic },
}));
vi.mock('@/store/device', () => ({
@@ -62,6 +66,8 @@ describe('useCommitWorkingDirectory β€” localTarget', () => {
testState.agent.updateAgentConfigById = vi.fn();
testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();
testState.chat.activeTopicId = undefined;
+ testState.chat.topic = undefined;
+ testState.chat.updateTopicMetadata = vi.fn();
testState.currentDeviceId = 'this-machine';
testState.effective = { agencyConfig: undefined, workspaceScoped: false };
});
@@ -123,3 +129,53 @@ describe('useCommitWorkingDirectory β€” localTarget', () => {
});
});
});
+
+describe('useCommitWorkingDirectory β€” topic device provenance', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testState.agent.agencyConfig = { boundDeviceId: 'device-b', executionTarget: 'device' };
+ testState.agent.agentMap = {};
+ testState.agent.localAgentWorkingDirectoryMap = {};
+ testState.chat.activeTopicId = 'topic-id';
+ // A conversation first pinned on device A, now running on device B.
+ testState.chat.topic = {
+ metadata: { boundDeviceId: 'device-a', workingDirectory: '/Users/me/repo-a' },
+ };
+ testState.chat.updateTopicMetadata = vi.fn();
+ testState.currentDeviceId = 'this-machine';
+ testState.effective = {
+ agencyConfig: { boundDeviceId: 'device-b', executionTarget: 'device' },
+ workspaceScoped: false,
+ };
+ });
+
+ it('re-stamps the topic device with the directory picked for the new device', async () => {
+ // The server only honours a topic pin on the device named by
+ // `boundDeviceId`; leaving device A there would make device B skip the
+ // directory just chosen for it and fall back to another cwd.
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit({ path: '/home/me/repo-b' });
+
+ expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith('topic-id', {
+ boundDeviceId: 'device-b',
+ workingDirectory: '/home/me/repo-b',
+ workingDirectoryConfig: { path: '/home/me/repo-b' },
+ });
+ });
+
+ it('drops the topic device together with a cleared directory', async () => {
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.clear();
+
+ // Clearing is carried as explicit `undefined` keys (a merge can't drop a
+ // key), so the key itself must be present β€” not merely unset.
+ const [topicId, patch] = testState.chat.updateTopicMetadata.mock.calls[0];
+ expect(topicId).toBe('topic-id');
+ expect(Object.keys(patch).sort()).toEqual([
+ 'boundDeviceId',
+ 'workingDirectory',
+ 'workingDirectoryConfig',
+ ]);
+ expect(patch.boundDeviceId).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 99b5499d7f1..ac8a9459c70 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -171,6 +171,11 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
priorSessionCwd !== sessionCwd &&
(!!activeTopic?.metadata?.heteroSessionId || !!scopedHeteroSessionId);
await updateTopicMetadata(activeTopicId, {
+ // The pin is a bare path that only holds on the machine it was picked
+ // for, and the server skips a topic pin whose `boundDeviceId` names a
+ // different device. Re-stamp it with every write so a conversation
+ // moved to another device keeps the directory just chosen there.
+ boundDeviceId: entry ? writeDeviceId : undefined,
...(shouldUpdateHeteroSession ? { heteroSessionId: scopedHeteroSessionId } : {}),
workingDirectory: sessionCwd,
workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,
@@ -221,6 +226,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
agencyConfig,
activeTopic,
activeTopicId,
+ currentDeviceId,
isHetero,
isPersonalDeviceTarget,
targetDeviceId,
@@ -239,6 +245,8 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
// we fall back to the agent default rather than nuking everything.
if (activeTopicId && activeTopic?.metadata?.workingDirectory) {
await updateTopicMetadata(activeTopicId, {
+ // No pin left, so no device it belongs to β€” the next run stamps its own.
+ boundDeviceId: undefined,
...(activeTopic.metadata.heteroSessionId ? { heteroSessionId: undefined } : {}),
workingDirectory: undefined,
workingDirectoryConfig: undefined,