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: list workspace devices in remote-device tool + add scope tracing (#16280)

LiJian81d1e011c39a
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
index 192fe624782..4716a68beab 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -142,6 +142,38 @@ describe('localSystemRuntime', () => {
undefined,
);
});
+
+ it('recovers the workspace scope from the running agent when context.workspaceId is missing', async () => {
+ // Minimal drizzle-like chain resolving the agent's workspace_id.
+ const serverDB = {
+ select: () => ({
+ from: () => ({
+ where: () => ({ limit: () => Promise.resolve([{ workspaceId: 'ws-1' }]) }),
+ }),
+ }),
+ } as any;
+ const context: ToolExecutionContext = {
+ activeDeviceId: 'device-ws',
+ agentId: 'agt-1',
+ serverDB,
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
+
+ const proxy = localSystemRuntime.factory(context);
+ const apiName = LocalSystemManifest.api[0].name;
+
+ await proxy[apiName]({ path: '/tmp' });
+
+ // The follow-up filesystem call routes to the recovered workspace pool.
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-ws', userId: 'user-1', workspaceId: 'ws-1' }),
+ expect.objectContaining({ apiName, identifier: LocalSystemIdentifier }),
+ undefined,
+ );
+ });
});
describe('working directory injection', () => {
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 05685894b6d..1e8cb96d212 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
@@ -14,11 +14,33 @@ vi.mock('@/server/services/deviceGateway', () => ({
},
}));
+// Mock the DeviceModel so the runtime's DB-backed workspace lookup is observable.
+const mockQueryWorkspaceDevices = vi.fn();
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(() => ({
+ queryWorkspaceDevices: mockQueryWorkspaceDevices,
+ })),
+}));
+
// Import after mock setup
const { remoteDeviceRuntime } = await import('../remoteDevice');
+/** Minimal drizzle-like chain that resolves the agent's workspace_id lookup. */
+const makeServerDB = (workspaceId: string | null) =>
+ ({
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ limit: () => Promise.resolve(workspaceId === null ? [] : [{ workspaceId }]),
+ }),
+ }),
+ }),
+ }) as any;
+
beforeEach(() => {
mockQueryDeviceList.mockReset();
+ mockQueryWorkspaceDevices.mockReset();
+ mockQueryWorkspaceDevices.mockResolvedValue([]);
});
describe('remoteDeviceRuntime', () => {
@@ -116,5 +138,103 @@ describe('remoteDeviceRuntime', () => {
]),
);
});
+
+ it('recovers the workspace scope from the running agent when context.workspaceId is missing', async () => {
+ const context: ToolExecutionContext = {
+ agentId: 'agt-1',
+ serverDB: makeServerDB('ws-1'),
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ const personalDevice = {
+ deviceId: 'd-personal',
+ hostname: 'laptop',
+ lastSeen: '2024-01-01',
+ online: true,
+ platform: 'darwin',
+ };
+ const workspaceDevice = {
+ deviceId: 'd-workspace',
+ hostname: 'shared-mac',
+ lastSeen: '2024-01-01',
+ online: true,
+ platform: 'darwin',
+ };
+ mockQueryDeviceList.mockImplementation((_userId: string, wsId?: string) =>
+ Promise.resolve(wsId ? [workspaceDevice] : [personalDevice]),
+ );
+
+ const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
+
+ const result = await runtime.listOnlineDevices();
+
+ // The recovered workspace id drives the workspace gateway pool query.
+ expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1', 'ws-1');
+ const parsed = JSON.parse(result.content);
+ expect(parsed).toEqual(
+ expect.arrayContaining([expect.objectContaining({ deviceId: 'd-workspace' })]),
+ );
+ });
+
+ it('stays personal-only when the running agent has no workspace', async () => {
+ const context: ToolExecutionContext = {
+ agentId: 'agt-personal',
+ serverDB: makeServerDB(null),
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+ mockQueryDeviceList.mockResolvedValue([
+ {
+ deviceId: 'd-personal',
+ hostname: 'laptop',
+ lastSeen: '2024-01-01',
+ online: true,
+ platform: 'darwin',
+ },
+ ]);
+
+ const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
+ await runtime.listOnlineDevices();
+
+ expect(mockQueryDeviceList).toHaveBeenCalledTimes(1);
+ expect(mockQueryDeviceList).toHaveBeenCalledWith('user-1');
+ });
+
+ it('surfaces a DB-registered workspace device merged with gateway online status (no duplicate)', async () => {
+ const context: ToolExecutionContext = {
+ serverDB: makeServerDB('ws-1'),
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ };
+
+ const gatewayWorkspaceDevice = {
+ deviceId: 'd-ws',
+ hostname: 'shared-mac',
+ lastSeen: '2024-01-02',
+ online: true,
+ platform: 'linux',
+ };
+ mockQueryDeviceList.mockImplementation((_userId: string, wsId?: string) =>
+ Promise.resolve(wsId ? [gatewayWorkspaceDevice] : []),
+ );
+ mockQueryWorkspaceDevices.mockResolvedValue([
+ {
+ deviceId: 'd-ws',
+ hostname: 'shared-mac',
+ lastSeenAt: new Date('2024-01-01'),
+ platform: 'linux',
+ },
+ ]);
+
+ const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
+ const result = await runtime.listOnlineDevices();
+
+ 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 });
+ });
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 65ab6db8d0d..042526391fa 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -6,6 +6,7 @@ import {
import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
/**
@@ -48,6 +49,15 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
throw new Error('activeDeviceId is required for Local System device proxy execution');
}
+ // Resolve the workspace scope the same way `remote-device` does, recovering
+ // it from the running agent when the run-scoped `context.workspaceId` was
+ // lost (see `resolveRunWorkspaceId`). Without this, a workspace device the
+ // model just activated via listOnlineDevices would be addressed under the
+ // personal principal and every filesystem/shell call against it would miss.
+ // Resolved once, shared by every api call in this step.
+ let workspaceIdPromise: Promise<string | undefined> | undefined;
+ const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));
+
const proxy: Record<string, (args: any) => Promise<any>> = {};
for (const api of LocalSystemManifest.api) {
@@ -67,8 +77,8 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
userId: context.userId!,
// Workspace devices live under the `workspace:<id>` principal in
// the gateway, so the relay needs the workspaceId to address the
- // right DO pool. Personal device runs leave it undefined.
- workspaceId: context.workspaceId,
+ // right DO pool. Personal device runs resolve to undefined.
+ workspaceId: await getDeviceWorkspaceId(),
},
{
apiName: api.name,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
index cee8ff7e579..f1578d5897d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
@@ -2,11 +2,20 @@ import {
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 { 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 = {
factory: (context) => {
if (!context.userId) {
@@ -14,20 +23,71 @@ export const remoteDeviceRuntime: ServerRuntimeRegistration = {
}
const userId = context.userId;
- const workspaceId = context.workspaceId;
+ 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). Mirrors execAgent's onlineDevices fetch so the
- // tool refresh stays consistent with the systemRole snapshot β€” otherwise
- // a workspace-bound chat would see its workspace device in the system
- // prompt but lose it the moment the model calls listOnlineDevices.
+ // (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 () => {
- const [personal, workspace] = await Promise.all([
+ // 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
+ // `resolveRunWorkspaceId`. Otherwise a workspace agent would silently
+ // 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([]),
]);
- return [...personal, ...workspace];
+
+ // 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));
+
+ log(
+ 'scope: contextWorkspaceId=%o resolvedWorkspaceId=%o agentId=%o | gateway personal=%d workspace=%d | db workspace rows=%d',
+ contextWorkspaceId,
+ workspaceId,
+ agentId,
+ personal.length,
+ workspaceOnline.length,
+ workspaceRows.length,
+ );
+ 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];
},
});
},
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts
new file mode 100644
index 00000000000..436786e7515
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts
@@ -0,0 +1,44 @@
+import debug from 'debug';
+import { eq } from 'drizzle-orm';
+
+import { agents } from '@/database/schemas';
+
+import { type ToolExecutionContext } from '../types';
+
+const log = debug('lobe-server:device-scope');
+
+type DeviceScopeContext = Pick<ToolExecutionContext, 'agentId' | 'serverDB' | 'workspaceId'>;
+
+/**
+ * The workspace scope a device tool call should run under: the run-scoped
+ * `context.workspaceId`, or β€” when that was lost on the way to this tool call
+ * (some dispatch / resume paths do not thread it through to
+ * `ToolExecutionContext`) β€” the running agent's durable `workspace_id`.
+ *
+ * Both device runtimes resolve scope through this single path so a run stays
+ * consistent: `remote-device` lists/activates the workspace device, and the
+ * `local-system` filesystem/shell calls that follow route to the same
+ * `workspace:<id>` gateway pool instead of silently falling back to the personal
+ * pool. Unscoped lookup by id on purpose: the run already authorized this agent,
+ * we only read which workspace it belongs to.
+ */
+export const resolveRunWorkspaceId = async (
+ context: DeviceScopeContext,
+): Promise<string | undefined> => {
+ if (context.workspaceId) return context.workspaceId;
+
+ const { agentId, serverDB } = context;
+ if (!agentId || !serverDB) return undefined;
+
+ try {
+ const [row] = await serverDB
+ .select({ workspaceId: agents.workspaceId })
+ .from(agents)
+ .where(eq(agents.id, agentId))
+ .limit(1);
+ return row?.workspaceId ?? undefined;
+ } catch (error) {
+ log('failed to recover workspaceId from agent %s: %O', agentId, error);
+ return undefined;
+ }
+};