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: harden device connection presence (#19352)

Neko3b0d29cd54b9
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index 8eb8f3553aa..cb597650fde 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -347,6 +347,9 @@ importers:
../../packages/device-gateway-client:
dependencies:
+ '@lobechat/types':
+ specifier: workspace:*
+ version: link:../types
ws:
specifier: ^8.21.0
version: 8.21.0
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
index 8a80fa10dc6..269a0cf446a 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
@@ -70,23 +70,28 @@ describe('assertWorkspaceRootApproved', () => {
});
describe('assertWorkspaceDeviceVisible', () => {
- const mockHiddenModel = (hiddenIds: string[]) =>
+ const mockWorkspaceModel = (row: object | undefined) =>
({
- queryWorkspaceHiddenDeviceIds: vi.fn().mockResolvedValue(hiddenIds),
+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(row),
}) as unknown as DeviceModel;
+ /** @example A visible registered device remains addressable by workspace RPCs. */
it('allows a device the caller can see', async () => {
- const model = mockHiddenModel(['someone-elses-private']);
+ const model = mockWorkspaceModel({ deviceId: 'public-dev' });
await expect(assertWorkspaceDeviceVisible(model, 'public-dev')).resolves.toBeUndefined();
});
- it('allows a transient device with no DB row (empty hidden set)', async () => {
- const model = mockHiddenModel([]);
- await expect(assertWorkspaceDeviceVisible(model, 'transient-dev')).resolves.toBeUndefined();
+ /** @example A Gateway-only ghost is not authorized after its workspace row is removed. */
+ it('rejects a transient device with no workspace registry row', async () => {
+ const model = mockWorkspaceModel(undefined);
+ await expect(assertWorkspaceDeviceVisible(model, 'transient-dev')).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
});
+ /** @example Another member's private device is indistinguishable from an unknown device. */
it("rejects another member's private device with NOT_FOUND", async () => {
- const model = mockHiddenModel(['someone-elses-private']);
+ const model = mockWorkspaceModel(undefined);
await expect(
assertWorkspaceDeviceVisible(model, 'someone-elses-private'),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 1185441f8c7..e5603778e1f 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -25,6 +25,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { signWorkspaceDeviceToken } from '@/libs/trpc/utils/internalJwt';
import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGateway';
+import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';
import { preserveWorkspaceCache } from './deviceWorkingDirs';
import { assertWorkspaceDeviceVisible, assertWorkspaceRootApproved } from './deviceWorkspaceGuard';
@@ -860,34 +861,23 @@ export const deviceRouter = router({
* device may therefore hold multiple channels (e.g. desktop app + CLI both
* connected at once), and `online` is simply "has at least one live channel".
*
- * A union, not just the DB rows: a device may be connected but not yet in
- * the DB (old client that predates auto-register, or registration still in
- * flight). Those are surfaced as transient entries so the picker never loses
- * a currently-reachable device during rollout.
+ * Personal scope is a union rather than only DB rows: auto-registration may
+ * briefly lag a live socket. Workspace scope fails closed on visible registry
+ * rows because the row is the enrollment and authorization boundary.
*/
listDevices: deviceProcedure.query(async ({ ctx }): Promise<DeviceListItem[]> => {
const wsId = ctx.workspaceId;
// Personal devices resolve under the user principal; workspace devices under
// the `workspace:<id>` principal (a separate gateway pool). Fetch both.
- // `hiddenWorkspaceIds` (other members' private enrollments) is needed because
- // the gateway pool is visibility-blind: without it a private device would
- // resurface below as an online "ghost".
- const [
- personalRows,
- workspaceRows,
- hiddenWorkspaceIds,
- sharedRows,
- personalOnline,
- workspaceOnline,
- ] = await Promise.all([
- ctx.deviceModel.queryPersonal(),
- wsId ? ctx.deviceModel.queryWorkspaceDevices() : Promise.resolve([]),
- wsId ? ctx.deviceModel.queryWorkspaceHiddenDeviceIds() : Promise.resolve([]),
- ctx.deviceModel.querySharedWorkspaceDevices(),
- deviceGateway.queryDeviceList(ctx.userId),
- wsId ? deviceGateway.queryDeviceList(ctx.userId, wsId) : Promise.resolve([]),
- ]);
+ const [personalRows, workspaceRows, sharedRows, personalOnline, workspaceOnline] =
+ await Promise.all([
+ ctx.deviceModel.queryPersonal(),
+ wsId ? ctx.deviceModel.queryWorkspaceDevices() : Promise.resolve([]),
+ ctx.deviceModel.querySharedWorkspaceDevices(),
+ deviceGateway.queryDeviceList(ctx.userId),
+ wsId ? deviceGateway.queryDeviceList(ctx.userId, wsId) : Promise.resolve([]),
+ ]);
// Shares the caller created from their personal device list, grouped by the
// source personal deviceId — attached to personal rows below so the list can
@@ -952,14 +942,10 @@ export const deviceRouter = router({
rows: Awaited<ReturnType<typeof ctx.deviceModel.queryPersonal>>,
onlineList: DeviceAttachment[],
scope: DeviceScope,
- hiddenIds: string[] = [],
): DeviceListItem[] => {
- const hidden = new Set(hiddenIds);
+ const registeredDeviceIds = new Set(rows.map((device) => device.deviceId));
const channelsByDevice = new Map<string, DeviceChannel[]>();
- for (const conn of onlineList) {
- // Another member's private device: online in the workspace gateway pool
- // but not visible to the caller — must not leak as a ghost row.
- if (hidden.has(conn.deviceId)) continue;
+ for (const conn of filterAuthorizedDevicePresence(registeredDeviceIds, onlineList, scope)) {
channelsByDevice.set(conn.deviceId, toChannels(conn));
}
@@ -1012,7 +998,10 @@ export const deviceRouter = router({
};
});
- // Online but not yet persisted — transient until the client auto-registers.
+ // Personal clients auto-register immediately before opening their
+ // socket, so preserve their brief Gateway-first race. Workspace rows are
+ // authorization: a Gateway-only socket may be a stale process that missed
+ // Unshare, and must stay hidden and ineligible.
const ghosts = [...channelsByDevice.entries()]
.filter(([deviceId]) => !seen.has(deviceId))
.map(([deviceId, channels]): DeviceListItem => ({
@@ -1043,7 +1032,7 @@ export const deviceRouter = router({
// filtering preserves order, so one pass serves every surface.
return sortDevicesByActivity([
...buildItems(personalRows, personalOnline, 'personal'),
- ...buildItems(workspaceRows, workspaceOnline, 'workspace', hiddenWorkspaceIds),
+ ...buildItems(workspaceRows, workspaceOnline, 'workspace'),
]);
}),
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
index f99d99a4f0f..e0eaa464772 100644
--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
@@ -62,15 +62,25 @@ export const assertWorkspaceRootApproved = async (
* `deviceId` input: a workspace-scoped call against a device hidden from the
* caller fails closed with the same NOT_FOUND an unknown device produces.
*
- * Personal deviceIds are never in the hidden set (different hash domain), and
- * transient gateway-only devices (no DB row) are public by definition.
+ * The visible registry row is also the workspace execution authority. A live
+ * Gateway connection without that row can be a stale process that missed an
+ * Unshare RPC, so it must fail exactly like an unknown or private device.
+ *
+ * Use when:
+ * - A workspace-scoped RPC accepts a client-supplied logical device ID
+ *
+ * Expects:
+ * - `deviceModel` is already scoped to the authorized workspace and caller
+ *
+ * Returns:
+ * - Nothing for a visible registered device; otherwise throws `NOT_FOUND`
*/
export const assertWorkspaceDeviceVisible = async (
deviceModel: DeviceModel,
deviceId: string,
): Promise<void> => {
- const hiddenIds = await deviceModel.queryWorkspaceHiddenDeviceIds();
- if (hiddenIds.includes(deviceId)) {
+ const device = await deviceModel.findWorkspaceDeviceById(deviceId);
+ if (!device) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
}
};
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index aba894c6c44..4a1987df069 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -574,7 +574,18 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await expect(
service.execAgent({ agentId: 'agent-1', prompt: 'Run a command' }),
- ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ ).rejects.toMatchObject({
+ cause: {
+ data: {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-001',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ },
+ },
+ code: 'PRECONDITION_FAILED',
+ });
expect(mockCreateOperation).not.toHaveBeenCalled();
expect(mockMessageUpdate).toHaveBeenCalledWith(
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 6b2b785bed5..0a162fd3b8c 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -17,6 +17,7 @@ const {
mockPluginQuery,
mockQueryDeviceList,
mockQueryDeviceSystemInfo,
+ mockQueryWorkspaceDevices,
} = vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
mockCreateServerAgentToolsEngine: vi.fn(),
@@ -28,6 +29,7 @@ const {
mockPluginQuery: vi.fn(),
mockQueryDeviceList: vi.fn(),
mockQueryDeviceSystemInfo: vi.fn(),
+ mockQueryWorkspaceDevices: vi.fn(),
}));
vi.mock('@/libs/trusted-client', () => ({
@@ -53,16 +55,15 @@ vi.mock('@/database/models/agent', () => ({
})),
}));
-// Empty DB-side device rows so getScopedOnlineDevices falls through to the
-// gateway list as transient devices. Returning [] (not rejecting) for
-// queryWorkspaceHiddenDeviceIds is required — a failed/null hidden lookup
-// suppresses all workspace-scope transients.
+// This mock previously kept every DB-side device query empty so gateway devices
+// became transient rows. Workspace transients are now intentionally rejected;
+// expose the workspace query so tests can register authorized workspace devices.
vi.mock('@/database/models/device', () => ({
DeviceModel: vi.fn().mockImplementation(() => ({
findByDeviceId: vi.fn().mockResolvedValue(undefined),
findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),
queryPersonal: vi.fn().mockResolvedValue([]),
- queryWorkspaceDevices: vi.fn().mockResolvedValue([]),
+ queryWorkspaceDevices: mockQueryWorkspaceDevices,
queryWorkspaceHiddenDeviceIds: vi.fn().mockResolvedValue([]),
})),
}));
@@ -203,6 +204,7 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
});
mockQueryDeviceList.mockResolvedValue([]);
mockQueryDeviceSystemInfo.mockResolvedValue(null);
+ mockQueryWorkspaceDevices.mockResolvedValue([]);
mockPluginQuery.mockResolvedValue([]);
mockGenerateToolsDetailed.mockReturnValue({ enabledToolIds: [], tools: [] });
mockGetEnabledPluginManifests.mockReturnValue(new Map());
@@ -631,14 +633,27 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
workingDirectory: '/',
};
+ /** @example A registered live workspace device supplies scoped system information. */
it('should query system info with workspace id and inject into createOperation for workspace devices', async () => {
const workspaceId = 'ws-1';
service = new AiAgentService(mockDb, userId, { workspaceId });
const { deviceGateway } = await import('@/server/services/deviceGateway');
vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);
- // Single online device under the workspace principal → auto-activates.
- // getScopedOnlineDevices tags scope from the workspaceId argument.
+ // ROOT CAUSE:
+ //
+ // This test previously supplied only Gateway presence. Workspace authorization now requires
+ // a matching database enrollment, so the transient device was correctly filtered before
+ // system-info lookup. Register the device in the DB mock and keep Gateway as liveness truth.
+ mockQueryWorkspaceDevices.mockResolvedValue([
+ {
+ deviceId: 'ws-dev-1',
+ friendlyName: null,
+ hostname: 'workspace-mac',
+ lastSeenAt: new Date('2026-09-09T00:00:00.000Z'),
+ platform: 'darwin',
+ },
+ ]);
mockQueryDeviceList.mockResolvedValue([
{ deviceId: 'ws-dev-1', hostname: 'workspace-mac', online: true, platform: 'darwin' },
]);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index e6b4378ac46..ed301737bea 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -16,6 +16,7 @@ const {
mockGetHeterogeneousResumeSessionId,
mockMessageCreate,
mockMessageQuery,
+ mockMessageUpdate,
mockResolveAttachmentsByFileIds,
mockSpawnHeteroSandbox,
mockIngestAttachment,
@@ -33,6 +34,7 @@ const {
mockIngestAttachment: vi.fn(),
mockMessageCreate: vi.fn(),
mockMessageQuery: vi.fn(),
+ mockMessageUpdate: vi.fn().mockResolvedValue({}),
mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),
mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),
mockResolveAttachmentsByFileIds: vi.fn(),
@@ -87,7 +89,7 @@ vi.mock('@/database/models/message', () => ({
getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
query: mockMessageQuery,
- update: vi.fn().mockResolvedValue({}),
+ update: mockMessageUpdate,
})),
}));
@@ -212,6 +214,10 @@ vi.mock('@/server/services/deviceGateway', () => ({
},
}));
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({
buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,
}));
@@ -517,6 +523,52 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
});
+ it('returns structured retry context when a device disappears between discovery and dispatch', async () => {
+ heteroAgentConfig.model = 'amp';
+ heteroAgentConfig.provider = 'amp';
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'amp' },
+ } as any;
+ mockDispatchAgentRun.mockResolvedValueOnce({
+ error: 'DEVICE_NOT_FOUND',
+ errorData: {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'personal',
+ },
+ success: false,
+ });
+
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Use Amp on my device',
+ });
+
+ // ROOT CAUSE:
+ //
+ // A device can disconnect after discovery succeeds but before the Gateway accepts dispatch.
+ // The old result kept only the error string, so an outer agent could not distinguish a safe
+ // presence retry from an execution failure. The structured transport data now survives the
+ // Agent result and persisted message envelope.
+ expect(result.errorData).toEqual({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'personal',
+ });
+ expect(mockMessageUpdate).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ error: expect.objectContaining({
+ body: expect.objectContaining({ code: 'DEVICE_NOT_FOUND', retryable: true }),
+ }),
+ }),
+ );
+ });
+
it('resumes Amp natively without loading or injecting fallback history', async () => {
mockGetHeterogeneousResumeSessionId.mockResolvedValue('amp-thread-existing');
heteroAgentConfig.model = 'amp';
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index bf846dcf6fd..6e91dc4982d 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -7,6 +7,7 @@ import {
isRemoteHeterogeneousType,
} from '@lobechat/heterogeneous-agents';
import type {
+ DeviceUnavailableErrorData,
ErrorType,
ExecAgentResult,
HeterogeneousTopicPin,
@@ -36,6 +37,7 @@ import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLi
import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
import { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
@@ -94,6 +96,7 @@ const finalizeHeteroDispatchError = async (
agentId?: string;
assistantMessageId: string;
detail: string;
+ errorData?: DeviceUnavailableErrorData;
/**
* Client error type. Defaults to the generic `ServerAgentRuntimeError`; pass a
* dedicated `ChatErrorType` (e.g. `DeviceGatewayNotConfigured`) so the web
@@ -109,6 +112,7 @@ const finalizeHeteroDispatchError = async (
agentId,
assistantMessageId,
detail,
+ errorData,
errorType = ChatErrorType.ServerAgentRuntimeError,
message,
operationId,
@@ -119,7 +123,7 @@ const finalizeHeteroDispatchError = async (
// end event below re-reads a message that already carries the error.
await deps.messageModel.update(assistantMessageId, {
content: '',
- error: { body: { detail }, message, type: errorType },
+ error: { body: { detail, ...errorData }, message, type: errorType },
});
// 1b. Finalize the run through CompletionLifecycle's single entry — the SAME
@@ -699,40 +703,54 @@ export const dispatchHeteroAgent = async (
// lh connect only handles tool_call_request (not agent_run_request),
// so we use executeToolCall with the runHeteroTask tool instead of dispatchAgentRun.
- const result = await deviceGateway.executeToolCall(
- {
- deviceId: remoteDeviceId,
- userId: remoteDeviceUserId,
- workspaceId: remoteDeviceWorkspaceId,
- },
- {
- apiName: 'runHeteroTask',
- arguments: JSON.stringify({
- agentId: resolvedAgentId,
- agentType: heteroType,
- cwd: undefined,
- operationId,
- parentOperationId: topicStartOwnerOperationId,
- platformAgentId: agentConfig.agencyConfig?.heterogeneousProvider?.platformAgentId,
- prompt,
- taskId: operationId,
- topicId,
- // Scope notify callbacks to the same workspace as the dispatched
- // topic so agentNotify can resolve the workspace-owned topic.
- // Without this the device's notify call falls back to personal
- // mode and TopicModel.findById returns NOT_FOUND.
- workspaceId: deps.workspaceId,
- }),
- identifier: 'runHeteroTask',
- },
- 120_000, // hetero tasks can take longer than the default 30 s
+ const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
+ deps.db,
+ deps.userId,
+ remoteDeviceId,
+ remoteDeviceWorkspaceId,
);
+ const result = authorizationError
+ ? {
+ content: 'The workspace device is no longer registered or visible for this run.',
+ error: 'DEVICE_NOT_FOUND',
+ errorData: authorizationError,
+ success: false,
+ }
+ : await deviceGateway.executeToolCall(
+ {
+ deviceId: remoteDeviceId,
+ userId: remoteDeviceUserId,
+ workspaceId: remoteDeviceWorkspaceId,
+ },
+ {
+ apiName: 'runHeteroTask',
+ arguments: JSON.stringify({
+ agentId: resolvedAgentId,
+ agentType: heteroType,
+ cwd: undefined,
+ operationId,
+ parentOperationId: topicStartOwnerOperationId,
+ platformAgentId: agentConfig.agencyConfig?.heterogeneousProvider?.platformAgentId,
+ prompt,
+ taskId: operationId,
+ topicId,
+ // Scope notify callbacks to the same workspace as the dispatched
+ // topic so agentNotify can resolve the workspace-owned topic.
+ // Without this the device's notify call falls back to personal
+ // mode and TopicModel.findById returns NOT_FOUND.
+ workspaceId: deps.workspaceId,
+ }),
+ identifier: 'runHeteroTask',
+ },
+ 120_000, // hetero tasks can take longer than the default 30 s
+ );
if (!result.success) {
log('execAgent: remote hetero dispatch failed: %s', result.error);
await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: result.error ?? 'Device dispatch failed',
+ errorData: result.errorData,
errorType: resolveHeteroDispatchErrorType(result.error),
message: humanizeHeteroDispatchError(result.error),
operationId,
@@ -744,6 +762,7 @@ export const dispatchHeteroAgent = async (
autoStarted: false,
createdAt: new Date().toISOString(),
error: result.error,
+ errorData: result.errorData,
message: 'Remote hetero agent dispatch failed',
operationId,
status: 'error',
@@ -880,27 +899,36 @@ export const dispatchHeteroAgent = async (
})
: undefined;
- const result = await deviceGateway.dispatchAgentRun({
- ...heteroParams,
- args: heteroExecArgs,
- cwd: deviceCwd,
- deviceId: dispatchDeviceId,
- resumeFallbackSystemContext: deviceResumeFallbackSystemContext,
- systemContext: deviceSystemContext,
- // Route to the workspace pool when this is a workspace device; the
- // operation JWT stays member-scoped (the run belongs to the member).
- workspaceId: dispatchWorkspaceId,
- // Topic scope for device-side heteroIngest/heteroFinish. Distinct
- // from the routing workspace above: a workspace topic on a personal
- // device still has to write back under `deps.workspaceId`.
- ingestWorkspaceId: deps.workspaceId,
- });
+ const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
+ deps.db,
+ deps.userId,
+ dispatchDeviceId,
+ dispatchWorkspaceId,
+ );
+ const result = authorizationError
+ ? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }
+ : await deviceGateway.dispatchAgentRun({
+ ...heteroParams,
+ args: heteroExecArgs,
+ cwd: deviceCwd,
+ deviceId: dispatchDeviceId,
+ resumeFallbackSystemContext: deviceResumeFallbackSystemContext,
+ systemContext: deviceSystemContext,
+ // Route to the workspace pool when this is a workspace device; the
+ // operation JWT stays member-scoped (the run belongs to the member).
+ workspaceId: dispatchWorkspaceId,
+ // Topic scope for device-side heteroIngest/heteroFinish. Distinct
+ // from the routing workspace above: a workspace topic on a personal
+ // device still has to write back under `deps.workspaceId`.
+ ingestWorkspaceId: deps.workspaceId,
+ });
if (!result.success) {
log('execAgent: hetero device dispatch failed: %s', result.error);
await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: result.error ?? 'Device dispatch failed',
+ errorData: result.errorData,
errorType: resolveHeteroDispatchErrorType(result.error),
message: humanizeHeteroDispatchError(result.error),
operationId,
@@ -912,6 +940,7 @@ export const dispatchHeteroAgent = async (
autoStarted: false,
createdAt: new Date().toISOString(),
error: result.error,
+ errorData: result.errorData,
message: 'Hetero agent device dispatch failed',
operationId,
status: 'error',
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 7b314985997..8571fffc647 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -19,6 +19,7 @@ import type {
ToolSource,
} from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
+import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
import type { ChatTopicBotContext, RequestTrigger } from '@lobechat/types';
import { getActivePluginIds } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
@@ -691,9 +692,17 @@ export const discoverTools = async (
// before tool/runtime preparation so no operation can start elsewhere.
if (
isFixedDeviceTarget &&
+ boundDeviceId &&
resolveToolMode(agentConfig.chatConfig ?? undefined) !== 'chat' &&
executionPlan.kind !== 'device'
) {
+ const errorData: DeviceUnavailableErrorData = {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: boundDeviceId,
+ retryable: true,
+ scope: deps.workspaceId ? 'workspace' : 'personal',
+ ...(deps.workspaceId ? { workspaceId: deps.workspaceId } : {}),
+ };
const detail =
executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline'
? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
@@ -701,13 +710,13 @@ export const discoverTools = async (
await deps.messageModel.update(assistantMessageId, {
content: '',
error: {
- body: { detail },
+ body: { detail, ...errorData },
message: 'Fixed agent device unavailable',
type: 'ServerAgentRuntimeError',
},
});
throw new TRPCError({
- cause: { data: { code: 'FixedAgentDeviceUnavailable' } },
+ cause: { data: errorData },
code: 'PRECONDITION_FAILED',
message: detail,
});
diff --git a/apps/server/src/services/deviceGateway/authorizedToolCall.test.ts b/apps/server/src/services/deviceGateway/authorizedToolCall.test.ts
new file mode 100644
index 00000000000..89f2d8c3214
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/authorizedToolCall.test.ts
@@ -0,0 +1,41 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ executeToolCall: vi.fn(),
+ resolveAuthorizationFailure: vi.fn(),
+}));
+
+vi.mock('./dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: mocks.resolveAuthorizationFailure,
+}));
+vi.mock('./index', () => ({ deviceGateway: { executeToolCall: mocks.executeToolCall } }));
+
+const { executeAuthorizedDeviceToolCall } = await import('./authorizedToolCall');
+const serverDB = {} as LobeChatDatabase;
+const params = { deviceId: 'device-1', userId: 'user-1', workspaceId: 'workspace-1' };
+const toolCall = { apiName: 'readFile', arguments: '{}', identifier: 'local-system' };
+
+describe('executeAuthorizedDeviceToolCall', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ /** @example A stale workspace socket receives no new work after Unshare. */
+ it('fails before Gateway dispatch when registry authority was removed', async () => {
+ mocks.resolveAuthorizationFailure.mockResolvedValue({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+
+ const result = await executeAuthorizedDeviceToolCall(serverDB, params, toolCall);
+
+ expect(result).toMatchObject({
+ error: 'DEVICE_NOT_FOUND',
+ errorData: { code: 'DEVICE_NOT_FOUND', retryable: true },
+ success: false,
+ });
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/authorizedToolCall.ts b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
new file mode 100644
index 00000000000..fe366f90bf8
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
@@ -0,0 +1,41 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { DeviceToolCallResult } from '@lobechat/device-gateway-client';
+
+import { resolveDeviceDispatchAuthorizationFailure } from './dispatchAuthorization';
+import { deviceGateway } from './index';
+
+/**
+ * Executes a device tool call after a last-moment workspace registry check.
+ *
+ * Use when:
+ * - An Agent runtime dispatches new work to its active device
+ *
+ * Expects:
+ * - `workspaceId`, when present, is the same principal used during target selection
+ *
+ * Returns:
+ * - The Gateway result, or immediate structured `DEVICE_NOT_FOUND` after Unshare
+ */
+export const executeAuthorizedDeviceToolCall = async (
+ serverDB: LobeChatDatabase | undefined,
+ params: { deviceId: string; operationId?: string; userId: string; workspaceId?: string },
+ toolCall: { apiName: string; arguments: string; identifier: string },
+ timeout?: number,
+): Promise<DeviceToolCallResult> => {
+ const errorData = await resolveDeviceDispatchAuthorizationFailure(
+ serverDB,
+ params.userId,
+ params.deviceId,
+ params.workspaceId,
+ );
+ if (errorData) {
+ return {
+ content: 'The workspace device is no longer registered or visible for this run.',
+ error: 'DEVICE_NOT_FOUND',
+ errorData,
+ success: false,
+ };
+ }
+
+ return deviceGateway.executeToolCall(params, toolCall, timeout);
+};
diff --git a/apps/server/src/services/deviceGateway/dispatchAuthorization.test.ts b/apps/server/src/services/deviceGateway/dispatchAuthorization.test.ts
new file mode 100644
index 00000000000..923a99bea6c
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/dispatchAuthorization.test.ts
@@ -0,0 +1,55 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ findWorkspaceDeviceById: vi.fn() }));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(() => ({
+ findWorkspaceDeviceById: mocks.findWorkspaceDeviceById,
+ })),
+}));
+
+const { resolveDeviceDispatchAuthorizationFailure } = await import('./dispatchAuthorization');
+const serverDB = {} as LobeChatDatabase;
+
+describe('resolveDeviceDispatchAuthorizationFailure', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ /** @example Personal dispatch does not have a workspace registry boundary. */
+ it('allows personal dispatch without a registry lookup', async () => {
+ await expect(
+ resolveDeviceDispatchAuthorizationFailure(serverDB, 'user-1', 'device-1'),
+ ).resolves.toBeUndefined();
+ expect(mocks.findWorkspaceDeviceById).not.toHaveBeenCalled();
+ });
+
+ /** @example A visible workspace registration permits the selected device dispatch. */
+ it('allows workspace dispatch while its registry row remains visible', async () => {
+ mocks.findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'device-1' });
+
+ await expect(
+ resolveDeviceDispatchAuthorizationFailure(serverDB, 'user-1', 'device-1', 'workspace-1'),
+ ).resolves.toBeUndefined();
+ expect(mocks.findWorkspaceDeviceById).toHaveBeenCalledWith('device-1');
+ });
+
+ /** @example Unshare revokes a previously selected target before its next tool call. */
+ it('returns structured failure after the workspace row is removed', async () => {
+ // ROOT CAUSE:
+ //
+ // Target discovery was checked once, but a later tool call reused activeDeviceId directly.
+ // Unshare could delete the registry row while a stale socket remained, allowing new work.
+ // The dispatch boundary now rechecks the visible workspace row before every new call.
+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);
+
+ await expect(
+ resolveDeviceDispatchAuthorizationFailure(serverDB, 'user-1', 'device-1', 'workspace-1'),
+ ).resolves.toEqual({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/dispatchAuthorization.ts b/apps/server/src/services/deviceGateway/dispatchAuthorization.ts
new file mode 100644
index 00000000000..b47c62183f8
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/dispatchAuthorization.ts
@@ -0,0 +1,40 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { DeviceUnavailableErrorData } from '@lobechat/types';
+
+import { DeviceModel } from '@/database/models/device';
+
+/**
+ * Rechecks workspace registry authority immediately before device dispatch.
+ *
+ * Use when:
+ * - A previously selected workspace device is about to receive new work
+ * - Unshare may have raced with a long-running agent operation
+ *
+ * Expects:
+ * - The caller has already passed workspace membership checks
+ * - `workspaceId` is the principal used for Gateway routing
+ *
+ * Returns:
+ * - Structured `DEVICE_NOT_FOUND` context when the visible registry row no longer exists
+ */
+export const resolveDeviceDispatchAuthorizationFailure = async (
+ serverDB: LobeChatDatabase | undefined,
+ userId: string,
+ deviceId: string,
+ workspaceId?: string,
+): Promise<DeviceUnavailableErrorData | undefined> => {
+ if (!workspaceId) return undefined;
+
+ const device = serverDB
+ ? await new DeviceModel(serverDB, userId, workspaceId).findWorkspaceDeviceById(deviceId)
+ : undefined;
+ if (device) return undefined;
+
+ return {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId,
+ retryable: true,
+ scope: 'workspace',
+ workspaceId,
+ };
+};
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index c3cfe42bd61..6628f5560f5 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -38,6 +38,7 @@ import type {
DeviceProjectFileIndexResult,
DeviceProjectFileSearchResult,
DeviceRenameProjectFileResult,
+ DeviceUnavailableErrorData,
DeviceWriteProjectFileResult,
HeterogeneousAgentModelCatalog,
ProjectSkillMeta,
@@ -1396,7 +1397,7 @@ export class DeviceGateway {
workspaceId?: string;
/** Topic/run workspace forwarded to the device for hetero ingest. */
ingestWorkspaceId?: string;
- }): Promise<{ error?: string; success: boolean }> {
+ }): Promise<{ error?: string; errorData?: DeviceUnavailableErrorData; success: boolean }> {
const client = this.getClient();
if (!client) return { error: 'GATEWAY_NOT_CONFIGURED', success: false };
diff --git a/apps/server/src/services/deviceGateway/scopedDevicePresence.test.ts b/apps/server/src/services/deviceGateway/scopedDevicePresence.test.ts
new file mode 100644
index 00000000000..51d9abbdd95
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/scopedDevicePresence.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ filterAuthorizedDevicePresence,
+ isGatewayOnlyDevicePresenceAllowed,
+} from './scopedDevicePresence';
+
+const onlineDevices = [{ deviceId: 'registered' }, { deviceId: 'gateway-only' }];
+
+describe('filterAuthorizedDevicePresence', () => {
+ /** @example Personal auto-registration may briefly lag behind Gateway presence. */
+ it('retains Gateway-only devices in personal scope', () => {
+ expect(
+ filterAuthorizedDevicePresence(new Set(['registered']), onlineDevices, 'personal'),
+ ).toEqual(onlineDevices);
+ });
+
+ /** @example Unshare removes authority even when a stale workspace socket remains connected. */
+ it('excludes Gateway-only devices in workspace scope', () => {
+ // ROOT CAUSE:
+ //
+ // Workspace Gateway presence used to create an executable transient device without a DB row.
+ // If Unshare deleted the row while a stale process remained connected, the device resurfaced.
+ // The shared policy now treats workspace rows as authority and Gateway only as liveness.
+ expect(
+ filterAuthorizedDevicePresence(new Set(['registered']), onlineDevices, 'workspace'),
+ ).toEqual([{ deviceId: 'registered' }]);
+ expect(isGatewayOnlyDevicePresenceAllowed('workspace')).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/scopedDevicePresence.ts b/apps/server/src/services/deviceGateway/scopedDevicePresence.ts
new file mode 100644
index 00000000000..5056bce3d13
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/scopedDevicePresence.ts
@@ -0,0 +1,39 @@
+import type { DeviceScope } from '@lobechat/types';
+
+/**
+ * Reports whether a scope may surface a live device before its registry row exists.
+ *
+ * Use when:
+ * - A caller can avoid fetching Gateway presence that cannot be authorized
+ *
+ * Expects:
+ * - `scope` is the principal being queried
+ *
+ * Returns:
+ * - `true` only for the personal auto-registration compatibility window
+ */
+export const isGatewayOnlyDevicePresenceAllowed = (scope: DeviceScope): boolean =>
+ scope === 'personal';
+
+/**
+ * Filters Gateway presence through the registry authority for one device scope.
+ *
+ * Use when:
+ * - Merging live Gateway connections into device registry rows
+ * - Deciding whether Gateway-only devices may enter a picker or runtime
+ *
+ * Expects:
+ * - `registeredDeviceIds` contains rows visible to the authorized caller
+ * - `onlineDevices` contains only connections from the requested principal
+ *
+ * Returns:
+ * - Every personal connection, or only registered workspace connections
+ */
+export const filterAuthorizedDevicePresence = <T extends { deviceId: string }>(
+ registeredDeviceIds: ReadonlySet<string>,
+ onlineDevices: T[],
+ scope: DeviceScope,
+): T[] =>
+ isGatewayOnlyDevicePresenceAllowed(scope)
+ ? onlineDevices
+ : onlineDevices.filter((device) => registeredDeviceIds.has(device.deviceId));
diff --git a/apps/server/src/services/deviceGateway/scopedDevices.test.ts b/apps/server/src/services/deviceGateway/scopedDevices.test.ts
new file mode 100644
index 00000000000..3b500168113
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/scopedDevices.test.ts
@@ -0,0 +1,105 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ queryDeviceList: vi.fn(),
+ queryPersonal: vi.fn(),
+ queryWorkspaceDevices: vi.fn(),
+}));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(() => ({
+ queryPersonal: mocks.queryPersonal,
+ queryWorkspaceDevices: mocks.queryWorkspaceDevices,
+ })),
+}));
+
+vi.mock('./index', () => ({
+ deviceGateway: { queryDeviceList: mocks.queryDeviceList },
+}));
+
+const { getScopedOnlineDevices } = await import('./scopedDevices');
+
+const serverDB = {} as unknown as LobeChatDatabase;
+const row = (deviceId: string) => ({
+ deviceId,
+ friendlyName: null,
+ hostname: `${deviceId}-db`,
+ lastSeenAt: new Date('2026-09-09T00:00:00.000Z'),
+ platform: 'darwin',
+});
+const live = (deviceId: string) => ({
+ channels: [
+ { channel: 'desktop', connectedAt: '2026-09-09T01:00:00.000Z', connectionId: 'conn-1' },
+ ],
+ deviceId,
+ hostname: `${deviceId}-live`,
+ lastSeen: '2026-09-09T01:00:00.000Z',
+ online: true,
+ platform: 'darwin',
+});
+
+describe('getScopedOnlineDevices', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.queryPersonal.mockResolvedValue([]);
+ mocks.queryWorkspaceDevices.mockResolvedValue([]);
+ mocks.queryDeviceList.mockResolvedValue([]);
+ });
+
+ /**
+ * @example A stale workspace socket cannot recreate a device after Unshare removed its row.
+ */
+ it('keeps registered workspace rows and excludes gateway-only workspace devices', async () => {
+ // ROOT CAUSE:
+ //
+ // Workspace presence used to be authoritative even without a registry row.
+ // A process that missed Unshare therefore resurfaced as an executable ghost.
+ //
+ // Before: registered rows plus every Gateway-only workspace device.
+ // After: workspace rows are authoritative; Gateway only supplies liveness.
+ mocks.queryWorkspaceDevices.mockResolvedValue([
+ row('registered-online'),
+ row('registered-offline'),
+ ]);
+ mocks.queryDeviceList.mockResolvedValue([live('registered-online'), live('gateway-ghost')]);
+
+ const result = await getScopedOnlineDevices(serverDB, 'user-1', 'workspace-1');
+
+ expect(result.map((device) => device.deviceId)).toEqual([
+ 'registered-online',
+ 'registered-offline',
+ ]);
+ expect(result[0]).toMatchObject({ online: true, scope: 'workspace' });
+ expect(result[1]).toMatchObject({ online: false, scope: 'workspace' });
+ });
+
+ /**
+ * @example A workspace registry outage cannot turn an unverified socket into an authorized device.
+ */
+ it('fails closed when workspace registry lookup fails', async () => {
+ mocks.queryWorkspaceDevices.mockRejectedValue(new Error('database unavailable'));
+ mocks.queryDeviceList.mockResolvedValue([live('gateway-only')]);
+
+ const result = await getScopedOnlineDevices(serverDB, 'user-1', 'workspace-1');
+
+ expect(result).toEqual([]);
+ });
+
+ /**
+ * @example Personal auto-registration remains backward compatible during its short race window.
+ */
+ it('retains gateway-only personal devices as transient entries', async () => {
+ mocks.queryDeviceList.mockResolvedValue([live('personal-transient')]);
+
+ const result = await getScopedOnlineDevices(serverDB, 'user-1');
+
+ expect(result).toEqual([
+ expect.objectContaining({
+ deviceId: 'personal-transient',
+ online: true,
+ scope: 'personal',
+ }),
+ ]);
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/scopedDevices.ts b/apps/server/src/services/deviceGateway/scopedDevices.ts
index 3fffc797347..9a9a65148d3 100644
--- a/apps/server/src/services/deviceGateway/scopedDevices.ts
+++ b/apps/server/src/services/deviceGateway/scopedDevices.ts
@@ -6,6 +6,7 @@ import debug from 'debug';
import { DeviceModel } from '@/database/models/device';
import { deviceGateway } from './index';
+import { filterAuthorizedDevicePresence } from './scopedDevicePresence';
const log = debug('lobe-server:device-scope');
@@ -29,10 +30,20 @@ const log = debug('lobe-server:device-scope');
* 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.
+ * The **gateway is authoritative** for liveness, while the database is
+ * authoritative for workspace enrollment and visibility. Personal lookups may
+ * degrade to Gateway-only transient devices during auto-registration; workspace
+ * lookups fail closed when their registry query is unavailable.
+ *
+ * Use when:
+ * - Agent planning or a server runtime needs devices eligible in one principal
+ * - Device metadata must combine persistent registration with current presence
+ *
+ * Expects:
+ * - `workspaceId`, when present, has already passed an authorized workspace scope
+ *
+ * Returns:
+ * - Registered devices with scoped liveness, plus personal-only transient devices
*/
export const getScopedOnlineDevices = async (
serverDB: LobeChatDatabase,
@@ -42,30 +53,24 @@ export const getScopedOnlineDevices = async (
const deviceModel = new DeviceModel(serverDB, userId, workspaceId);
const scope: 'personal' | 'workspace' = workspaceId ? 'workspace' : 'personal';
- const [rows, hiddenIds, online] = await Promise.all([
+ 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);
+ log(
+ 'DB device lookup failed (scope=%s); %s: %O',
+ scope,
+ workspaceId ? 'failing closed' : 'using gateway only',
+ error,
+ );
return [] as Awaited<ReturnType<typeof deviceModel.queryPersonal>>;
},
),
- // Other members' PRIVATE workspace enrollments. The gateway pool is
- // visibility-blind (every enrolled device connects under the same
- // `workspace:<id>` principal), so these must be dropped from the transient
- // "online but unregistered" fallback below or they'd leak into every
- // member's agent runs. `null` (lookup failed) fails CLOSED: without the
- // hidden set we can't tell a genuine ghost from someone's private device,
- // so workspace-scope transients are suppressed entirely for that request.
- workspaceId
- ? deviceModel.queryWorkspaceHiddenDeviceIds().catch((error) => {
- log('DB hidden-device lookup failed; suppressing transient devices: %O', error);
- return null;
- })
- : Promise.resolve([] as string[]),
deviceGateway.queryDeviceList(userId, workspaceId),
]);
- const liveById = new Map(online.map((d) => [d.deviceId, d]));
+ const registeredDeviceIds = new Set(rows.map((device) => device.deviceId));
+ const authorizedOnline = filterAuthorizedDevicePresence(registeredDeviceIds, online, scope);
+ const liveById = new Map(authorizedOnline.map((d) => [d.deviceId, d]));
const seen = new Set<string>();
const fromDb = rows.map((row): DeviceAttachment => {
seen.add(row.deviceId);
@@ -81,16 +86,14 @@ export const getScopedOnlineDevices = async (
scope,
};
});
- // Online in the gateway but not yet auto-registered in the DB (no alias yet).
- // Excludes other members' private enrollments (`hiddenIds`); when the hidden
- // lookup itself failed (`null`) no workspace transient is safe to show.
- const hidden = new Set(hiddenIds ?? []);
- const transient =
- hiddenIds === null
- ? []
- : online
- .filter((d) => !seen.has(d.deviceId) && !hidden.has(d.deviceId))
- .map((d): DeviceAttachment => ({ ...d, friendlyName: null, scope }));
+ // Personal clients register immediately before opening their socket, but a
+ // short race can still expose the live connection first. Preserve that
+ // compatibility only for personal scope. Workspace rows are authorization:
+ // a Gateway-only connection may be a stale process that missed Unshare and
+ // must never become visible or executable again.
+ const transient = authorizedOnline
+ .filter((d) => !seen.has(d.deviceId))
+ .map((d): DeviceAttachment => ({ ...d, friendlyName: null, scope }));
// Online first, then most recently active — the same order the settings list
// and the run-target picker render, so "the first device" means the same
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index 80c4bbe2ee9..c8d9266528b 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -13,6 +13,9 @@ vi.mock('@/server/services/deviceGateway', () => ({
queryDeviceList: vi.fn().mockResolvedValue([]),
},
}));
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
// The tunnel fallback must use the visibility-aware scoped helper, never the
// raw (visibility-blind) gateway pool — see resolveMcpTunnelTarget.
vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
@@ -80,6 +83,47 @@ describe('ToolExecutionService', () => {
expect(result.content).toContain('Content truncated');
});
+ /** @example A missing remote device remains machine-readable to the calling agent runtime. */
+ it('preserves structured unavailable-device data in the normalized error envelope', async () => {
+ const builtinToolsExecutor = {
+ execute: vi.fn().mockResolvedValue({
+ content: 'The requested device is not connected.',
+ error: 'DEVICE_NOT_FOUND',
+ errorData: {
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ },
+ success: false,
+ }),
+ };
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: builtinToolsExecutor as any,
+ mcpService: {} as any,
+ });
+
+ const result = await service.executeTool(
+ {
+ apiName: 'readFile',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'lobe-local-system',
+ type: 'builtin',
+ },
+ { toolManifestMap: {} },
+ );
+
+ expect(result.error).toMatchObject({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+ });
+
// Device-only MCP servers (stdio / localhost / LAN) can't be called from the
// cloud — with a device gateway configured, those calls must tunnel to the
// user's device instead of failing with a spawn/fetch error (#16533).
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index f54830fde29..cb366061804 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -14,6 +14,7 @@ import {
getConnectorToolPermission,
} from '@/libs/mcp/connectorPermissionCheck';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';
import {
@@ -152,7 +153,7 @@ export class ToolExecutionService {
return {
...data,
content: truncatedContent,
- error: normalizeExecutionError(data.error, data.content),
+ error: normalizeExecutionError(data.errorData ?? data.error, data.content),
executionTime,
};
}
@@ -355,6 +356,21 @@ export class ToolExecutionService {
): Promise<ToolExecutionResult> {
const { identifier, apiName, arguments: args } = payload;
+ const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
+ context.serverDB,
+ context.userId!,
+ target.deviceId,
+ target.workspaceId,
+ );
+ if (authorizationError) {
+ return {
+ content: 'The workspace device is no longer registered or visible for this run.',
+ error: 'DEVICE_NOT_FOUND',
+ errorData: authorizationError,
+ success: false,
+ };
+ }
+
log(
'Executing %s MCP tool via device: %s:%s (device=%s, workspace=%s)',
mcpParams.type,
@@ -406,10 +422,11 @@ export class ToolExecutionService {
if (!result.success) {
return {
content: result.content,
- error: {
+ error: result.errorData ?? {
code: 'MCP_DEVICE_EXECUTION_ERROR',
message: result.error || result.content,
},
+ errorData: result.errorData,
success: false,
};
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
index b877062e76e..1f546cb7115 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
@@ -8,9 +8,12 @@ const queryDeviceSystemInfoMock = vi.fn();
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
queryDeviceSystemInfo: (...args: unknown[]) => queryDeviceSystemInfoMock(...args),
- executeToolCall: (...args: unknown[]) => executeToolCallMock(...args),
},
}));
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ executeToolCallMock(...args),
+}));
const { auvRuntime } = await import('../auv');
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
index 33ceb242bff..b2a7bb53b40 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
@@ -3,12 +3,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolExecutionContext } from '../../types';
-// Mock deviceGateway
const mockExecuteToolCall = vi.fn();
-vi.mock('@/server/services/deviceGateway', () => ({
- deviceGateway: {
- executeToolCall: (...args: any[]) => mockExecuteToolCall(...args),
- },
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ mockExecuteToolCall(...args),
}));
const mockUploadBase64 = vi.fn();
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 5f4eae8fbad..7c15bb6e18d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -7,12 +7,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolExecutionContext } from '../../types';
-// Mock deviceGateway
const mockExecuteToolCall = vi.fn();
-vi.mock('@/server/services/deviceGateway', () => ({
- deviceGateway: {
- executeToolCall: (...args: any[]) => mockExecuteToolCall(...args),
- },
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ mockExecuteToolCall(...args),
}));
// Import after mock setup
@@ -107,7 +105,7 @@ describe('localSystemRuntime', () => {
}
});
- it('should call deviceGateway.executeToolCall with correct arguments when a proxy function is invoked', async () => {
+ it('should dispatch the authorized device tool call with correct arguments', async () => {
const context: ToolExecutionContext = {
activeDeviceId: 'device-1',
operationId: 'op-1',
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 89ead0973d8..707a0ba7ec9 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
@@ -76,6 +76,30 @@ describe('remoteDeviceRuntime', () => {
expect(runtime).toBeInstanceOf(RemoteDeviceExecutionRuntime);
});
+ /** @example Workspace discovery without a registry connection fails closed. */
+ it('does not expose raw workspace Gateway devices when the database is unavailable', async () => {
+ mockQueryDeviceList.mockResolvedValue([
+ {
+ deviceId: 'gateway-only-workspace-device',
+ hostname: 'stale-client',
+ lastSeen: '2026-09-09T00:00:00.000Z',
+ online: true,
+ platform: 'darwin',
+ },
+ ]);
+ const context: ToolExecutionContext = {
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ };
+
+ const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
+ const result = await runtime.listOnlineDevices();
+
+ expect(mockQueryDeviceList).not.toHaveBeenCalled();
+ expect(result.state).toEqual({ devices: [] });
+ });
+
it('should query only the personal pool when no workspaceId is in context', async () => {
const context: ToolExecutionContext = {
toolManifestMap: {},
@@ -104,6 +128,7 @@ describe('remoteDeviceRuntime', () => {
it('lists ONLY workspace devices in a workspace run (personal devices excluded)', async () => {
const context: ToolExecutionContext = {
+ serverDB: makeServerDB('ws-1'),
toolManifestMap: {},
userId: 'user-1',
workspaceId: 'ws-1',
@@ -127,6 +152,9 @@ describe('remoteDeviceRuntime', () => {
mockQueryDeviceList.mockImplementation((_userId: string, wsId?: string) =>
Promise.resolve(wsId ? [workspaceDevice] : [personalDevice]),
);
+ mockQueryWorkspaceDevices.mockResolvedValue([
+ { ...workspaceDevice, lastSeenAt: new Date(workspaceDevice.lastSeen) },
+ ]);
const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
@@ -169,6 +197,9 @@ describe('remoteDeviceRuntime', () => {
mockQueryDeviceList.mockImplementation((_userId: string, wsId?: string) =>
Promise.resolve(wsId ? [workspaceDevice] : [personalDevice]),
);
+ mockQueryWorkspaceDevices.mockResolvedValue([
+ { ...workspaceDevice, lastSeenAt: new Date(workspaceDevice.lastSeen) },
+ ]);
const runtime = remoteDeviceRuntime.factory(context) as RemoteDeviceExecutionRuntime;
@@ -249,10 +280,8 @@ describe('remoteDeviceRuntime', () => {
});
});
- 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.
+ /** @example A registry outage cannot authorize raw workspace Gateway presence. */
+ it('fails closed when the workspace DB lookup fails', async () => {
const context: ToolExecutionContext = {
serverDB: makeServerDB('ws-1'),
toolManifestMap: {},
@@ -280,11 +309,8 @@ describe('remoteDeviceRuntime', () => {
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' }),
- ]);
+ expect(result.state).toEqual({ devices: [] });
+ expect(result.content).toContain('No online devices found');
});
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index d84081d1eb2..98c313d996a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -112,11 +112,15 @@ vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
- executeToolCall: mocks.executeToolCall,
prepareSkillDirectory: mocks.prepareSkillDirectory,
},
}));
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ mocks.executeToolCall(...args),
+}));
+
vi.mock('../resolveWorkspaceScope', () => ({
resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,
resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
index 30c96878b98..69a3b9d0ef5 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
@@ -1,6 +1,7 @@
import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
@@ -44,7 +45,8 @@ export const auvRuntime: ServerRuntimeRegistration = {
'The selected device does not support Computer Use. Update the desktop app and reconnect.',
);
}
- return deviceGateway.executeToolCall(
+ return executeAuthorizedDeviceToolCall(
+ context.serverDB,
{
deviceId: context.activeDeviceId!,
operationId: context.operationId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index a477adc8a9a..2b0dc5520b7 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -1,7 +1,7 @@
import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';
import debug from 'debug';
-import { deviceGateway } from '@/server/services/deviceGateway';
+import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { FileService } from '@/server/services/file';
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
@@ -147,7 +147,8 @@ export const browserRuntime: ServerRuntimeRegistration = {
// are stripped device-side.
const finalArgs = { ...args, __agentId: context.agentId, __topicId: context.topicId };
- const result = await deviceGateway.executeToolCall(
+ const result = await executeAuthorizedDeviceToolCall(
+ context.serverDB,
{
deviceId: context.activeDeviceId!,
operationId: context.operationId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 1cb80b8e153..1db39a4d037 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -4,7 +4,7 @@ import {
LocalSystemManifest,
} from '@lobechat/builtin-tool-local-system';
-import { deviceGateway } from '@/server/services/deviceGateway';
+import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCommand';
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
@@ -151,7 +151,8 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
}
}
- return deviceGateway.executeToolCall(
+ return executeAuthorizedDeviceToolCall(
+ context.serverDB,
{
deviceId: context.activeDeviceId!,
operationId: context.operationId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
index 96be36940ec..27787e8cd58 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
@@ -6,6 +6,10 @@ import { RemoteDeviceExecutionRuntime } from '@lobechat/builtin-tool-remote-devi
import debug from 'debug';
import { deviceGateway } from '@/server/services/deviceGateway';
+import {
+ filterAuthorizedDevicePresence,
+ isGatewayOnlyDevicePresenceAllowed,
+} from '@/server/services/deviceGateway/scopedDevicePresence';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
@@ -14,6 +18,25 @@ import { type ServerRuntimeRegistration } from './types';
// Enable with DEBUG=lobe-server:remote-device (works in prod via the env var).
const log = debug('lobe-server:remote-device');
+/**
+ * Registers remote-device discovery for a server-side agent tool execution.
+ *
+ * Use when:
+ * - The tools engine activates the remote-device builtin runtime
+ *
+ * Expects:
+ * - Workspace discovery has a server database handle for registry authorization
+ *
+ * Returns:
+ * - A runtime whose device list is scoped to one authorized principal
+ *
+ * Call stack:
+ *
+ * ToolExecutionService
+ * -> {@link remoteDeviceRuntime.factory}
+ * -> getScopedOnlineDevices
+ * -> RemoteDeviceExecutionRuntime
+ */
export const remoteDeviceRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId) {
@@ -37,13 +60,18 @@ export const remoteDeviceRuntime: ServerRuntimeRegistration = {
// degrade to the personal-only pool.
const workspaceId = await resolveRunWorkspaceId(context);
- // 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.
+ // Without a DB handle, personal scope may retain the auto-registration
+ // transient fallback. Workspace scope cannot: its registry row is the
+ // authorization boundary, and a raw Gateway socket may be a stale
+ // process that missed Unshare.
if (!serverDB) {
const scope = workspaceId ? ('workspace' as const) : ('personal' as const);
+ if (!isGatewayOnlyDevicePresenceAllowed(scope)) return [];
const online = await deviceGateway.queryDeviceList(userId, workspaceId);
- return online.map((d) => ({ ...d, scope }));
+ return filterAuthorizedDevicePresence(new Set(), online, scope).map((d) => ({
+ ...d,
+ scope,
+ }));
}
const devices = await getScopedOnlineDevices(serverDB, userId, workspaceId);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index ed721059b1a..8f71ed78217 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -31,6 +31,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import { createSandboxService, normalizeSandboxCommandResult } from '@/server/services/sandbox';
@@ -415,7 +416,8 @@ class SkillServerRuntimeService implements SkillRuntimeService {
// workspace agent routed to the caller's own machine is still editing
// workspace content.
const deviceLhEnv = buildDeviceLhEnv(await this.resolveWorkspaceId());
- const response = await deviceGateway.executeToolCall(
+ const response = await executeAuthorizedDeviceToolCall(
+ this.serverDB,
{
deviceId: device.deviceId,
operationId: device.operationId,
@@ -771,8 +773,13 @@ export const skillsRuntime: ServerRuntimeRegistration = {
const userId = context.userId;
deviceFileAccess = {
listFiles: async (dir: string) => {
- const result = await deviceGateway.executeToolCall(
- { deviceId: activeDeviceId, userId },
+ const result = await executeAuthorizedDeviceToolCall(
+ context.serverDB,
+ {
+ deviceId: activeDeviceId,
+ userId,
+ workspaceId: await resolveRunWorkspaceId(context),
+ },
{
apiName: LocalSystemApiName.globFiles,
// `**/*` matches every regular file recursively under `dir`.
@@ -800,8 +807,13 @@ export const skillsRuntime: ServerRuntimeRegistration = {
.map((f) => (f.startsWith(dir) ? f.slice(dir.length).replace(/^[/\\]+/, '') : f));
},
readFile: async (filePath: string) => {
- const result = await deviceGateway.executeToolCall(
- { deviceId: activeDeviceId, userId },
+ const result = await executeAuthorizedDeviceToolCall(
+ context.serverDB,
+ {
+ deviceId: activeDeviceId,
+ userId,
+ workspaceId: await resolveRunWorkspaceId(context),
+ },
{
apiName: LocalSystemApiName.readFile,
// Read the whole file; SKILL.md and references are small.
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 51842df3604..a442e3cba7a 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -4,6 +4,7 @@ import {
type AgentShareVisitorContext,
type ChatToolPayload,
type ClientSecretPayload,
+ type DeviceUnavailableErrorData,
type ExecSubAgentParams,
type StepActivatedSkill,
type StepContextTodoItem,
@@ -346,6 +347,8 @@ export interface ToolExecutionResult {
*/
deferred?: boolean;
error?: any;
+ /** Structured unavailable-device context preserved through the runtime error envelope. */
+ errorData?: DeviceUnavailableErrorData;
state?: Record<string, any>;
success: boolean;
/**
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d4c4095b60c..6b86a862f2c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -966,6 +966,8 @@
"heteroAgent.executionTarget.noneDesc": "No device enabled",
"heteroAgent.executionTarget.offline": "Offline",
"heteroAgent.executionTarget.online": "Online",
+ "heteroAgent.executionTarget.onlineConnections_one": "Online · {{count}} connection",
+ "heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} connections",
"heteroAgent.executionTarget.personalGroup": "Private Devices",
"heteroAgent.executionTarget.reconnect": "Reconnect",
"heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.",
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index e7784828588..0ae0b0484a0 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -2,9 +2,15 @@
"gateway.enableConnection": "Connect to Gateway",
"gateway.manageDevices": "Manage devices",
"gateway.statusConnected": "This device is connected to Gateway",
+ "gateway.statusConnectedConnections_one": "Online · {{count}} connection",
+ "gateway.statusConnectedConnections_other": "Online · {{count}} connections",
"gateway.statusConnecting": "This device is connecting to Gateway...",
"gateway.statusDisconnected": "This device is not connected to Gateway",
"gateway.title": "Device Gateway",
+ "gateway.workspaceStatusConnections_one": "Workspace · {{count}} connection online",
+ "gateway.workspaceStatusConnections_other": "Workspace · {{count}} connections online",
+ "gateway.workspaceStatusDisconnected": "No workspace device connection is online",
+ "gateway.workspaceStatusUnavailable": "Workspace device status is temporarily unavailable",
"navigation.agentShare": "Share",
"navigation.agents": "Agents",
"navigation.apps": "Apps",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 9d620434f08..a1ca79b34cb 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -459,6 +459,8 @@
"devices.share.visibilityTag.public": "Workspace",
"devices.status.offline": "Offline",
"devices.status.online": "Online",
+ "devices.status.onlineConnections_one": "Online · {{count}} connection",
+ "devices.status.onlineConnections_other": "Online · {{count}} connections",
"devices.title": "My Devices",
"devices.visibility.publish": "Publish to Workspace",
"devices.visibility.publishConfirmTitle": "Publish this device to the workspace?",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d9c72a9207c..fbae83b4edd 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -966,6 +966,8 @@
"heteroAgent.executionTarget.noneDesc": "不启用任何设备",
"heteroAgent.executionTarget.offline": "离线",
"heteroAgent.executionTarget.online": "在线",
+ "heteroAgent.executionTarget.onlineConnections_one": "在线 · {{count}} 个连接",
+ "heteroAgent.executionTarget.onlineConnections_other": "在线 · {{count}} 个连接",
"heteroAgent.executionTarget.personalGroup": "私人设备",
"heteroAgent.executionTarget.reconnect": "重新连接",
"heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 6f3c6deb916..9e6db120079 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -2,9 +2,15 @@
"gateway.enableConnection": "连接到网关",
"gateway.manageDevices": "管理设备",
"gateway.statusConnected": "本机已连接设备网关",
+ "gateway.statusConnectedConnections_one": "在线 · {{count}} 个连接",
+ "gateway.statusConnectedConnections_other": "在线 · {{count}} 个连接",
"gateway.statusConnecting": "本机正在连接设备网关...",
"gateway.statusDisconnected": "本机未连接设备网关",
"gateway.title": "设备网关",
+ "gateway.workspaceStatusConnections_one": "工作空间 · {{count}} 个连接在线",
+ "gateway.workspaceStatusConnections_other": "工作空间 · {{count}} 个连接在线",
+ "gateway.workspaceStatusDisconnected": "当前没有工作空间设备连接在线",
+ "gateway.workspaceStatusUnavailable": "暂时无法获取工作空间设备状态",
"navigation.agentShare": "分享",
"navigation.agents": "助手",
"navigation.apps": "应用",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index db650ecfe6e..f1628347577 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -459,6 +459,8 @@
"devices.share.visibilityTag.public": "工作区",
"devices.status.offline": "离线",
"devices.status.online": "在线",
+ "devices.status.onlineConnections_one": "在线 · {{count}} 个连接",
+ "devices.status.onlineConnections_other": "在线 · {{count}} 个连接",
"devices.title": "我的设备",
"devices.visibility.publish": "发布到工作区",
"devices.visibility.publishConfirmTitle": "将此设备发布到工作区?",
diff --git a/packages/device-gateway-client/package.json b/packages/device-gateway-client/package.json
index d75ec7685a1..cdf6f197b21 100644
--- a/packages/device-gateway-client/package.json
+++ b/packages/device-gateway-client/package.json
@@ -11,6 +11,7 @@
"test:coverage": "bunx vitest run --coverage"
},
"dependencies": {
+ "@lobechat/types": "workspace:*",
"ws": "^8.21.0"
},
"devDependencies": {
diff --git a/packages/device-gateway-client/src/deviceTransportError.test.ts b/packages/device-gateway-client/src/deviceTransportError.test.ts
index d3b53d5a418..4d2b654b5e0 100644
--- a/packages/device-gateway-client/src/deviceTransportError.test.ts
+++ b/packages/device-gateway-client/src/deviceTransportError.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
import {
- DeviceTransportErrorCode,
describeGatewayRequestFailure,
describeGatewayResponseFailure,
+ DeviceTransportErrorCode,
} from './deviceTransportError';
describe('describeGatewayResponseFailure', () => {
@@ -66,6 +66,22 @@ describe('describeGatewayResponseFailure', () => {
);
});
+ /** @example A workspace dispatch miss carries enough context for an outer agent to retry. */
+ it('describes a missing device with structured retryable scope data', () => {
+ const failure = describeGatewayResponseFailure(404, 'DEVICE_NOT_FOUND', 'tool call', {
+ deviceId: 'workspace-device-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(failure.data).toEqual({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'workspace-device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+ });
+
it('names the operation that failed', () => {
expect(describeGatewayResponseFailure(503, '', 'message API call').content).toContain(
'message API call',
@@ -116,8 +132,10 @@ describe('describeGatewayRequestFailure', () => {
it('recognises the DOM AbortError name as well', () => {
expect(
- describeGatewayRequestFailure(Object.assign(new Error('aborted'), { name: 'AbortError' }), 'tool call')
- .code,
+ describeGatewayRequestFailure(
+ Object.assign(new Error('aborted'), { name: 'AbortError' }),
+ 'tool call',
+ ).code,
).toBe(DeviceTransportErrorCode.DeviceResponseTimeout);
});
@@ -151,7 +169,10 @@ describe('describeGatewayRequestFailure', () => {
// The old copy claimed the gateway was unreachable for every rejection,
// including ones (a malformed response body, say) that prove nothing about
// whether the device ran the call.
- const failure = describeGatewayRequestFailure(new Error('Unexpected token < in JSON'), 'tool call');
+ const failure = describeGatewayRequestFailure(
+ new Error('Unexpected token < in JSON'),
+ 'tool call',
+ );
expect(failure.code).toBe(DeviceTransportErrorCode.GatewayError);
expect(failure.content).toContain('unclear whether the device ran it');
diff --git a/packages/device-gateway-client/src/deviceTransportError.ts b/packages/device-gateway-client/src/deviceTransportError.ts
index 77ccd886203..59ca0e73b54 100644
--- a/packages/device-gateway-client/src/deviceTransportError.ts
+++ b/packages/device-gateway-client/src/deviceTransportError.ts
@@ -1,3 +1,7 @@
+import type { DeviceUnavailableErrorData } from '@lobechat/types';
+
+export type { DeviceUnavailableErrorData } from '@lobechat/types';
+
/**
* Human- and model-readable descriptions for device-channel transport
* failures.
@@ -42,10 +46,13 @@ export const DeviceTransportErrorCode = {
export type DeviceTransportErrorCode =
(typeof DeviceTransportErrorCode)[keyof typeof DeviceTransportErrorCode];
+/** A normalized failure from the server-to-device transport hop. */
export interface DeviceTransportFailure {
code: DeviceTransportErrorCode;
/** LLM- and user-facing explanation. Goes in the result `content`. */
content: string;
+ /** Structured retry context when the requested logical device is absent. */
+ data?: DeviceUnavailableErrorData;
/** Machine-facing detail: the gateway's own body when it sent one. */
error: string;
}
@@ -53,6 +60,11 @@ export interface DeviceTransportFailure {
/** What the failed hop was carrying, used to open the sentence. */
export type DeviceTransportOperation = 'tool call' | 'message API call' | 'RPC call' | 'agent run';
+interface DeviceTransportTarget {
+ deviceId?: string;
+ workspaceId?: string;
+}
+
const RECONNECT_HINT = `Tell the user to check that the LobeHub desktop app (or the \`lh\` CLI) is running and shows as connected.`;
const describeStatus = (
@@ -121,18 +133,40 @@ const describeStatus = (
* `body` is the gateway's response text; it is kept verbatim as `error` so that
* existing matches on gateway codes (e.g. `DEVICE_OFFLINE`) keep working, and
* appended to the explanation when it carries anything beyond the status.
+ *
+ * Use when:
+ * - A Gateway HTTP request returned a non-success status
+ * - A caller needs structured retry context for a missing logical device
+ *
+ * Expects:
+ * - `target`, when provided, is the already-authorized dispatch target
+ *
+ * Returns:
+ * - Backward-compatible text plus optional structured unavailable-device data
*/
export const describeGatewayResponseFailure = (
status: number,
body: string | undefined,
operation: DeviceTransportOperation,
+ target?: DeviceTransportTarget,
): DeviceTransportFailure => {
const { code, content } = describeStatus(status, operation);
const detail = body?.trim();
+ const data =
+ code === DeviceTransportErrorCode.DeviceNotFound && target?.deviceId
+ ? {
+ code: DeviceTransportErrorCode.DeviceNotFound,
+ deviceId: target.deviceId,
+ retryable: true as const,
+ scope: target.workspaceId ? ('workspace' as const) : ('personal' as const),
+ ...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
+ }
+ : undefined;
return {
code,
content: detail ? `${content}\n\nGateway detail: ${detail}` : content,
+ ...(data ? { data } : {}),
error: detail || `${code} (HTTP ${status})`,
};
};
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index f1b55794fa6..5e5dbfc6f39 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -182,6 +182,32 @@ describe('GatewayHttpClient', () => {
});
});
+ /** @example The HTTP client preserves target context on a missing workspace device. */
+ it('returns structured retryable data for DEVICE_NOT_FOUND', async () => {
+ mockFetch({
+ ok: false,
+ status: 404,
+ text: vi.fn().mockResolvedValue('DEVICE_NOT_FOUND'),
+ });
+
+ const result = await client.executeToolCall(
+ {
+ deviceId: 'workspace-device-1',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ },
+ { apiName: 'readFile', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(result.errorData).toEqual({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'workspace-device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+ });
+
it('keeps a deliberate empty success result empty', async () => {
mockFetch({
json: vi.fn().mockResolvedValue({ content: '', success: true }),
@@ -538,6 +564,35 @@ describe('GatewayHttpClient', () => {
expect(result).toEqual({ error: 'DEVICE_OFFLINE', success: false });
});
+
+ /** @example A pre-acceptance 404 keeps enough context for an outer agent to retry. */
+ it('returns structured retry context for a missing agent-run target', async () => {
+ mockFetch({
+ ok: false,
+ status: 404,
+ text: vi.fn().mockResolvedValue('DEVICE_NOT_FOUND'),
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ assistantMessageId: 'asst-1',
+ deviceId: 'device-1',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(result.errorData).toEqual({
+ code: 'DEVICE_NOT_FOUND',
+ deviceId: 'device-1',
+ retryable: true,
+ scope: 'workspace',
+ workspaceId: 'workspace-1',
+ });
+ });
});
describe('executeMcpCall', () => {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 86630987fc9..ed3fd24fe18 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,6 +1,8 @@
import {
describeGatewayRequestFailure,
describeGatewayResponseFailure,
+ type DeviceTransportFailure,
+ type DeviceUnavailableErrorData,
} from './deviceTransportError';
import type {
DeviceSystemInfo,
@@ -23,32 +25,43 @@ export interface DeviceStatusResult {
online: boolean;
}
+/** Result envelope returned by a tunneled device tool call. */
export interface DeviceToolCallResult {
content: string;
error?: string;
+ /** Structured availability context for callers that can choose whether to retry. */
+ errorData?: DeviceUnavailableErrorData;
state?: unknown;
success: boolean;
}
+/** Result envelope returned by a tunneled device messaging call. */
export interface DeviceMessageApiResult {
content: string;
error?: string;
+ /** Structured availability context for callers that can choose whether to retry. */
+ errorData?: DeviceUnavailableErrorData;
success: boolean;
}
+/**
+ * Result envelope returned by a generic device RPC.
+ *
+ * @param T Successful RPC payload type.
+ */
export interface DeviceRpcResult<T = unknown> {
data?: T;
error?: string;
+ /** Structured availability context for callers that can choose whether to retry. */
+ errorData?: DeviceUnavailableErrorData;
success: boolean;
}
/** Shape a described transport failure into the LLM-facing tool result. */
-const toFailedToolCallResult = (failure: {
- content: string;
- error: string;
-}): DeviceToolCallResult => ({
+const toFailedToolCallResult = (failure: DeviceTransportFailure): DeviceToolCallResult => ({
content: failure.content,
error: failure.error,
+ ...(failure.data ? { errorData: failure.data } : {}),
success: false,
});
@@ -180,7 +193,9 @@ export class GatewayHttpClient {
if (!res.ok) {
const text = await res.text().catch(() => '');
- return toFailedToolCallResult(describeGatewayResponseFailure(res.status, text, 'tool call'));
+ return toFailedToolCallResult(
+ describeGatewayResponseFailure(res.status, text, 'tool call', params),
+ );
}
const data = await res.json();
@@ -227,8 +242,13 @@ export class GatewayHttpClient {
if (!res.ok) {
const text = await res.text().catch(() => '');
- const failure = describeGatewayResponseFailure(res.status, text, 'message API call');
- return { content: failure.content, error: failure.error, success: false };
+ const failure = describeGatewayResponseFailure(res.status, text, 'message API call', params);
+ return {
+ content: failure.content,
+ error: failure.error,
+ ...(failure.data ? { errorData: failure.data } : {}),
+ success: false,
+ };
}
const data = await res.json();
@@ -266,12 +286,14 @@ export class GatewayHttpClient {
* `lh hetero exec` can write back under the topic's scope.
*/
ingestWorkspaceId?: string;
- }): Promise<{ success: boolean; error?: string }> {
+ }): Promise<{ success: boolean; error?: string; errorData?: DeviceUnavailableErrorData }> {
const res = await this.post('/api/device/agent/run', params);
if (!res.ok) {
const text = await res.text().catch(() => '');
+ const failure = describeGatewayResponseFailure(res.status, text, 'agent run', params);
return {
- error: describeGatewayResponseFailure(res.status, text, 'agent run').error,
+ error: failure.error,
+ ...(failure.data ? { errorData: failure.data } : {}),
success: false,
};
}
@@ -316,8 +338,10 @@ export class GatewayHttpClient {
if (!res.ok) {
const text = await res.text().catch(() => '');
+ const failure = describeGatewayResponseFailure(res.status, text, 'RPC call', params);
return {
- error: describeGatewayResponseFailure(res.status, text, 'RPC call').error,
+ error: failure.error,
+ ...(failure.data ? { errorData: failure.data } : {}),
success: false,
};
}
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index 8745f3de054..a07885a5343 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -1,6 +1,10 @@
export type { GatewayClientLogger, GatewayClientOptions } from './client';
export { GatewayClient } from './client';
-export type { DeviceTransportFailure, DeviceTransportOperation } from './deviceTransportError';
+export type {
+ DeviceTransportFailure,
+ DeviceTransportOperation,
+ DeviceUnavailableErrorData,
+} from './deviceTransportError';
export {
describeGatewayRequestFailure,
describeGatewayResponseFailure,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f33193c9671..ad44205aaa9 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -648,6 +648,8 @@ export default {
'heteroAgent.executionTarget.noneDesc': 'No device enabled',
'heteroAgent.executionTarget.offline': 'Offline',
'heteroAgent.executionTarget.online': 'Online',
+ 'heteroAgent.executionTarget.onlineConnections_one': 'Online · {{count}} connection',
+ 'heteroAgent.executionTarget.onlineConnections_other': 'Online · {{count}} connections',
'heteroAgent.executionTarget.reconnect': 'Reconnect',
'heteroAgent.executionTarget.reconnectFailed':
'Could not reconnect this device. Make sure the desktop app is running, then try again.',
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 6a36bfbf71e..0cbb16332b9 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -105,9 +105,15 @@ export default {
'gateway.enableConnection': 'Connect to Gateway',
'gateway.manageDevices': 'Manage devices',
'gateway.statusConnected': 'This device is connected to Gateway',
+ 'gateway.statusConnectedConnections_one': 'Online · {{count}} connection',
+ 'gateway.statusConnectedConnections_other': 'Online · {{count}} connections',
'gateway.statusConnecting': 'This device is connecting to Gateway...',
'gateway.statusDisconnected': 'This device is not connected to Gateway',
'gateway.title': 'Device Gateway',
+ 'gateway.workspaceStatusConnections_one': 'Workspace · {{count}} connection online',
+ 'gateway.workspaceStatusConnections_other': 'Workspace · {{count}} connections online',
+ 'gateway.workspaceStatusDisconnected': 'No workspace device connection is online',
+ 'gateway.workspaceStatusUnavailable': 'Workspace device status is temporarily unavailable',
'remoteServer.authError': 'Authorization failed: {{error}}',
'remoteServer.authPending': 'Please complete the authorization in your browser',
'remoteServer.configDesc': 'Connect to the remote LobeHub server to enable data synchronization',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 42cfe5d6f07..5c2f5e5c5fc 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -682,6 +682,8 @@ export default {
'devices.share.visibilityTag.public': 'Workspace',
'devices.status.offline': 'Offline',
'devices.status.online': 'Online',
+ 'devices.status.onlineConnections_one': 'Online · {{count}} connection',
+ 'devices.status.onlineConnections_other': 'Online · {{count}} connections',
'devices.title': 'My Devices',
'devices.visibility.publish': 'Publish to Workspace',
'devices.visibility.publishConfirmTitle': 'Publish this device to the workspace?',
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index e15d2494d93..8e219855871 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -1,6 +1,6 @@
import type { LobeAgentChatConfig } from '../agent/chatConfig';
import type { CreateThreadWithMessageParams } from '../aiChat';
-import type { WorkingDirConfig } from '../device';
+import type { DeviceUnavailableErrorData, WorkingDirConfig } from '../device';
import type { TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
@@ -303,9 +303,7 @@ export interface ScheduleAgentRunResult {
topicId: string;
}
-/**
- * Response from execAgent
- */
+/** Response from execAgent. */
export interface ExecAgentResult {
/** The resolved agent ID */
agentId: string;
@@ -319,6 +317,8 @@ export interface ExecAgentResult {
createdThreadId?: string;
/** Error message if operation failed to start */
error?: string;
+ /** Structured availability context when a device dispatch failed before acceptance. */
+ errorData?: DeviceUnavailableErrorData;
/**
* External heterogeneous producer for this run. `null` explicitly denotes
* the normal AgentRuntime path; `undefined` is reserved for rolling clients
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index d741b25c12d..c1b661e643c 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -1,5 +1,19 @@
import { z } from 'zod';
+/** Structured context for an unavailable logical device. */
+export interface DeviceUnavailableErrorData {
+ /** Stable machine-readable availability code. */
+ code: 'DEVICE_NOT_FOUND';
+ /** Logical device requested by the failed dispatch. */
+ deviceId: string;
+ /** Availability failures are safe for an outer caller to reconsider. */
+ retryable: true;
+ /** Principal pool in which presence was checked. */
+ scope: 'personal' | 'workspace';
+ /** Workspace principal, present only for workspace-scoped dispatch. */
+ workspaceId?: string;
+}
+
export type ProjectSkillScope = 'device' | 'project';
export type ProjectSkillSource = '.agents/skills' | '.claude/skills';
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 6080ce0dbfe..67a74ef228e 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -1,6 +1,7 @@
import { type ReactNode } from 'react';
import { z } from 'zod';
+import { type DeviceUnavailableErrorData } from '../device';
import { type RuntimeStepContext } from '../stepContext';
import { type HumanInterventionConfig, type HumanInterventionPolicy } from './intervention';
import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';
@@ -488,6 +489,8 @@ export interface BuiltinServerRuntimeOutput {
*/
deferred?: boolean;
error?: any;
+ /** Structured unavailable-device context preserved through the runtime error envelope. */
+ errorData?: DeviceUnavailableErrorData;
state?: any;
success: boolean;
}
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 5115a60ee10..3224ebb7dcb 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -696,7 +696,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<ExecutionTargetDeviceStatus
offlineLabel={t('heteroAgent.executionTarget.offline')}
online={d.online}
- onlineLabel={t('heteroAgent.executionTarget.online')}
+ onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
+ count: d.channels.length,
+ })}
/>
);
diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsx
index d78e0feb3b5..be0deeeae9b 100644
--- a/src/features/DeviceManager/DeviceDetailPanel.tsx
+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx
@@ -234,7 +234,9 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
</Text>
<Flexbox horizontal align={'center'} gap={8}>
<Tag color={online ? 'success' : 'default'} size={'small'}>
- {online ? t('devices.status.online') : t('devices.status.offline')}
+ {online
+ ? t('devices.status.onlineConnections', { count: channels.length })
+ : t('devices.status.offline')}
</Tag>
{isCurrent && <Tag size={'small'}>{t('devices.currentBadge')}</Tag>}
</Flexbox>
diff --git a/src/features/DeviceManager/DeviceItem.tsx b/src/features/DeviceManager/DeviceItem.tsx
index 522a076d67f..cdc0db9b369 100644
--- a/src/features/DeviceManager/DeviceItem.tsx
+++ b/src/features/DeviceManager/DeviceItem.tsx
@@ -158,9 +158,12 @@ const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selecte
// CONNECTED", not "last active". The copy says exactly that; it becomes a
// true last-active once a writer stamps liveness.
const activityText = online
- ? t('devices.channel.connected', {
- time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
- })
+ ? `${t('devices.status.onlineConnections', { count: channels.length })} · ${t(
+ 'devices.channel.connected',
+ {
+ time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
+ },
+ )}`
: t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
// Publish / make-private for workspace enrollments. Reuses the
diff --git a/src/features/DeviceManager/connectionCount.test.ts b/src/features/DeviceManager/connectionCount.test.ts
new file mode 100644
index 00000000000..705600a46dc
--- /dev/null
+++ b/src/features/DeviceManager/connectionCount.test.ts
@@ -0,0 +1,72 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { getScopedConnectionCount, getWorkspaceConnectionState } from './connectionCount';
+
+const device = (
+ deviceId: string,
+ scope: DeviceListItem['scope'],
+ connectionCount: number,
+): DeviceListItem =>
+ ({
+ channels: Array.from({ length: connectionCount }, (_, index) => ({
+ channel: null,
+ connectedAt: `2026-09-09T00:00:0${index}.000Z`,
+ hostname: null,
+ platform: null,
+ })),
+ deviceId,
+ scope,
+ }) as DeviceListItem;
+
+describe('getScopedConnectionCount', () => {
+ /** @example Personal presence cannot make an offline workspace device appear connected. */
+ it('keeps personal and workspace connection counts independent', () => {
+ // ROOT CAUSE:
+ //
+ // The Electron title bar previously showed its personal socket while a workspace target had
+ // no live connection, making DEVICE_NOT_FOUND look contradictory. Counts now follow scope.
+ const devices = [
+ device('personal-device', 'personal', 2),
+ device('workspace-device', 'workspace', 0),
+ ];
+
+ expect(getScopedConnectionCount(devices, 'personal', 'personal-device')).toBe(2);
+ expect(getScopedConnectionCount(devices, 'workspace')).toBe(0);
+ });
+
+ /** @example Switching workspaces recomputes the total from the newly scoped device list. */
+ it('aggregates multiple logical devices only within the current workspace response', () => {
+ expect(
+ getScopedConnectionCount(
+ [device('workspace-a', 'workspace', 1), device('workspace-b', 'workspace', 2)],
+ 'workspace',
+ ),
+ ).toBe(3);
+ });
+});
+
+describe('getWorkspaceConnectionState', () => {
+ /** @example A failed first request does not claim that every workspace device is offline. */
+ it('reports unavailable when the device list fails without cached data', () => {
+ // ROOT CAUSE:
+ //
+ // The Electron title bar previously converted an undefined device list into a zero count after
+ // an SWR error, presenting an unverified result as "No workspace device connection is online".
+ // The unavailable state now preserves the distinction between a failed lookup and an empty list.
+ expect(getWorkspaceConnectionState(undefined, false, new Error('network unavailable'))).toBe(
+ 'unavailable',
+ );
+ });
+
+ /** @example Cached presence remains useful when a background revalidation request fails. */
+ it('uses cached device presence during a revalidation error', () => {
+ expect(
+ getWorkspaceConnectionState(
+ [device('workspace-device', 'workspace', 1)],
+ false,
+ new Error('revalidation failed'),
+ ),
+ ).toBe('connected');
+ });
+});
diff --git a/src/features/DeviceManager/connectionCount.ts b/src/features/DeviceManager/connectionCount.ts
new file mode 100644
index 00000000000..a73381a034b
--- /dev/null
+++ b/src/features/DeviceManager/connectionCount.ts
@@ -0,0 +1,50 @@
+import type { DeviceListItem, DeviceScope } from '@lobechat/types';
+
+/**
+ * Counts live connections within one principal scope.
+ *
+ * Use when:
+ * - A scope-level control summarizes all authorized device presence
+ * - A personal control needs the count for one logical device
+ *
+ * Expects:
+ * - Device channels were already filtered by the server for the active principal
+ *
+ * Returns:
+ * - The number of live connections in the requested scope and optional device
+ */
+export const getScopedConnectionCount = (
+ devices: DeviceListItem[] | undefined,
+ scope: DeviceScope,
+ deviceId?: string,
+): number | undefined => {
+ if (!devices) return undefined;
+
+ return devices
+ .filter((device) => device.scope === scope && (!deviceId || device.deviceId === deviceId))
+ .reduce((count, device) => count + device.channels.length, 0);
+};
+
+/**
+ * Resolves the workspace presence state without treating a failed lookup as offline.
+ *
+ * Use when:
+ * - A workspace-scoped surface summarizes device presence from an asynchronous list
+ * - Cached presence may remain available while background revalidation fails
+ *
+ * Expects:
+ * - `devices` is already scoped to the active workspace by the caller's data hook
+ *
+ * Returns:
+ * - A presentation state that distinguishes unavailable data from an authoritative empty list
+ */
+export const getWorkspaceConnectionState = (
+ devices: DeviceListItem[] | undefined,
+ isLoading: boolean,
+ error: unknown,
+): 'connected' | 'connecting' | 'disconnected' | 'unavailable' => {
+ if (!devices && error) return 'unavailable';
+ if (!devices && isLoading) return 'connecting';
+
+ return getScopedConnectionCount(devices, 'workspace') ? 'connected' : 'disconnected';
+};
diff --git a/src/features/Electron/connection/DeviceGateway.tsx b/src/features/Electron/connection/DeviceGateway.tsx
index 4d641d6c78c..04f5d2a3447 100644
--- a/src/features/Electron/connection/DeviceGateway.tsx
+++ b/src/features/Electron/connection/DeviceGateway.tsx
@@ -7,6 +7,11 @@ import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import {
+ getScopedConnectionCount,
+ getWorkspaceConnectionState,
+} from '@/features/DeviceManager/connectionCount';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
@@ -40,7 +45,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const DeviceGateway = memo(() => {
+interface DeviceGatewayProps {
+ workspaceScoped: boolean;
+}
+
+const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {
const { t } = useTranslation('electron');
const navigate = useWorkspaceAwareNavigate();
const [
@@ -58,6 +67,13 @@ const DeviceGateway = memo(() => {
]);
useFetchGatewayStatus();
+ useElectronStore((s) => s.useFetchGatewayDeviceInfo)();
+ const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
+ const {
+ data: devices,
+ error: deviceListError,
+ isLoading: isDeviceListLoading,
+ } = useDeviceList();
useWatchBroadcast('gatewayConnectionStatusChanged', ({ status }) => {
setGatewayConnectionStatus(status);
@@ -82,13 +98,31 @@ const DeviceGateway = memo(() => {
[connectGateway, disconnectGateway],
);
- const connectionHint = t(
- isConnecting
- ? 'gateway.statusConnecting'
- : isConnected
- ? 'gateway.statusConnected'
- : 'gateway.statusDisconnected',
+ const connectionCount = getScopedConnectionCount(
+ devices,
+ workspaceScoped ? 'workspace' : 'personal',
+ workspaceScoped ? undefined : gatewayDeviceInfo?.deviceId,
+ );
+ const workspaceConnectionState = getWorkspaceConnectionState(
+ devices,
+ isDeviceListLoading,
+ deviceListError,
);
+ const scopeConnected = workspaceScoped ? workspaceConnectionState === 'connected' : isConnected;
+ const connectionHint =
+ workspaceScoped
+ ? workspaceConnectionState === 'unavailable'
+ ? t('gateway.workspaceStatusUnavailable')
+ : workspaceConnectionState === 'connecting'
+ ? t('gateway.statusConnecting')
+ : workspaceConnectionState === 'connected'
+ ? t('gateway.workspaceStatusConnections', { count: connectionCount })
+ : t('gateway.workspaceStatusDisconnected')
+ : isConnecting
+ ? t('gateway.statusConnecting')
+ : isConnected && connectionCount
+ ? t('gateway.statusConnectedConnections', { count: connectionCount })
+ : t(isConnected ? 'gateway.statusConnected' : 'gateway.statusDisconnected');
const popoverContent = (
<Flexbox className={styles.popoverContent} gap={4}>
@@ -102,16 +136,18 @@ const DeviceGateway = memo(() => {
title={t('gateway.manageDevices')}
onClick={() => {
setOpen(false);
- navigate('/settings/devices', { escape: true });
+ navigate('/settings/devices');
}}
/>
- <Switch
- aria-label={t('gateway.enableConnection')}
- checked={isConnected || isConnecting}
- loading={isConnecting}
- size="small"
- onChange={handleSwitchChange}
- />
+ {!workspaceScoped && (
+ <Switch
+ aria-label={t('gateway.enableConnection')}
+ checked={isConnected || isConnecting}
+ loading={isConnecting}
+ size="small"
+ onChange={handleSwitchChange}
+ />
+ )}
</Flexbox>
</Flexbox>
<span className={styles.scopeHint}>{connectionHint}</span>
@@ -136,7 +172,7 @@ const DeviceGateway = memo(() => {
title={t('gateway.title')}
tooltipProps={{ placement: 'bottomRight' }}
/>
- {isConnected && <div className={styles.greenDot} />}
+ {scopeConnected && <div className={styles.greenDot} />}
</div>
</Popover>
);
@@ -146,9 +182,9 @@ const DeviceGatewayWithAuth = memo(() => {
const isSyncActive = useElectronStore(electronSyncSelectors.isSyncActive);
const activeWorkspaceSlug = useActiveWorkspaceSlug();
- if (!isSyncActive || activeWorkspaceSlug) return null;
+ if (!isSyncActive) return null;
- return <DeviceGateway />;
+ return <DeviceGateway workspaceScoped={!!activeWorkspaceSlug} />;
});
export default DeviceGatewayWithAuth;