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: label personal vs workspace scope on agent-facing device lists (#16295)

LiJiandf2c4a8e45d9
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index cb3f13fa179..aef8725c448 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -211,8 +211,10 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
// Override deviceGateway.isConfigured
const { deviceGateway } = await import('@/server/services/deviceGateway');
vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);
+ // The gateway only ever returns connected devices, each with `online: true`
+ // (see deviceGateway.queryDeviceList) β€” the snapshot filters on `online`.
mockQueryDeviceList.mockResolvedValue([
- { deviceId: 'dev-1', deviceName: 'My PC', platform: 'win32' },
+ { deviceId: 'dev-1', hostname: 'My PC', online: true, platform: 'win32' },
]);
mockGetAgentConfig.mockResolvedValue(
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 2779d6dd027..f111a4bdd74 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -107,6 +107,7 @@ import {
import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
import { ComposioService } from '@/server/services/composio';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';
@@ -2089,16 +2090,16 @@ export class AiAgentService {
const boundDeviceId = topicBoundDeviceId || agentBoundDeviceId;
if (gatewayConfigured) {
try {
- // Personal pool (user principal) βˆͺ the current workspace's shared pool
- // (workspace principal). Workspace devices are absent for non-workspace
- // runs, so this is identical to the personal-only fetch there.
- const [personalOnline, workspaceOnline] = await Promise.all([
- deviceGateway.queryDeviceList(this.userId),
- this.workspaceId
- ? deviceGateway.queryDeviceList(this.userId, this.workspaceId)
- : Promise.resolve([]),
- ]);
- onlineDevices = [...personalOnline, ...workspaceOnline];
+ // Personal pool βˆͺ the current workspace pool, DB rows βŠ• gateway online,
+ // tagged with `scope` and the user-set `friendlyName` alias (see
+ // `getScopedOnlineDevices`) so the systemRole snapshot lets the model
+ // tell a personal machine apart from its workspace-enrolled counterpart
+ // (same physical machine under both principals). Keep only live devices:
+ // downstream `onlineDeviceIds` / `deviceOnline` treat this list as the
+ // online set.
+ onlineDevices = (
+ await getScopedOnlineDevices(this.db, this.userId, this.workspaceId)
+ ).filter((d) => d.online);
log('execAgent: found %d online device(s)', onlineDevices.length);
} catch (error) {
log('execAgent: failed to query device list: %O', error);
diff --git a/apps/server/src/services/deviceGateway/scopedDevices.ts b/apps/server/src/services/deviceGateway/scopedDevices.ts
new file mode 100644
index 00000000000..352f51346f0
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/scopedDevices.ts
@@ -0,0 +1,76 @@
+import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
+import { type LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
+
+import { DeviceModel } from '@/database/models/device';
+
+import { deviceGateway } from './index';
+
+const log = debug('lobe-server:device-scope');
+
+/**
+ * Online devices an agent run may reach, scoped to a SINGLE principal and built
+ * the way the device-settings page (`device.ts` listDevices) does β€” the
+ * DB-registered rows merged with the live gateway pool.
+ *
+ * Scope is strict / mutually exclusive (mirrors `buildWorkspaceWhere`):
+ * - workspace run (`workspaceId` set) β†’ ONLY that workspace's devices. Personal
+ * devices are never exposed to a workspace conversation.
+ * - personal run (no `workspaceId`) β†’ ONLY the user's personal devices.
+ *
+ * Each device carries:
+ * - `scope` (`personal` | `workspace`): which pool it came from.
+ * - `friendlyName`: the user-set alias from the DB. The gateway only knows the
+ * raw hostname, so without this merge the device shows up as e.g.
+ * `VM-6-209-ubuntu` and the user can't recognise which machine it is.
+ *
+ * Rows include offline DB devices (`online: false`); callers that only want live
+ * devices filter on `online` (both `listOnlineDevices` and the systemRole
+ * snapshot already do).
+ *
+ * The **gateway is authoritative** for which devices are online (and enforces the
+ * scope via the principal); the DB lookup is best-effort enrichment (aliases +
+ * offline rows). A DB hiccup must NOT blank the device list / disable
+ * auto-activation, so it degrades to gateway-only on failure.
+ */
+export const getScopedOnlineDevices = async (
+ serverDB: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+): Promise<DeviceAttachment[]> => {
+ const deviceModel = new DeviceModel(serverDB, userId, workspaceId);
+ const scope: 'personal' | 'workspace' = workspaceId ? 'workspace' : 'personal';
+
+ const [rows, online] = await Promise.all([
+ (workspaceId ? deviceModel.queryWorkspaceDevices() : deviceModel.queryPersonal()).catch(
+ (error) => {
+ log('DB device lookup failed (scope=%s); using gateway only: %O', scope, error);
+ return [] as Awaited<ReturnType<typeof deviceModel.queryPersonal>>;
+ },
+ ),
+ deviceGateway.queryDeviceList(userId, workspaceId),
+ ]);
+
+ const liveById = new Map(online.map((d) => [d.deviceId, d]));
+ const seen = new Set<string>();
+ const fromDb = rows.map((row): DeviceAttachment => {
+ seen.add(row.deviceId);
+ const live = liveById.get(row.deviceId);
+ return {
+ channels: live?.channels,
+ deviceId: row.deviceId,
+ friendlyName: row.friendlyName ?? null,
+ hostname: live?.hostname ?? row.hostname ?? '',
+ lastSeen: live?.lastSeen ?? row.lastSeenAt.toISOString(),
+ online: !!live,
+ platform: live?.platform ?? row.platform ?? '',
+ scope,
+ };
+ });
+ // Online in the gateway but not yet auto-registered in the DB (no alias yet).
+ const transient = online
+ .filter((d) => !seen.has(d.deviceId))
+ .map((d): DeviceAttachment => ({ ...d, friendlyName: null, scope }));
+
+ return [...fromDb, ...transient];
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
index 1e8cb96d212..1508c9f06b4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
@@ -14,10 +14,12 @@ vi.mock('@/server/services/deviceGateway', () => ({
},
}));
-// Mock the DeviceModel so the runtime's DB-backed workspace lookup is observable.
+// Mock the DeviceModel so the runtime's DB-backed lookups are observable.
+const mockQueryPersonal = vi.fn();
const mockQueryWorkspaceDevices = vi.fn();
vi.mock('@/database/models/device', () => ({
DeviceModel: vi.fn().mockImplementation(() => ({
+ queryPersonal: mockQueryPersonal,
queryWorkspaceDevices: mockQueryWorkspaceDevices,
})),
}));
@@ -39,6 +41,8 @@ const makeServerDB = (workspaceId: string | null) =>
beforeEach(() => {
mockQueryDeviceList.mockReset();
+ mockQueryPersonal.mockReset();
+ mockQueryPersonal.mockResolvedValue([]);
mockQueryWorkspaceDevices.mockReset();
mockQueryWorkspaceDevices.mockResolvedValue([]);
});
@@ -92,11 +96,11 @@ describe('remoteDeviceRuntime', () => {
const result = await runtime.listOnlineDevices();
expect(mockQueryDeviceList).toHaveBeenCalledTimes(1);
- expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1');
+ expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1', undefined);
expect(result.success).toBe(true);
});
- it('should merge personal + workspace pools when workspaceId is in context', async () => {
+ it('lists ONLY workspace devices in a workspace run (personal devices excluded)', async () => {
const context: ToolExecutionContext = {
toolManifestMap: {},
userId: 'user-1',
@@ -126,17 +130,16 @@ describe('remoteDeviceRuntime', () => {
const result = await runtime.listOnlineDevices();
- expect(mockQueryDeviceList).toHaveBeenCalledTimes(2);
- expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1');
+ // Strict isolation: only the workspace pool is queried; the personal pool
+ // is never fetched for a workspace run.
+ expect(mockQueryDeviceList).toHaveBeenCalledTimes(1);
expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1', 'ws-1');
expect(result.success).toBe(true);
const parsed = JSON.parse(result.content);
- expect(parsed).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ deviceId: 'd-personal' }),
- expect.objectContaining({ deviceId: 'd-workspace' }),
- ]),
- );
+ expect(parsed).toEqual([
+ expect.objectContaining({ deviceId: 'd-workspace', scope: 'workspace' }),
+ ]);
+ expect(parsed.some((d: { deviceId: string }) => d.deviceId === 'd-personal')).toBe(false);
});
it('recovers the workspace scope from the running agent when context.workspaceId is missing', async () => {
@@ -198,10 +201,10 @@ describe('remoteDeviceRuntime', () => {
await runtime.listOnlineDevices();
expect(mockQueryDeviceList).toHaveBeenCalledTimes(1);
- expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1');
+ expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1', undefined);
});
- it('surfaces a DB-registered workspace device merged with gateway online status (no duplicate)', async () => {
+ it('surfaces a DB-registered workspace device (with its alias) merged with gateway online status (no duplicate)', async () => {
const context: ToolExecutionContext = {
serverDB: makeServerDB('ws-1'),
toolManifestMap: {},
@@ -211,7 +214,7 @@ describe('remoteDeviceRuntime', () => {
const gatewayWorkspaceDevice = {
deviceId: 'd-ws',
- hostname: 'shared-mac',
+ hostname: 'VM-7-11-ubuntu',
lastSeen: '2024-01-02',
online: true,
platform: 'linux',
@@ -222,7 +225,8 @@ describe('remoteDeviceRuntime', () => {
mockQueryWorkspaceDevices.mockResolvedValue([
{
deviceId: 'd-ws',
- hostname: 'shared-mac',
+ friendlyName: 'Build Server',
+ hostname: 'VM-7-11-ubuntu',
lastSeenAt: new Date('2024-01-01'),
platform: 'linux',
},
@@ -234,7 +238,51 @@ describe('remoteDeviceRuntime', () => {
const parsed = JSON.parse(result.content);
const wsEntries = parsed.filter((d: { deviceId: string }) => d.deviceId === 'd-ws');
expect(wsEntries).toHaveLength(1);
- expect(wsEntries[0]).toMatchObject({ deviceId: 'd-ws', online: true });
+ // The user-set alias is surfaced so the model/user can recognise it.
+ expect(wsEntries[0]).toMatchObject({
+ deviceId: 'd-ws',
+ friendlyName: 'Build Server',
+ online: true,
+ scope: 'workspace',
+ });
+ });
+
+ it('still returns gateway devices when the DB enrichment lookup fails', async () => {
+ // The gateway is authoritative for "online"; a DB failure must degrade to
+ // gateway-only (no alias) rather than blanking the list / disabling
+ // auto-activation.
+ const context: ToolExecutionContext = {
+ serverDB: makeServerDB('ws-1'),
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ };
+
+ mockQueryWorkspaceDevices.mockRejectedValue(new Error('db down'));
+ mockQueryDeviceList.mockImplementation((_userId: string, wsId?: string) =>
+ Promise.resolve(
+ wsId
+ ? [
+ {
+ deviceId: 'd-ws',
+ hostname: 'VM-7-11-ubuntu',
+ lastSeen: '2024-01-02',
+ online: true,
+ platform: 'linux',
+ },
+ ]
+ : [],
+ ),
+ );
+
+ const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
+ const result = await runtime.listOnlineDevices();
+
+ expect(result.success).toBe(true);
+ const parsed = JSON.parse(result.content);
+ expect(parsed).toEqual([
+ expect.objectContaining({ deviceId: 'd-ws', online: true, scope: 'workspace' }),
+ ]);
});
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
index f1578d5897d..8167cfb4e1e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
@@ -1,19 +1,17 @@
import {
+ type DeviceAttachment,
RemoteDeviceExecutionRuntime,
RemoteDeviceIdentifier,
} from '@lobechat/builtin-tool-remote-device';
import debug from 'debug';
-import { DeviceModel } from '@/database/models/device';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
// Enable with DEBUG=lobe-server:remote-device (works in prod via the env var).
-// Traces how the remote-device tool resolves its workspace scope and which
-// device pools it reads, so a "lists personal devices instead of workspace"
-// report can be pinned to a concrete layer (missing scope vs empty gateway pool).
const log = debug('lobe-server:remote-device');
export const remoteDeviceRuntime: ServerRuntimeRegistration = {
@@ -24,17 +22,14 @@ export const remoteDeviceRuntime: ServerRuntimeRegistration = {
const userId = context.userId;
const serverDB = context.serverDB;
- const agentId = context.agentId;
- const contextWorkspaceId = context.workspaceId;
return new RemoteDeviceExecutionRuntime({
// Personal pool (user principal) βˆͺ the current workspace's shared pool
// (workspace principal), surfaced the same way the device-settings page
- // (`device.ts` listDevices) does: the DB-registered workspace rows merged
- // with the live gateway pool. Returning only the raw gateway pool meant a
- // workspace device the DB knows about could silently drop out β€” diverging
- // from the settings page and from `list_document`, which are DB-backed.
- queryDeviceList: async () => {
+ // (`device.ts` listDevices) does β€” DB rows merged with the live gateway
+ // pool, tagged with `scope` and the user-set `friendlyName` alias so the
+ // model can tell the workspace device apart from the personal one.
+ queryDeviceList: async (): Promise<DeviceAttachment[]> => {
// Resolve the workspace scope used to decide which workspace device pool
// to include. Recovers from the running agent when the run-scoped
// workspaceId was lost on the way to this tool call β€” see
@@ -42,52 +37,28 @@ export const remoteDeviceRuntime: ServerRuntimeRegistration = {
// degrade to the personal-only pool.
const workspaceId = await resolveRunWorkspaceId(context);
- const deviceModel = serverDB ? new DeviceModel(serverDB, userId, workspaceId) : undefined;
-
- const [personal, workspaceOnline, workspaceRows] = await Promise.all([
- deviceGateway.queryDeviceList(userId),
- workspaceId ? deviceGateway.queryDeviceList(userId, workspaceId) : Promise.resolve([]),
- workspaceId && deviceModel ? deviceModel.queryWorkspaceDevices() : Promise.resolve([]),
- ]);
-
- // DB rows βŠ• gateway online: `online` is driven by the gateway's live
- // channels (the DB does not track liveness), but a workspace device the
- // gateway pool momentarily omits is still surfaced (offline) rather than
- // vanishing entirely.
- const onlineById = new Map(workspaceOnline.map((d) => [d.deviceId, d]));
- const seen = new Set<string>();
- const workspaceMerged = workspaceRows.map((row) => {
- seen.add(row.deviceId);
- const live = onlineById.get(row.deviceId);
- return {
- channels: live?.channels,
- deviceId: row.deviceId,
- hostname: live?.hostname ?? row.hostname ?? '',
- lastSeen: live?.lastSeen ?? row.lastSeenAt.toISOString(),
- online: !!live,
- platform: live?.platform ?? row.platform ?? '',
- };
- });
- // Gateway-reported workspace devices not yet auto-registered in the DB.
- const workspaceTransient = workspaceOnline.filter((d) => !seen.has(d.deviceId));
+ // Without a DB handle we cannot merge aliases / DB rows; fall back to the
+ // raw gateway pool for the active scope (workspace runs never include
+ // personal devices), still tagged with scope.
+ if (!serverDB) {
+ const scope = workspaceId ? ('workspace' as const) : ('personal' as const);
+ const online = await deviceGateway.queryDeviceList(userId, workspaceId);
+ return online.map((d) => ({ ...d, scope }));
+ }
+ const devices = await getScopedOnlineDevices(serverDB, userId, workspaceId);
log(
- 'scope: contextWorkspaceId=%o resolvedWorkspaceId=%o agentId=%o | gateway personal=%d workspace=%d | db workspace rows=%d',
- contextWorkspaceId,
+ 'listOnlineDevices: workspaceId=%o -> %d device(s): %o',
workspaceId,
- agentId,
- personal.length,
- workspaceOnline.length,
- workspaceRows.length,
+ devices.length,
+ devices.map((d) => ({
+ id: d.deviceId,
+ name: d.friendlyName ?? d.hostname,
+ online: d.online,
+ scope: d.scope,
+ })),
);
- log(
- ' deviceIds: gatewayPersonal=%o gatewayWorkspace=%o dbWorkspace=%o',
- personal.map((d) => d.deviceId),
- workspaceOnline.map((d) => d.deviceId),
- workspaceRows.map((d) => d.deviceId),
- );
-
- return [...personal, ...workspaceMerged, ...workspaceTransient];
+ return devices;
},
});
},
diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
index 553570cfac0..8e5faeacdb6 100644
--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
@@ -48,7 +48,7 @@ export class RemoteDeviceExecutionRuntime {
}
return {
- content: `Device "${target.hostname}" (${target.platform}) activated successfully. Local System tools are now available.`,
+ content: `Device "${target.friendlyName || target.hostname}" (${target.platform}) activated successfully. Local System tools are now available.`,
state: {
activatedDevice: target,
metadata: { activeDeviceId: args.deviceId },
diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
index 39fce13d916..15d60938498 100644
--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
@@ -5,12 +5,28 @@ export interface DeviceChannel {
connectionId: string;
}
+/** Which principal pool a device belongs to. */
+export type DeviceScope = 'personal' | 'workspace';
+
export interface DeviceAttachment {
/** Live connections backing this device; absent for offline devices. */
channels?: DeviceChannel[];
deviceId: string;
+ /**
+ * User-set alias from the device-settings page. The gateway only knows the raw
+ * `hostname`; this is merged in from the DB so the device shows the name the
+ * user recognises. Null when never aliased.
+ */
+ friendlyName?: string | null;
hostname: string;
lastSeen: string;
online: boolean;
platform: string;
+ /**
+ * Whether this device is the caller's personal machine or a device enrolled
+ * into the active workspace. Lets the model tell otherwise-identical devices
+ * apart (the same physical machine can be connected under both principals) and
+ * pick the workspace one when asked.
+ */
+ scope?: DeviceScope;
}
diff --git a/packages/builtin-tool-remote-device/src/systemRole.ts b/packages/builtin-tool-remote-device/src/systemRole.ts
index f3f31c5fa21..dc8dda85e64 100644
--- a/packages/builtin-tool-remote-device/src/systemRole.ts
+++ b/packages/builtin-tool-remote-device/src/systemRole.ts
@@ -7,10 +7,14 @@ export const generateSystemPrompt = (devices?: DeviceAttachment[]): string => {
const deviceSection = onlineDevicesPrompt(
onlineDevices.map((d) => ({
+ hostname: d.hostname,
id: d.deviceId,
lastSeen: d.lastSeen,
- name: d.hostname,
+ // Prefer the user-set alias so the listed name matches what the user sees
+ // in device settings; fall back to the raw hostname.
+ name: d.friendlyName || d.hostname,
os: d.platform,
+ scope: d.scope,
})),
);
@@ -29,6 +33,7 @@ ${deviceSection}
- If no devices are online, inform the user that they need to have their desktop application running and connected.
- When only one device is online, activate it directly without asking the user to choose.
- When multiple devices are online, present the list and let the user choose which device to activate.
+- Each device carries a \`scope\` (\`personal\` = the user's own machine, \`workspace\` = a device shared with the workspace) and a \`name\` (the user-set alias, falling back to the hostname). A workspace conversation only lists workspace devices and a personal conversation only personal ones, so the list is already scoped to this context β€” surface the \`name\` and \`scope\` when listing so the user can confirm which machine it is.
</guidelines>
`;
};
diff --git a/packages/prompts/src/prompts/remoteDevice/index.ts b/packages/prompts/src/prompts/remoteDevice/index.ts
index 8823ac20e50..4cc41f0ad5c 100644
--- a/packages/prompts/src/prompts/remoteDevice/index.ts
+++ b/packages/prompts/src/prompts/remoteDevice/index.ts
@@ -1,12 +1,23 @@
export interface DeviceItem {
+ /** Raw machine hostname; rendered alongside `name` when an alias differs. */
+ hostname?: string;
id: string;
lastSeen?: string;
+ /** Display name β€” the user-set alias when present, else the hostname. */
name: string;
os: string;
+ /** 'personal' = the user's own machine, 'workspace' = enrolled into the workspace. */
+ scope?: string;
}
export const devicePrompt = (device: DeviceItem) => {
- const attrs = [`id="${device.id}"`, `name="${device.name}"`, `os="${device.os}"`];
+ const attrs = [`id="${device.id}"`, `name="${device.name}"`];
+ // Surface the raw hostname too, but only when it adds information beyond `name`.
+ if (device.hostname && device.hostname !== device.name) {
+ attrs.push(`hostname="${device.hostname}"`);
+ }
+ attrs.push(`os="${device.os}"`);
+ if (device.scope) attrs.push(`scope="${device.scope}"`);
if (device.lastSeen) attrs.push(`last-seen="${device.lastSeen}"`);
return ` <device ${attrs.join(' ')} />`;
};