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(hetero): spawn device CLI runs in the source repo, not the active worktree (#21312)

AmAzing-6644518c4408
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
index f86caf9ecc8..df0d1ed3965 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -1,5 +1,5 @@
import type { ExecAgentResult } from '@lobechat/types';
-import { getWorkingDirEffectivePath } from '@lobechat/types';
+import { getWorkingDirSourcePath } from '@lobechat/types';
import debug from 'debug';
import { DeviceModel } from '@/database/models/device';
@@ -127,7 +127,16 @@ export const dispatchToCliDevice = async (
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
workingDirByDevice: agentConfig.agencyConfig?.workingDirByDevice,
});
- const deviceCwd = getWorkingDirEffectivePath(deviceCwdConfig);
+ // Local CLIs (Claude Code, Codex) key their sessions by cwd, so the spawn cwd
+ // stays on the SOURCE repo, mirroring the client's `conversationLifecycle`.
+ // The active worktree is a record the agent may already have deleted:
+ // spawning in it would lose the session, or fail the run outright once the
+ // directory is gone. The agent is told about it in the system context instead.
+ const deviceCwd = getWorkingDirSourcePath(deviceCwdConfig);
+ const worktreePath = deviceCwdConfig?.git?.activeWorktree;
+ const worktreeContext = worktreePath
+ ? { activeWorktree: { path: worktreePath, sourceDirectory: deviceCwd } }
+ : {};
// An unbound topic has no pinned cwd yet: the directory was only
// recorded at agent level (`workingDirByDevice`) when no topic existed.
@@ -145,12 +154,14 @@ export const dispatchToCliDevice = async (
// (which describes an ephemeral /workspace + pre-cloned repos and would mislead
// the agent). The spawned CLI already receives deviceCwd as its actual cwd.
const deviceSystemContext = buildRemoteDeviceHeteroContext({
+ ...worktreeContext,
agentSystemContext,
conversationHistory: resumeSessionId ? undefined : conversationHistory,
});
const deviceResumeFallbackSystemContext =
resumeSessionId && conversationHistory
? buildRemoteDeviceHeteroContext({
+ ...worktreeContext,
agentSystemContext,
conversationHistory,
})
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
index 40264d7d655..9837460083e 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
@@ -493,6 +493,38 @@ describe('dispatchHeteroAgent — local CLI agents', () => {
expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });
});
+ it('spawns in the source repo and names the active worktree in the context', async () => {
+ // The agent created this worktree last turn and may have removed it since:
+ // spawning in it failed every later turn with working_directory_not_found.
+ const workingDirectoryConfig = {
+ git: { activeWorktree: '/repo-wt-21058' },
+ path: '/repo',
+ repoType: 'github' as const,
+ };
+ const { deps, topicModel } = createDeps();
+ topicModel.findById.mockResolvedValue({
+ metadata: { boundDeviceId: 'dev-1', workingDirectory: '/repo', workingDirectoryConfig },
+ });
+
+ await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ }),
+ createInput('claude-code'),
+ );
+
+ const dispatched = mocks.dispatchAgentRun.mock.calls[0][0];
+ expect(dispatched.cwd).toBe('/repo');
+ expect(dispatched.systemContext).toContain('/repo-wt-21058');
+ // The worktree stays on the topic as the selected one; only the spawn cwd moved.
+ expect(deps.bindTopicWorkingDirectory).toHaveBeenCalledWith(
+ expect.objectContaining({ config: workingDirectoryConfig }),
+ );
+ });
+
it('never routes a device-only provider to the cloud sandbox', async () => {
const { deps } = createDeps();
diff --git a/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.test.ts b/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.test.ts
index eac3b0eb2c7..81b431e2db1 100644
--- a/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.test.ts
@@ -34,4 +34,21 @@ describe('buildRemoteDeviceHeteroContext', () => {
expect(result.indexOf('AGENT_CTX')).toBeLessThan(result.indexOf('<previous_conversation>'));
expect(result).not.toContain('## Workspace');
});
+
+ it('names the active worktree and the source repo to fall back to', () => {
+ const result = buildRemoteDeviceHeteroContext({
+ activeWorktree: { path: '/repo-wt', sourceDirectory: '/repo' },
+ })!;
+ expect(result).toContain('<active_worktree>');
+ expect(result).toContain('selected git worktree is /repo-wt');
+ expect(result).toContain('If it no longer exists, work in /repo.');
+ });
+
+ it('says nothing about a worktree that is the source repo itself', () => {
+ expect(
+ buildRemoteDeviceHeteroContext({
+ activeWorktree: { path: '/repo', sourceDirectory: '/repo' },
+ }),
+ ).toBeUndefined();
+ });
});
diff --git a/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.ts b/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.ts
index c11a3118376..428214c4875 100644
--- a/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.ts
+++ b/apps/server/src/services/heterogeneousAgent/remoteDeviceHeteroContext.ts
@@ -11,7 +11,8 @@ import type { ConversationHistoryEntry } from './cloudHeteroContext';
* applies to a device run, so injecting it would actively mislead the agent.
*
* What remains is only what's genuinely useful on a device:
- * - the agent-level static context (workspace conventions / rules), and
+ * - the agent-level static context (workspace conventions / rules),
+ * - the selected git worktree, which is not the process cwd, and
* - prior conversation turns when a session is resumed without a native session
* file.
*
@@ -19,6 +20,13 @@ import type { ConversationHistoryEntry } from './cloudHeteroContext';
* can omit the extra content block entirely.
*/
export function buildRemoteDeviceHeteroContext(params: {
+ /**
+ * The topic's selected worktree (`workingDirectoryConfig.git.activeWorktree`)
+ * and the source repo the CLI is spawned in. The spawn cwd stays on the source
+ * so the CLI's per-cwd session survives, which leaves this as the only way the
+ * agent learns where the conversation's work lives.
+ */
+ activeWorktree?: { path: string; sourceDirectory?: string };
/** Static systemContext from HeterogeneousProviderConfig.systemContext (agent-level). */
agentSystemContext?: string;
/**
@@ -27,7 +35,7 @@ export function buildRemoteDeviceHeteroContext(params: {
*/
conversationHistory?: ConversationHistoryEntry[];
}): string | undefined {
- const { agentSystemContext, conversationHistory } = params;
+ const { activeWorktree, agentSystemContext, conversationHistory } = params;
const parts: string[] = [];
@@ -36,6 +44,17 @@ export function buildRemoteDeviceHeteroContext(params: {
parts.push(agentSystemContext.trim());
}
+ // --- Selected worktree ---
+ // The server cannot see the device's filesystem, so the agent is the one to
+ // check that the worktree still exists (it may have removed it last turn).
+ if (activeWorktree && activeWorktree.path !== activeWorktree.sourceDirectory) {
+ const { path, sourceDirectory } = activeWorktree;
+ const fallback = sourceDirectory ? ` If it no longer exists, work in ${sourceDirectory}.` : '';
+ parts.push(
+ `<active_worktree>\nThis conversation's selected git worktree is ${path}. Your process starts in the source repository, so read, edit and run git commands in the worktree.${fallback}\n</active_worktree>`,
+ );
+ }
+
// --- Previous conversation context (injected when session was reset) ---
// Mirrors buildCloudHeteroContext truncation: user 1 KB, assistant 2 KB.
if (conversationHistory && conversationHistory.length > 0) {