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(device-gateway): stop laundering a failed device read into "none online" (#19022)

Arvin Xua2dcef079282
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index aab398654b6..aff2824a934 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -201,6 +201,42 @@ describe('DeviceGateway', () => {
]);
});
+ it('absorbs a transient failure instead of reporting an empty pool', async () => {
+ // The online set decides which devices a run may reach, so one dropped
+ // connection must not read as "every device is offline".
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const connectedAt = Date.parse('2025-01-15T10:30:00Z');
+ mockClient.queryDeviceList
+ .mockRejectedValueOnce(new Error('fetch failed'))
+ .mockResolvedValueOnce([
+ { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },
+ ]);
+
+ const result = await new DeviceGateway().queryDeviceList('user-1');
+
+ expect(mockClient.queryDeviceList).toHaveBeenCalledTimes(2);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ deviceId: 'dev-1', online: true });
+ });
+
+ it('reports the fallback out loud when the gateway stays unreachable', async () => {
+ // The old bare `catch {}` made this failure invisible: a device-bound run
+ // degraded to the cloud sandbox with no breadcrumb in any log.
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.queryDeviceList.mockRejectedValue(new Error('fetch failed'));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = await new DeviceGateway().queryDeviceList('user-1', 'ws-1');
+
+ expect(result).toEqual([]);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('queryDeviceList'),
+ expect.objectContaining({ error: 'fetch failed', userId: 'user-1', workspaceId: 'ws-1' }),
+ );
+ });
+
it('should return empty array on error', async () => {
mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index baabd308452..fcda58dbf14 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -85,9 +85,49 @@ const assertPathsWithinWorkspace = (
export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };
+/** One extra attempt for a device read; see `readDevices`. */
+const DEVICE_READ_ATTEMPTS = 2;
+const DEVICE_READ_RETRY_DELAY_MS = 250;
+
export class DeviceGateway {
private client: GatewayHttpClient | null = null;
+ /**
+ * Run a device READ, retrying once and reporting the fallback out loud.
+ *
+ * These reads decide which devices a run may reach, and the fallback value is
+ * indistinguishable from a legitimately empty pool: a single dropped
+ * connection therefore reads as "every device is offline", which sends a
+ * device-bound run to the cloud sandbox instead. Retrying absorbs the blip,
+ * and the warning leaves the breadcrumb that was missing entirely β€” the old
+ * bare `catch {}` made this failure invisible in every log.
+ */
+ private async readDevices<T>(
+ label: string,
+ context: { userId: string; workspaceId?: string },
+ read: () => Promise<T>,
+ fallback: T,
+ ): Promise<T> {
+ for (let attempt = 1; attempt <= DEVICE_READ_ATTEMPTS; attempt++) {
+ try {
+ return await read();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (attempt < DEVICE_READ_ATTEMPTS) {
+ await new Promise((resolve) => setTimeout(resolve, DEVICE_READ_RETRY_DELAY_MS));
+ continue;
+ }
+ console.warn(`[DeviceGateway] ${label} failed; treating the online set as empty`, {
+ attempts: attempt,
+ error: message,
+ userId: context.userId,
+ workspaceId: context.workspaceId,
+ });
+ }
+ }
+ return fallback;
+ }
+
get isConfigured(): boolean {
return !!gatewayEnv.DEVICE_GATEWAY_URL;
}
@@ -96,11 +136,12 @@ export class DeviceGateway {
const client = this.getClient();
if (!client) return { deviceCount: 0, online: false };
- try {
- return await client.queryDeviceStatus(userId, workspaceId);
- } catch {
- return { deviceCount: 0, online: false };
- }
+ return this.readDevices(
+ 'queryDeviceStatus',
+ { userId, workspaceId },
+ () => client.queryDeviceStatus(userId, workspaceId),
+ { deviceCount: 0, online: false },
+ );
}
// Pass a `workspaceId` to address a workspace-owned device pool (the gateway
@@ -109,40 +150,43 @@ export class DeviceGateway {
const client = this.getClient();
if (!client) return [];
- try {
- const devices = await client.queryDeviceList(userId, workspaceId);
- // The gateway already dedupes to one entry per physical device, with its
- // live connections nested as `channels`. Map to the runtime shape; every
- // returned device has at least one channel, so it's online.
- return devices.map((d) => ({
- // `channels` may be absent if the gateway worker deploy lags behind the
- // server (separate Cloudflare deploy); tolerate the legacy flat shape.
- //
- // Sorted newest-first because every consumer reads `channels[0]` as
- // "this device's current connection" β€” the settings row's
- // "Connected {time}", a ghost row's `lastSeen`, its hostname/platform
- // fallback β€” while `sortDevicesByActivity` ranks by the FRESHEST
- // channel. The gateway promises no order, so leaving it raw lets a
- // multi-channel device rank by one connection and get labelled with
- // another. Normalising here (the single entry point both `listDevices`
- // and `getScopedOnlineDevices` pull channels through) makes
- // `channels[0]` mean the same thing everywhere.
- channels: (d.channels ?? [])
- .map((c) => ({
- channel: c.channel,
- connectedAt: new Date(c.connectedAt).toISOString(),
- connectionId: c.connectionId,
- }))
- .sort((a, b) => Date.parse(b.connectedAt) - Date.parse(a.connectedAt)),
- deviceId: d.deviceId,
- hostname: d.hostname,
- lastSeen: new Date(d.connectedAt).toISOString(),
- online: true,
- platform: d.platform,
- }));
- } catch {
- return [];
- }
+ return this.readDevices(
+ 'queryDeviceList',
+ { userId, workspaceId },
+ async () => {
+ const devices = await client.queryDeviceList(userId, workspaceId);
+ // The gateway already dedupes to one entry per physical device, with its
+ // live connections nested as `channels`. Map to the runtime shape; every
+ // returned device has at least one channel, so it's online.
+ return devices.map((d) => ({
+ // `channels` may be absent if the gateway worker deploy lags behind the
+ // server (separate Cloudflare deploy); tolerate the legacy flat shape.
+ //
+ // Sorted newest-first because every consumer reads `channels[0]` as
+ // "this device's current connection" β€” the settings row's
+ // "Connected {time}", a ghost row's `lastSeen`, its hostname/platform
+ // fallback β€” while `sortDevicesByActivity` ranks by the FRESHEST
+ // channel. The gateway promises no order, so leaving it raw lets a
+ // multi-channel device rank by one connection and get labelled with
+ // another. Normalising here (the single entry point both `listDevices`
+ // and `getScopedOnlineDevices` pull channels through) makes
+ // `channels[0]` mean the same thing everywhere.
+ channels: (d.channels ?? [])
+ .map((c) => ({
+ channel: c.channel,
+ connectedAt: new Date(c.connectedAt).toISOString(),
+ connectionId: c.connectionId,
+ }))
+ .sort((a, b) => Date.parse(b.connectedAt) - Date.parse(a.connectedAt)),
+ deviceId: d.deviceId,
+ hostname: d.hostname,
+ lastSeen: new Date(d.connectedAt).toISOString(),
+ online: true,
+ platform: d.platform,
+ }));
+ },
+ [],
+ );
}
async queryDeviceSystemInfo(
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index dbf71c4cee4..dbdc4e591ef 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -59,12 +59,13 @@ describe('GatewayHttpClient', () => {
);
});
- it('should return defaults on non-ok response', async () => {
+ it('surfaces a non-ok response instead of reporting nothing online', async () => {
+ // Previously returned `{ deviceCount: 0, online: false }`, which is
+ // indistinguishable from a genuinely empty pool β€” the caller could not
+ // tell "no devices" from "the gateway never answered".
mockFetch({ ok: false, status: 500 });
- const result = await client.queryDeviceStatus('user-1');
-
- expect(result).toEqual({ deviceCount: 0, online: false });
+ await expect(client.queryDeviceStatus('user-1')).rejects.toThrow('responded 500');
});
it('should handle missing fields in response', async () => {
@@ -94,12 +95,23 @@ describe('GatewayHttpClient', () => {
expect(result).toEqual(devices);
});
- it('should return empty array on non-ok response', async () => {
- mockFetch({ ok: false });
+ it('surfaces a non-ok response instead of reporting an empty pool', async () => {
+ // The empty array used to be returned for a 5xx too, so a gateway blip
+ // became an authoritative "every device is offline" for the run that
+ // asked β€” which is what silently rerouted device-bound work elsewhere.
+ mockFetch({ ok: false, status: 503 });
- const result = await client.queryDeviceList('user-1');
+ await expect(client.queryDeviceList('user-1')).rejects.toThrow('responded 503');
+ });
- expect(result).toEqual([]);
+ it('bounds the read with a timeout', async () => {
+ mockFetch({ json: vi.fn().mockResolvedValue({ devices: [] }), ok: true });
+
+ await client.queryDeviceList('user-1');
+
+ // `post` applies no deadline unless asked, so an unanswered read would
+ // otherwise hang for as long as the socket stays open.
+ expect(vi.mocked(fetch).mock.calls[0][1]).toMatchObject({ signal: expect.anything() });
});
it('should return empty array when devices is not an array', async () => {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 8cea557c605..de1d52dbdef 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -6,6 +6,12 @@ import type {
} from './types';
const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
+/**
+ * Device *reads* are on the critical path of every routing decision, and `post`
+ * has no deadline of its own β€” an unanswered read would otherwise hang for as
+ * long as the socket stays open.
+ */
+const DEVICE_QUERY_TIMEOUT_MS = 10_000;
const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
export interface DeviceStatusResult {
@@ -47,8 +53,15 @@ export class GatewayHttpClient {
}
async queryDeviceStatus(userId: string, workspaceId?: string): Promise<DeviceStatusResult> {
- const res = await this.post('/api/device/status', { userId, workspaceId });
- if (!res.ok) return { deviceCount: 0, online: false };
+ const res = await this.post(
+ '/api/device/status',
+ { userId, workspaceId },
+ { timeout: DEVICE_QUERY_TIMEOUT_MS },
+ );
+ // A gateway that answered with an error did not tell us "nothing is
+ // online" β€” it told us nothing. Reporting the two as the same value is how
+ // a transient 5xx became an authoritative "all devices offline" downstream.
+ if (!res.ok) throw new Error(`Device gateway /api/device/status responded ${res.status}`);
const data = await res.json();
return {
@@ -58,8 +71,14 @@ export class GatewayHttpClient {
}
async queryDeviceList(userId: string, workspaceId?: string): Promise<GatewayDevice[]> {
- const res = await this.post('/api/device/devices', { userId, workspaceId });
- if (!res.ok) return [];
+ const res = await this.post(
+ '/api/device/devices',
+ { userId, workspaceId },
+ { timeout: DEVICE_QUERY_TIMEOUT_MS },
+ );
+ // See `queryDeviceStatus`: an errored read is an UNKNOWN online set, and
+ // only the caller can decide what to do about that.
+ if (!res.ok) throw new Error(`Device gateway /api/device/devices responded ${res.status}`);
const data = await res.json();
return Array.isArray(data.devices) ? data.devices : [];