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-runtime): inject local-system template vars for regular chat (#15087)

Arvin Xu7cad53d87808
diff --git a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
index 0692ff91866..15f0a052efd 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -263,7 +263,14 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
describe('Web UI scenario (no botContext/discordContext)', () => {
- it('should NOT auto-activate even with one device online', async () => {
+ // LOBE-9378: regular chat used to leave activeDeviceId undefined when no
+ // device was bound, which caused the local-system system prompt's
+ // {{workingDirectory}} / {{hostname}} placeholders to reach the LLM as
+ // literals. The model would then waste the first N steps groping for cwd.
+ // Now we auto-activate when exactly one device is online β€” multi-device
+ // users still need to bind explicitly, since picking one by recency
+ // would be a guess that could route tool calls to the wrong machine.
+ it('should auto-activate the only online device', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
@@ -273,6 +280,32 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
expect(mockCreateOperation).toHaveBeenCalled();
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
+ });
+
+ it('should NOT auto-activate when multiple devices are online', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'List my files',
+ });
+
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ expect(createOpArgs.activeDeviceId).toBeUndefined();
+ });
+
+ it('should NOT auto-activate when no devices are online', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'List my files',
+ });
+
const createOpArgs = mockCreateOperation.mock.calls[0][0];
expect(createOpArgs.activeDeviceId).toBeUndefined();
});
@@ -391,9 +424,15 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
);
});
+ // Verifies topic-stored metadata.boundDeviceId is NOT silently reused as
+ // the runtime bound device. Setup: topic.metadata says device-002, but the
+ // only online device is device-001. If the topic metadata were reused as
+ // boundDeviceId, activeDeviceId would be undefined (device-002 is offline).
+ // After LOBE-9378 auto-activate, we instead pick the most-recent online
+ // device (device-001) β€” proving the topic's stale metadata wasn't honored.
it('should not reuse topic boundDeviceId when no explicit deviceId is provided', async () => {
mockDeviceProxy.isConfigured = true;
- mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
topicMock.findById.mockResolvedValue({ metadata: { boundDeviceId: 'device-002' } });
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(
@@ -421,7 +460,8 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
const createOpArgs = mockCreateOperation.mock.calls[0][0];
- expect(createOpArgs.activeDeviceId).toBeUndefined();
+ expect(createOpArgs.activeDeviceId).not.toBe('device-002');
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
});
it('should keep explicit topic binding when the bound device is offline', async () => {
@@ -487,12 +527,18 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(createOpArgs.activeDeviceId).toBe('device-001');
});
+ // Mirrors the "should not reuse topic boundDeviceId" test above with a
+ // different mock shape. Topic metadata stores device-002, but only
+ // device-001 is online; if topic metadata leaked into boundDeviceId,
+ // activeDeviceId would be undefined (since device-002 is offline). The
+ // post-LOBE-9378 auto-activate picks device-001 instead, confirming the
+ // stale topic.metadata.boundDeviceId path is dead.
it('should not reuse topic metadata bound device when no deviceId is supplied', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
topicMock.findById.mockResolvedValue({
id: 'topic-1',
- metadata: { boundDeviceId: 'device-001' },
+ metadata: { boundDeviceId: 'device-002' },
});
await service.execAgent({
@@ -502,7 +548,8 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
const createOpArgs = mockCreateOperation.mock.calls[0][0];
- expect(createOpArgs.activeDeviceId).toBeUndefined();
+ expect(createOpArgs.activeDeviceId).not.toBe('device-002');
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
});
it('should not update topic metadata when a new deviceId is provided for existing topic', async () => {
diff --git a/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index 9649b6965a9..33a24a826a0 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -208,6 +208,7 @@ describe('AiAgentService.execAgent - device tool pipeline (LOBE-5636)', () => {
expect(mockCreateServerAgentToolsEngine).toHaveBeenCalledTimes(1);
const params = mockCreateServerAgentToolsEngine.mock.calls[0][1];
expect(params.deviceContext).toEqual({
+ autoActivated: true,
boundDeviceId: undefined,
deviceOnline: true,
gatewayConfigured: true,
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index ae04aa0ebb6..51a8177a354 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -1176,17 +1176,25 @@ export class AiAgentService {
// bypassing the engine's enabledToolIds exclusion. Skipping the
// assignment here closes that bypass at the source.
//
- // 1. If this run explicitly requested a device and that device is online, use it
- // 2. Otherwise, if the current topic has a bound device and it is online, use that
- // 3. Otherwise, fall back to the agent-level bound device when it is online
- // 4. Otherwise, in IM/Bot scenarios, auto-activate only when exactly one device is online
+ // Resolution order (LOBE-9378):
+ // 1. boundDeviceId (topic-bound > agent-bound): use if online; if offline,
+ // respect the explicit choice and stay unrouted β€” don't silently fall
+ // back to a different device, that would surprise the user.
+ // 2. No bound device: auto-activate only when EXACTLY ONE device is
+ // online. Multi-device users must bind explicitly β€” picking by
+ // recency / first-online would be a guess that could route tool calls
+ // to the wrong machine. This applies uniformly to regular chat and
+ // IM/Bot β€” the previous "regular-chat does nothing" path was the bug
+ // behind LOBE-9378 (the local-system system prompt's
+ // `{{workingDirectory}}` reached the LLM as a literal, wasting the
+ // first N steps groping for cwd).
activeDeviceId = !canUseDevice
? undefined
: boundDeviceId
? onlineDevices.some((device) => device.deviceId === boundDeviceId)
? boundDeviceId
: undefined
- : (discordContext || botContext) && onlineDevices.length === 1
+ : onlineDevices.length === 1
? onlineDevices[0].deviceId
: undefined;
@@ -1409,33 +1417,44 @@ export class AiAgentService {
};
}
- // 9.4. Fetch device system info for placeholder variable replacement
- let deviceSystemInfo: Record<string, string> = {};
- if (activeDeviceId) {
+ // 9.4. Fetch device system info for placeholder variable replacement.
+ //
+ // Decoupled from activeDeviceId routing (LOBE-9378): pulled into a helper
+ // so the device whose info populates the template (`{{hostname}}`,
+ // `{{workingDirectory}}`, etc.) is a separate decision from the device
+ // that tool calls route to. Today they're aligned β€” but future policy
+ // changes (e.g., showing last-known info for an offline bound device)
+ // belong in this helper, not in the activeDeviceId resolution block.
+ const fetchDeviceSystemInfoForTemplate = async (
+ deviceId: string | undefined,
+ ): Promise<Record<string, string>> => {
+ if (!deviceId) return {};
try {
- const systemInfo = await deviceProxy.queryDeviceSystemInfo(this.userId, activeDeviceId);
- if (systemInfo) {
- const activeDevice = onlineDevices.find((d) => d.deviceId === activeDeviceId);
- deviceSystemInfo = {
- arch: systemInfo.arch,
- desktopPath: systemInfo.desktopPath,
- documentsPath: systemInfo.documentsPath,
- downloadsPath: systemInfo.downloadsPath,
- homePath: systemInfo.homePath,
- hostname: activeDevice?.hostname ?? 'unknown',
- musicPath: systemInfo.musicPath,
- picturesPath: systemInfo.picturesPath,
- platform: activeDevice?.platform ?? 'unknown',
- userDataPath: systemInfo.userDataPath,
- videosPath: systemInfo.videosPath,
- workingDirectory: systemInfo.workingDirectory,
- };
- log('execAgent: fetched device system info for %s', activeDeviceId);
- }
+ const systemInfo = await deviceProxy.queryDeviceSystemInfo(this.userId, deviceId);
+ if (!systemInfo) return {};
+ const device = onlineDevices.find((d) => d.deviceId === deviceId);
+ log('execAgent: fetched device system info for %s', deviceId);
+ return {
+ arch: systemInfo.arch,
+ desktopPath: systemInfo.desktopPath,
+ documentsPath: systemInfo.documentsPath,
+ downloadsPath: systemInfo.downloadsPath,
+ homePath: systemInfo.homePath,
+ hostname: device?.hostname ?? 'unknown',
+ musicPath: systemInfo.musicPath,
+ picturesPath: systemInfo.picturesPath,
+ platform: device?.platform ?? 'unknown',
+ userDataPath: systemInfo.userDataPath,
+ videosPath: systemInfo.videosPath,
+ workingDirectory: systemInfo.workingDirectory,
+ };
} catch (error) {
log('execAgent: failed to fetch device system info: %O', error);
+ return {};
}
- }
+ };
+
+ const deviceSystemInfo = await fetchDeviceSystemInfoForTemplate(activeDeviceId);
// 9.5. Build Agent Management context
// - availableAgents is injected whenever the user is in auto mode (so the supervisor