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.

✨ feat(device): connectionId + channel routing in gateway client & device list (#15322)

Arvin Xu063fa61c4976
diff --git a/apps/device-gateway/package.json b/apps/device-gateway/package.json
deleted file mode 100644
index 2ee855a0cfc..00000000000
--- a/apps/device-gateway/package.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "@lobechat/device-gateway",
- "version": "0.1.0",
- "private": true,
- "scripts": {
- "deploy": "wrangler deploy",
- "dev": "wrangler dev",
- "test": "vitest run",
- "test:watch": "vitest",
- "type-check": "tsc --noEmit"
- },
- "dependencies": {
- "hono": "^4.12.5",
- "jose": "^6.1.3"
- },
- "devDependencies": {
- "@cloudflare/vitest-pool-workers": "^0.12.19",
- "@cloudflare/workers-types": "^4.20260301.1",
- "typescript": "^6.0.3",
- "vitest": "~3.2.4",
- "wrangler": "^4.70.0"
- }
-}
diff --git a/apps/device-gateway/scripts/extract-public-key.mjs b/apps/device-gateway/scripts/extract-public-key.mjs
deleted file mode 100755
index 042dbe74d48..00000000000
--- a/apps/device-gateway/scripts/extract-public-key.mjs
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Extract RS256 public key from JWKS_KEY environment variable.
- * Output is the JSON string to use with `wrangler secret put JWKS_PUBLIC_KEY`.
- *
- * Usage:
- * JWKS_KEY='{"keys":[...]}' node scripts/extract-public-key.mjs
- * # or load from .env
- * node --env-file=../../.env scripts/extract-public-key.mjs
- */
-
-const jwksString = process.env.JWKS_KEY;
-
-if (!jwksString) {
- console.error('Error: JWKS_KEY environment variable is not set.');
- process.exit(1);
-}
-
-const jwks = JSON.parse(jwksString);
-const privateKey = jwks.keys?.find((k) => k.alg === 'RS256' && k.kty === 'RSA');
-
-if (!privateKey) {
- console.error('Error: No RS256 RSA key found in JWKS_KEY.');
- process.exit(1);
-}
-
-const publicJwks = {
- keys: [
- {
- alg: privateKey.alg,
- e: privateKey.e,
- kid: privateKey.kid,
- kty: privateKey.kty,
- n: privateKey.n,
- use: privateKey.use,
- },
- ],
-};
-
-// Remove undefined fields
-for (const key of publicJwks.keys) {
- for (const [k, v] of Object.entries(key)) {
- if (v === undefined) delete key[k];
- }
-}
-
-console.log(JSON.stringify(publicJwks));
diff --git a/apps/device-gateway/src/DeviceGatewayDO.ts b/apps/device-gateway/src/DeviceGatewayDO.ts
deleted file mode 100644
index 739ce866d69..00000000000
--- a/apps/device-gateway/src/DeviceGatewayDO.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { Hono } from 'hono';
-
-import { resolveSocketAuth, verifyApiKeyToken, verifyDesktopToken } from './auth';
-import type { AgentRunRequestMessage, DeviceAttachment, Env } from './types';
-
-const AUTH_TIMEOUT = 10_000; // 10s to authenticate after connect
-const HEARTBEAT_TIMEOUT = 90_000; // 90s without heartbeat β†’ close
-const HEARTBEAT_CHECK_INTERVAL = 90_000; // check every 90s
-
-export class DeviceGatewayDO extends DurableObject<Env> {
- private pendingRequests = new Map<
- string,
- {
- resolve: (result: any) => void;
- timer: ReturnType<typeof setTimeout>;
- }
- >();
-
- private router = new Hono()
- .all('/api/device/status', async () => {
- const sockets = this.getAuthenticatedSockets();
- return Response.json({
- deviceCount: sockets.length,
- online: sockets.length > 0,
- });
- })
- .post('/api/device/tool-call', async (c) => {
- return this.handleToolCall(c.req.raw);
- })
- .post('/api/device/system-info', async (c) => {
- return this.handleSystemInfo(c.req.raw);
- })
- .post('/api/device/agent/run', async (c) => {
- return this.handleAgentRun(c.req.raw);
- })
- .all('/api/device/devices', async () => {
- const sockets = this.getAuthenticatedSockets();
- const devices = sockets.map((ws) => ws.deserializeAttachment() as DeviceAttachment);
- return Response.json({ devices });
- });
-
- async fetch(request: Request): Promise<Response> {
- // ─── WebSocket upgrade (from Desktop) ───
- if (request.headers.get('Upgrade') === 'websocket') {
- return this.handleWebSocketUpgrade(request);
- }
-
- // ─── HTTP API routes ───
- return this.router.fetch(request);
- }
-
- // ─── Hibernation Handlers ───
-
- async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
- const data = JSON.parse(message as string);
- const att = ws.deserializeAttachment() as DeviceAttachment;
-
- // ─── Auth message handling ───
- if (data.type === 'auth') {
- if (att.authenticated) return; // Already authenticated, ignore
-
- try {
- const token = data.token as string | undefined;
- const tokenType = data.tokenType as 'apiKey' | 'jwt' | 'serviceToken' | undefined;
- const serverUrl = data.serverUrl as string | undefined;
- const storedUserId = await this.ctx.storage.get<string>('_userId');
-
- const verifiedUserId = await resolveSocketAuth({
- serverUrl,
- serviceToken: this.env.SERVICE_TOKEN,
- storedUserId,
- token,
- tokenType,
- verifyApiKey: verifyApiKeyToken,
- verifyJwt: async (jwt) => {
- const result = await verifyDesktopToken(this.env, jwt);
- return { userId: result.userId };
- },
- });
-
- // Verify userId matches the DO routing
- if (storedUserId && verifiedUserId !== storedUserId) {
- throw new Error('userId mismatch');
- }
-
- // Mark as authenticated
- att.authenticated = true;
- att.authDeadline = undefined;
- ws.serializeAttachment(att);
-
- ws.send(JSON.stringify({ type: 'auth_success' }));
-
- // Schedule heartbeat check for authenticated connections
- await this.scheduleHeartbeatCheck();
- } catch (err) {
- const reason = err instanceof Error ? err.message : 'Authentication failed';
- ws.send(JSON.stringify({ reason, type: 'auth_failed' }));
- ws.close(1008, reason);
- }
- return;
- }
-
- // ─── Reject unauthenticated messages ───
- if (!att.authenticated) return;
-
- // ─── Business messages (authenticated only) ───
- if (
- data.type === 'tool_call_response' ||
- data.type === 'system_info_response' ||
- data.type === 'agent_run_ack'
- ) {
- const pending = this.pendingRequests.get(data.requestId ?? data.operationId);
- if (pending) {
- clearTimeout(pending.timer);
- pending.resolve(data.type === 'agent_run_ack' ? data : data.result);
- this.pendingRequests.delete(data.requestId ?? data.operationId);
- }
- }
-
- if (data.type === 'heartbeat') {
- att.lastHeartbeat = Date.now();
- ws.serializeAttachment(att);
- ws.send(JSON.stringify({ type: 'heartbeat_ack' }));
- }
- }
-
- async webSocketClose(_ws: WebSocket, _code: number) {
- // Hibernation API handles connection cleanup automatically
- }
-
- async webSocketError(ws: WebSocket, _error: unknown) {
- ws.close(1011, 'Internal error');
- }
-
- // ─── Heartbeat Timeout ───
-
- async alarm() {
- const now = Date.now();
- const closedSockets = new Set<WebSocket>();
-
- for (const ws of this.ctx.getWebSockets()) {
- const att = ws.deserializeAttachment() as DeviceAttachment;
-
- // Auth timeout: close unauthenticated connections past deadline
- if (!att.authenticated && att.authDeadline && now > att.authDeadline) {
- ws.send(JSON.stringify({ reason: 'Authentication timeout', type: 'auth_failed' }));
- ws.close(1008, 'Authentication timeout');
- closedSockets.add(ws);
- continue;
- }
-
- // Heartbeat timeout: only for authenticated connections
- if (att.authenticated && now - att.lastHeartbeat > HEARTBEAT_TIMEOUT) {
- ws.close(1000, 'Heartbeat timeout');
- closedSockets.add(ws);
- }
- }
-
- // Keep alarm running while there are active connections
- const remaining = this.ctx.getWebSockets().filter((ws) => !closedSockets.has(ws));
- if (remaining.length > 0) {
- await this.scheduleHeartbeatCheck();
- }
- }
-
- // ─── WebSocket Upgrade ───
-
- private async handleWebSocketUpgrade(request: Request): Promise<Response> {
- const url = new URL(request.url);
- const userId = request.headers.get('X-User-Id');
-
- const deviceId = url.searchParams.get('deviceId') || 'unknown';
- const hostname = url.searchParams.get('hostname') || '';
- const platform = url.searchParams.get('platform') || '';
-
- // Close stale connection from the same device
- for (const ws of this.ctx.getWebSockets()) {
- const att = ws.deserializeAttachment() as DeviceAttachment;
- if (att.deviceId === deviceId) {
- ws.close(1000, 'Replaced by new connection');
- }
- }
-
- const pair = new WebSocketPair();
- const [client, server] = Object.values(pair);
-
- this.ctx.acceptWebSocket(server);
-
- const now = Date.now();
- server.serializeAttachment({
- authDeadline: now + AUTH_TIMEOUT,
- authenticated: false,
- connectedAt: now,
- deviceId,
- hostname,
- lastHeartbeat: now,
- platform,
- } satisfies DeviceAttachment);
-
- if (userId) {
- await this.ctx.storage.put('_userId', userId);
- }
-
- // Schedule auth timeout check (10s)
- await this.scheduleAuthTimeout();
-
- return new Response(null, { status: 101, webSocket: client });
- }
-
- private async scheduleAuthTimeout() {
- const currentAlarm = await this.ctx.storage.getAlarm();
- if (!currentAlarm) {
- await this.ctx.storage.setAlarm(Date.now() + AUTH_TIMEOUT);
- }
- }
-
- private async scheduleHeartbeatCheck() {
- const currentAlarm = await this.ctx.storage.getAlarm();
- if (!currentAlarm) {
- await this.ctx.storage.setAlarm(Date.now() + HEARTBEAT_CHECK_INTERVAL);
- }
- }
-
- // ─── Helpers ───
-
- private getAuthenticatedSockets(): WebSocket[] {
- return this.ctx.getWebSockets().filter((ws) => {
- const att = ws.deserializeAttachment() as DeviceAttachment;
- return att.authenticated;
- });
- }
-
- // ─── System Info RPC ───
-
- private async handleSystemInfo(request: Request): Promise<Response> {
- const sockets = this.getAuthenticatedSockets();
- if (sockets.length === 0) {
- return Response.json({ error: 'DEVICE_OFFLINE', success: false }, { status: 503 });
- }
-
- const { deviceId, timeout = 10_000 } = (await request.json()) as {
- deviceId?: string;
- timeout?: number;
- };
- const requestId = crypto.randomUUID();
-
- const targetWs = deviceId
- ? sockets.find((ws) => {
- const att = ws.deserializeAttachment() as DeviceAttachment;
- return att.deviceId === deviceId;
- })
- : sockets[0];
-
- if (!targetWs) {
- return Response.json({ error: 'DEVICE_NOT_FOUND', success: false }, { status: 503 });
- }
-
- try {
- const result = await new Promise((resolve, reject) => {
- const timer = setTimeout(() => {
- this.pendingRequests.delete(requestId);
- reject(new Error('TIMEOUT'));
- }, timeout);
-
- this.pendingRequests.set(requestId, { resolve, timer });
-
- targetWs.send(
- JSON.stringify({
- requestId,
- type: 'system_info_request',
- }),
- );
- });
-
- return Response.json({ success: true, ...(result as object) });
- } catch (err) {
- return Response.json(
- {
- error: (err as Error).message,
- success: false,
- },
- { status: 504 },
- );
- }
- }
-
- // ─── Agent Run RPC ───
-
- private async handleAgentRun(request: Request): Promise<Response> {
- const sockets = this.getAuthenticatedSockets();
- if (sockets.length === 0) {
- return Response.json({ error: 'DEVICE_OFFLINE', success: false }, { status: 503 });
- }
-
- const body = (await request.json()) as {
- agentType: 'claude-code' | 'codex';
- cwd?: string;
- deviceId?: string;
- jwt: string;
- operationId: string;
- prompt: string;
- resumeSessionId?: string;
- timeout?: number;
- topicId: string;
- };
- const { deviceId, timeout = 10_000, ...runParams } = body;
-
- const targetWs = deviceId
- ? sockets.find((ws) => {
- const att = ws.deserializeAttachment() as DeviceAttachment;
- return att.deviceId === deviceId;
- })
- : sockets[0];
-
- if (!targetWs) {
- return Response.json({ error: 'DEVICE_NOT_FOUND', success: false }, { status: 503 });
- }
-
- try {
- const ack = await new Promise<{ status: string }>((resolve, reject) => {
- const timer = setTimeout(() => {
- this.pendingRequests.delete(runParams.operationId);
- reject(new Error('TIMEOUT'));
- }, timeout);
-
- this.pendingRequests.set(runParams.operationId, { resolve, timer });
-
- const msg: AgentRunRequestMessage = { type: 'agent_run_request', ...runParams };
- targetWs.send(JSON.stringify(msg));
- });
-
- if (ack.status === 'rejected') {
- return Response.json({ error: 'DEVICE_REJECTED', success: false }, { status: 422 });
- }
- return Response.json({ success: true });
- } catch (err) {
- return Response.json({ error: (err as Error).message, success: false }, { status: 504 });
- }
- }
-
- // ─── Tool Call RPC ───
-
- private async handleToolCall(request: Request): Promise<Response> {
- const sockets = this.getAuthenticatedSockets();
- if (sockets.length === 0) {
- return Response.json(
- { content: 'Desktop device offline', error: 'DEVICE_OFFLINE', success: false },
- { status: 503 },
- );
- }
-
- const {
- deviceId,
- timeout = 30_000,
- toolCall,
- } = (await request.json()) as {
- deviceId?: string;
- timeout?: number;
- toolCall: unknown;
- };
- const requestId = crypto.randomUUID();
-
- // Select target device (specified > first available)
- const targetWs = deviceId
- ? sockets.find((ws) => {
- const att = ws.deserializeAttachment() as DeviceAttachment;
- return att.deviceId === deviceId;
- })
- : sockets[0];
-
- if (!targetWs) {
- return Response.json({ error: 'DEVICE_NOT_FOUND', success: false }, { status: 503 });
- }
-
- try {
- const result = await new Promise((resolve, reject) => {
- const timer = setTimeout(() => {
- this.pendingRequests.delete(requestId);
- reject(new Error('TIMEOUT'));
- }, timeout);
-
- this.pendingRequests.set(requestId, { resolve, timer });
-
- targetWs.send(
- JSON.stringify({
- requestId,
- toolCall,
- type: 'tool_call_request',
- }),
- );
- });
-
- return Response.json({ success: true, ...(result as object) });
- } catch (err) {
- return Response.json(
- {
- content: `Tool call timed out (${timeout / 1000}s)`,
- error: (err as Error).message,
- success: false,
- },
- { status: 504 },
- );
- }
- }
-}
diff --git a/apps/device-gateway/src/auth.test.ts b/apps/device-gateway/src/auth.test.ts
deleted file mode 100644
index 54f879f6c9a..00000000000
--- a/apps/device-gateway/src/auth.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { resolveSocketAuth } from './auth';
-
-describe('resolveSocketAuth', () => {
- it('rejects missing token', async () => {
- const verifyApiKey = vi.fn();
- const verifyJwt = vi.fn();
-
- await expect(
- resolveSocketAuth({
- serviceToken: 'service-secret',
- storedUserId: 'user-123',
- verifyApiKey,
- verifyJwt,
- }),
- ).rejects.toThrow('Missing token');
-
- expect(verifyApiKey).not.toHaveBeenCalled();
- expect(verifyJwt).not.toHaveBeenCalled();
- });
-
- it('rejects the real service token when storedUserId is missing', async () => {
- const verifyApiKey = vi.fn();
- const verifyJwt = vi.fn();
-
- await expect(
- resolveSocketAuth({
- serviceToken: 'service-secret',
- token: 'service-secret',
- tokenType: 'serviceToken',
- verifyApiKey,
- verifyJwt,
- }),
- ).rejects.toThrow('Missing userId');
-
- expect(verifyApiKey).not.toHaveBeenCalled();
- expect(verifyJwt).not.toHaveBeenCalled();
- });
- it('rejects clients that only self-declare serviceToken mode', async () => {
- const verifyApiKey = vi.fn();
- const verifyJwt = vi.fn().mockRejectedValue(new Error('invalid jwt'));
-
- await expect(
- resolveSocketAuth({
- serviceToken: 'service-secret',
- storedUserId: 'user-123',
- token: 'attacker-token',
- tokenType: 'serviceToken',
- verifyApiKey,
- verifyJwt,
- }),
- ).rejects.toThrow('invalid jwt');
-
- expect(verifyApiKey).not.toHaveBeenCalled();
- expect(verifyJwt).toHaveBeenCalledWith('attacker-token');
- });
-
- it('treats a forged serviceToken claim with a valid JWT as JWT auth', async () => {
- const verifyApiKey = vi.fn();
- const verifyJwt = vi.fn().mockResolvedValue({ userId: 'user-123' });
-
- await expect(
- resolveSocketAuth({
- serviceToken: 'service-secret',
- storedUserId: 'user-123',
- token: 'valid-jwt',
- tokenType: 'serviceToken',
- verifyApiKey,
- verifyJwt,
- }),
- ).resolves.toBe('user-123');
-
- expect(verifyApiKey).not.toHaveBeenCalled();
- expect(verifyJwt).toHaveBeenCalledWith('valid-jwt');
- });
-
- it('accepts the real service token', async () => {
- const verifyApiKey = vi.fn();
- const verifyJwt = vi.fn();
-
- await expect(
- resolveSocketAuth({
- serviceToken: 'service-secret',
- storedUserId: 'user-123',
- token: 'service-secret',
- tokenType: 'serviceToken',
- verifyApiKey,
- verifyJwt,
- }),
- ).resolves.toBe('user-123');
-
- expect(verifyApiKey).not.toHaveBeenCalled();
- expect(verifyJwt).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/device-gateway/src/auth.ts b/apps/device-gateway/src/auth.ts
deleted file mode 100644
index 39e766556b0..00000000000
--- a/apps/device-gateway/src/auth.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { importJWK, jwtVerify } from 'jose';
-
-import type { Env } from './types';
-
-let cachedKey: CryptoKey | null = null;
-
-interface CurrentUserResponse {
- data?: {
- id?: string;
- userId?: string;
- };
- error?: string;
- message?: string;
- success?: boolean;
-}
-
-export interface ResolveSocketAuthOptions {
- serverUrl?: string;
- serviceToken: string;
- storedUserId?: string;
- token?: string;
- tokenType?: 'apiKey' | 'jwt' | 'serviceToken';
- verifyApiKey: (serverUrl: string, token: string) => Promise<{ userId: string }>;
- verifyJwt: (token: string) => Promise<{ userId: string }>;
-}
-
-async function getPublicKey(env: Env): Promise<CryptoKey> {
- if (cachedKey) return cachedKey;
-
- const jwks = JSON.parse(env.JWKS_PUBLIC_KEY);
- const rsaKey = jwks.keys.find((k: any) => k.alg === 'RS256');
-
- if (!rsaKey) {
- throw new Error('No RS256 key found in JWKS_PUBLIC_KEY');
- }
-
- cachedKey = (await importJWK(rsaKey, 'RS256')) as CryptoKey;
- return cachedKey;
-}
-
-export async function verifyDesktopToken(
- env: Env,
- token: string,
-): Promise<{ clientId: string; userId: string }> {
- const publicKey = await getPublicKey(env);
- const { payload } = await jwtVerify(token, publicKey, {
- algorithms: ['RS256'],
- });
-
- if (!payload.sub) throw new Error('Missing sub claim');
-
- return {
- clientId: payload.client_id as string,
- userId: payload.sub,
- };
-}
-
-export async function verifyApiKeyToken(
- serverUrl: string,
- token: string,
-): Promise<{ userId: string }> {
- const normalizedServerUrl = new URL(serverUrl).toString().replace(/\/$/, '');
-
- const response = await fetch(`${normalizedServerUrl}/api/v1/users/me`, {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- });
-
- let body: CurrentUserResponse | undefined;
- try {
- body = (await response.json()) as CurrentUserResponse;
- } catch {
- throw new Error(`Failed to parse response from ${normalizedServerUrl}/api/v1/users/me.`);
- }
-
- if (!response.ok || body?.success === false) {
- throw new Error(
- body?.error || body?.message || `Request failed with status ${response.status}.`,
- );
- }
-
- const userId = body?.data?.id || body?.data?.userId;
- if (!userId) {
- throw new Error('Current user response did not include a user id.');
- }
-
- return { userId };
-}
-
-export async function resolveSocketAuth(options: ResolveSocketAuthOptions): Promise<string> {
- const { serverUrl, serviceToken, storedUserId, token, tokenType, verifyApiKey, verifyJwt } =
- options;
-
- if (!token) throw new Error('Missing token');
-
- if (tokenType === 'apiKey') {
- if (!serverUrl) throw new Error('Missing serverUrl');
- const result = await verifyApiKey(serverUrl, token);
- return result.userId;
- }
-
- if (token === serviceToken) {
- if (!storedUserId) throw new Error('Missing userId');
- return storedUserId;
- }
-
- const result = await verifyJwt(token);
- return result.userId;
-}
diff --git a/apps/device-gateway/src/index.ts b/apps/device-gateway/src/index.ts
deleted file mode 100644
index c1c61666e20..00000000000
--- a/apps/device-gateway/src/index.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { Hono } from 'hono';
-
-import { DeviceGatewayDO } from './DeviceGatewayDO';
-import type { Env } from './types';
-
-export { DeviceGatewayDO };
-
-const app = new Hono<{ Bindings: Env }>();
-
-// ─── Health check ───
-app.get('/health', (c) => c.text('OK'));
-
-// ─── Auth middleware for service APIs ───
-const serviceAuth = (): ((c: any, next: () => Promise<void>) => Promise<Response | void>) => {
- return async (c, next) => {
- const authHeader = c.req.header('Authorization');
- if (authHeader !== `Bearer ${c.env.SERVICE_TOKEN}`) {
- return c.text('Unauthorized', 401);
- }
- await next();
- };
-};
-
-// ─── Desktop WebSocket connection ───
-app.get('/ws', async (c) => {
- const userId = c.req.query('userId');
- if (!userId) return c.text('Missing userId', 400);
-
- const id = c.env.DEVICE_GATEWAY.idFromName(`user:${userId}`);
- const stub = c.env.DEVICE_GATEWAY.get(id);
-
- const headers = new Headers(c.req.raw.headers);
- headers.set('X-User-Id', userId);
- return stub.fetch(new Request(c.req.raw, { headers }));
-});
-
-// ─── Vercel Agent HTTP API ───
-app.all('/api/device/*', serviceAuth(), async (c) => {
- const body = (await c.req.raw.clone().json()) as { userId: string };
- if (!body.userId) return c.text('Missing userId', 400);
-
- const id = c.env.DEVICE_GATEWAY.idFromName(`user:${body.userId}`);
- const stub = c.env.DEVICE_GATEWAY.get(id);
- return stub.fetch(c.req.raw);
-});
-
-export default app;
diff --git a/apps/device-gateway/src/types.ts b/apps/device-gateway/src/types.ts
deleted file mode 100644
index 73098fa52ac..00000000000
--- a/apps/device-gateway/src/types.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-export interface Env {
- DEVICE_GATEWAY: DurableObjectNamespace;
- JWKS_PUBLIC_KEY: string;
- SERVICE_TOKEN: string;
-}
-
-// ─── Device Info ───
-
-export interface DeviceAttachment {
- authDeadline?: number;
- authenticated: boolean;
- connectedAt: number;
- deviceId: string;
- hostname: string;
- lastHeartbeat: number;
- platform: string;
-}
-
-// ─── WebSocket Protocol Messages ───
-
-// Desktop β†’ CF
-export interface AuthMessage {
- serverUrl?: string;
- token: string;
- tokenType?: 'apiKey' | 'jwt' | 'serviceToken';
- type: 'auth';
-}
-
-export interface HeartbeatMessage {
- type: 'heartbeat';
-}
-
-export interface ToolCallResponseMessage {
- requestId: string;
- result: {
- content: string;
- error?: string;
- success: boolean;
- };
- type: 'tool_call_response';
-}
-
-export interface SystemInfoResponseMessage {
- requestId: string;
- result: DeviceSystemInfo;
- type: 'system_info_response';
-}
-
-export interface DeviceSystemInfo {
- arch: string;
- desktopPath: string;
- documentsPath: string;
- downloadsPath: string;
- homePath: string;
- musicPath: string;
- picturesPath: string;
- userDataPath: string;
- videosPath: string;
- workingDirectory: string;
-}
-
-// CF β†’ Desktop
-export interface AuthSuccessMessage {
- type: 'auth_success';
-}
-
-export interface AuthFailedMessage {
- reason: string;
- type: 'auth_failed';
-}
-
-export interface HeartbeatAckMessage {
- type: 'heartbeat_ack';
-}
-
-export interface AuthExpiredMessage {
- type: 'auth_expired';
-}
-
-export interface ToolCallRequestMessage {
- requestId: string;
- toolCall: {
- apiName: string;
- arguments: string;
- identifier: string;
- };
- type: 'tool_call_request';
-}
-
-export interface SystemInfoRequestMessage {
- requestId: string;
- type: 'system_info_request';
-}
-
-/**
- * CF β†’ Desktop: request the desktop to spawn `lh hetero exec` for a
- * heterogeneous agent run. The JWT is operation-scoped (4h TTL) and only
- * grants `heteroIngest` / `heteroFinish` for this operationId.
- */
-export interface AgentRunRequestMessage {
- agentType: 'claude-code' | 'codex';
- /** Working directory to pass to `lh hetero exec --cwd`. */
- cwd?: string;
- /** Operation-scoped JWT signed by the server β€” inject as LOBEHUB_JWT env. */
- jwt: string;
- operationId: string;
- /** Plain-text prompt to pass via `lh hetero exec --prompt`. */
- prompt: string;
- /** Native CLI session id for `lh hetero exec --resume`. */
- resumeSessionId?: string;
- topicId: string;
- type: 'agent_run_request';
-}
-
-/** Desktop β†’ CF: acknowledgement for an `agent_run_request`. */
-export interface AgentRunAckMessage {
- operationId: string;
- reason?: string;
- status: 'accepted' | 'rejected';
- type: 'agent_run_ack';
-}
-
-export type ClientMessage =
- | AgentRunAckMessage
- | AuthMessage
- | HeartbeatMessage
- | SystemInfoResponseMessage
- | ToolCallResponseMessage;
-export type ServerMessage =
- | AgentRunRequestMessage
- | AuthExpiredMessage
- | AuthFailedMessage
- | AuthSuccessMessage
- | HeartbeatAckMessage
- | SystemInfoRequestMessage
- | ToolCallRequestMessage;
diff --git a/apps/device-gateway/tsconfig.json b/apps/device-gateway/tsconfig.json
deleted file mode 100644
index d63ef5e826a..00000000000
--- a/apps/device-gateway/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "ESNext",
- "module": "ESNext",
- "moduleResolution": "bundler",
- "lib": ["ESNext"],
- "types": ["@cloudflare/workers-types"],
- "strict": true,
- "noEmit": true,
- "skipLibCheck": true,
- "esModuleInterop": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true,
- "isolatedModules": true
- },
- "include": ["src"]
-}
diff --git a/apps/device-gateway/wrangler.toml b/apps/device-gateway/wrangler.toml
deleted file mode 100644
index 32863b74dfc..00000000000
--- a/apps/device-gateway/wrangler.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-name = "device-gateway"
-main = "src/index.ts"
-compatibility_date = "2025-01-01"
-
-[durable_objects]
-bindings = [
- { name = "DEVICE_GATEWAY", class_name = "DeviceGatewayDO" }
-]
-
-[[migrations]]
-tag = "v1"
-new_classes = ["DeviceGatewayDO"]
-
-# Secrets (injected via `wrangler secret put`):
-# - JWKS_PUBLIC_KEY: RS256 public key JSON (extracted from JWKS_KEY)
-# - SERVICE_TOKEN: Vercel β†’ CF service-to-service auth secret
diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
index 7d253a6e784..39fce13d916 100644
--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/types.ts
@@ -1,4 +1,13 @@
+/** A single live gateway connection (channel) of a device. */
+export interface DeviceChannel {
+ channel?: string;
+ connectedAt: string;
+ connectionId: string;
+}
+
export interface DeviceAttachment {
+ /** Live connections backing this device; absent for offline devices. */
+ channels?: DeviceChannel[];
deviceId: string;
hostname: string;
lastSeen: string;
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index a1a13b45982..fdfaf21e4e5 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -133,6 +133,32 @@ describe('GatewayClient', () => {
expect(ws.url).toContain('userId=test-user');
});
+ it('should include connectionId and channel in the URL when provided', () => {
+ const c = new GatewayClient({
+ autoReconnect: false,
+ channel: 'cli',
+ connectionId: 'conn-123',
+ deviceId: 'dev-1',
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+ c.connect();
+ const ws = (c as any).ws;
+ expect(ws.url).toContain('connectionId=conn-123');
+ expect(ws.url).toContain('channel=cli');
+ expect(c.currentConnectionId).toBe('conn-123');
+ c.disconnect();
+ });
+
+ it('should default connectionId to a generated UUID when omitted', () => {
+ const c = new GatewayClient({ autoReconnect: false, token: 'tok' });
+ c.connect();
+ const ws = (c as any).ws;
+ expect(ws.url).toContain(`connectionId=${c.currentConnectionId}`);
+ expect(ws.url).not.toContain('channel=');
+ c.disconnect();
+ });
+
it('should build ws URL for http gateway', () => {
const c = new GatewayClient({
autoReconnect: false,
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 3a36aaec272..83157433f0c 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -46,6 +46,20 @@ const noopLogger: GatewayClientLogger = {
export interface GatewayClientOptions {
/** Auto-reconnect on disconnection (default: true) */
autoReconnect?: boolean;
+ /**
+ * Freeform routing label for this connection, e.g. `desktop` / `desktop-dev`
+ * / `cli` / `cli-dev`. Used by the gateway for dispatch priority + UI; it does
+ * NOT participate in stale-connection dedupe (that's `connectionId`).
+ */
+ channel?: string;
+ /**
+ * Stable per-install random UUID identifying this connection. The gateway uses
+ * it as the stale-connection dedupe key, so multiple channels on the same
+ * physical device (same `deviceId`) coexist. Defaults to a fresh UUID, which
+ * means a fresh dedupe identity per process β€” callers that want a reconnect to
+ * replace its own previous socket should pass a persisted value.
+ */
+ connectionId?: string;
deviceId?: string;
gatewayUrl?: string;
logger?: GatewayClientLogger;
@@ -64,6 +78,8 @@ export class GatewayClient extends EventEmitter {
private status: ConnectionStatus = 'disconnected';
private intentionalDisconnect = false;
private deviceId: string;
+ private connectionId: string;
+ private channel?: string;
private gatewayUrl: string;
private token: string;
private tokenType?: 'apiKey' | 'jwt' | 'serviceToken';
@@ -78,6 +94,8 @@ export class GatewayClient extends EventEmitter {
this.tokenType = options.tokenType;
this.gatewayUrl = options.gatewayUrl || DEFAULT_GATEWAY_URL;
this.deviceId = options.deviceId || randomUUID();
+ this.connectionId = options.connectionId || randomUUID();
+ this.channel = options.channel;
this.serverUrl = options.serverUrl;
this.userId = options.userId;
this.logger = options.logger || noopLogger;
@@ -94,6 +112,10 @@ export class GatewayClient extends EventEmitter {
return this.deviceId;
}
+ get currentConnectionId(): string {
+ return this.connectionId;
+ }
+
override on<K extends keyof GatewayClientEvents>(
event: K,
listener: GatewayClientEvents[K],
@@ -204,11 +226,16 @@ export class GatewayClient extends EventEmitter {
const wsProtocol = this.gatewayUrl.startsWith('https') ? 'wss' : 'ws';
const host = this.gatewayUrl.replace(/^https?:\/\//, '');
const params = new URLSearchParams({
+ connectionId: this.connectionId,
deviceId: this.deviceId,
hostname: os.hostname(),
platform: process.platform,
});
+ if (this.channel) {
+ params.set('channel', this.channel);
+ }
+
// Service token mode: pass userId in query
if (this.userId) {
params.set('userId', this.userId);
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index f2b37203921..e52b9e2f3a0 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,4 +1,4 @@
-import type { DeviceAttachment, DeviceSystemInfo } from './types';
+import type { DeviceSystemInfo, GatewayDevice } from './types';
const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
@@ -45,7 +45,7 @@ export class GatewayHttpClient {
};
}
- async queryDeviceList(userId: string): Promise<DeviceAttachment[]> {
+ async queryDeviceList(userId: string): Promise<GatewayDevice[]> {
const res = await this.post('/api/device/devices', { userId });
if (!res.ok) return [];
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index ea56b69a988..2dc6eb4a75f 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -1,6 +1,23 @@
// ─── Device Info ───
-export interface DeviceAttachment {
+/** A single live gateway WebSocket connection belonging to a device. */
+export interface DeviceConnection {
+ /** Freeform routing label, e.g. `desktop` / `desktop-dev` / `cli` / `cli-dev`. */
+ channel?: string;
+ connectedAt: number;
+ /** Per-install random UUID β€” the gateway's stale-connection dedupe key. */
+ connectionId: string;
+}
+
+/**
+ * A device as surfaced by the gateway `/api/device/devices` endpoint. Keyed by
+ * the stable `deviceId` (one entry per physical machine); the live WS sessions
+ * are nested under `channels` so a single device can hold several at once
+ * (e.g. desktop app + `lh connect` both connected).
+ */
+export interface GatewayDevice {
+ channels: DeviceConnection[];
+ /** Most recent channel's connect time. */
connectedAt: number;
deviceId: string;
hostname: string;
@@ -20,7 +37,7 @@ export interface DeviceSystemInfo {
workingDirectory: string;
}
-// ─── WebSocket Protocol Messages (mirrors apps/device-gateway/src/types.ts) ───
+// ─── WebSocket Protocol Messages (mirrors the device-gateway service's types) ───
// Client β†’ Server
export interface AuthMessage {
@@ -73,7 +90,11 @@ export interface AuthExpiredMessage {
}
export interface ToolCallRequestMessage {
+ /** Operation that triggered the call, propagated by the gateway for tracing. */
+ operationId?: string;
requestId: string;
+ /** Per-call timeout (ms) the gateway forwards; clients pass it through. */
+ timeout?: number;
toolCall: {
apiName: string;
arguments: string;
diff --git a/src/routes/(main)/settings/devices/features/DeviceItem.tsx b/src/routes/(main)/settings/devices/features/DeviceItem.tsx
index 2c1e56ebe55..2802965bdb1 100644
--- a/src/routes/(main)/settings/devices/features/DeviceItem.tsx
+++ b/src/routes/(main)/settings/devices/features/DeviceItem.tsx
@@ -19,6 +19,7 @@ import { lambdaQuery } from '@/libs/trpc/client';
import { getDeviceIcon } from './getDeviceIcon';
export interface DeviceChannel {
+ channel: string | null;
connectedAt: string;
hostname: string | null;
platform: string | null;
@@ -97,7 +98,9 @@ const DeviceItem = memo<{ device: DeviceListItem }>(({ device }) => {
// `listDevices` shape; fall back to a single synthetic channel when online.
const channels =
device.channels ??
- (device.online ? [{ connectedAt: device.lastSeen, hostname: null, platform: null }] : []);
+ (device.online
+ ? [{ channel: null, connectedAt: device.lastSeen, hostname: null, platform: null }]
+ : []);
const openEdit = () => {
setName(device.friendlyName ?? '');
@@ -161,6 +164,7 @@ const DeviceItem = memo<{ device: DeviceListItem }>(({ device }) => {
>
<span className={styles.dotOnline} />
<Text style={{ fontSize: 12 }} type={'secondary'}>
+ {channel.channel ? `${channel.channel} Β· ` : ''}
{t('devices.channel.connected', { time: dayjs(channel.connectedAt).fromNow() })}
</Text>
</Flexbox>
diff --git a/src/server/routers/lambda/device.ts b/src/server/routers/lambda/device.ts
index b838f310d40..de51c780d56 100644
--- a/src/server/routers/lambda/device.ts
+++ b/src/server/routers/lambda/device.ts
@@ -20,6 +20,7 @@ const PROFILE_TIMEOUT_MS = 5_000;
/** A single live gateway WebSocket connection belonging to a device. */
interface DeviceChannel {
+ channel: string | null;
connectedAt: string;
hostname: string | null;
platform: string | null;
@@ -132,16 +133,28 @@ export const deviceRouter = router({
deviceProxy.queryDeviceList(ctx.userId),
]);
- // Group live gateway connections (channels) by the device they belong to.
+ // The gateway already groups by device, exposing live sessions as nested
+ // `channels`. Flatten them into the UI-facing channel shape; fall back to a
+ // single synthetic channel for a legacy gateway that omits the field.
const channelsByDevice = new Map<string, DeviceChannel[]>();
for (const conn of onlineList) {
- const list = channelsByDevice.get(conn.deviceId) ?? [];
- list.push({
- connectedAt: conn.lastSeen,
- hostname: conn.hostname ?? null,
- platform: conn.platform ?? null,
- });
- channelsByDevice.set(conn.deviceId, list);
+ const channels: DeviceChannel[] =
+ conn.channels && conn.channels.length > 0
+ ? conn.channels.map((c) => ({
+ channel: c.channel ?? null,
+ connectedAt: c.connectedAt,
+ hostname: conn.hostname ?? null,
+ platform: conn.platform ?? null,
+ }))
+ : [
+ {
+ channel: null,
+ connectedAt: conn.lastSeen,
+ hostname: conn.hostname ?? null,
+ platform: conn.platform ?? null,
+ },
+ ];
+ channelsByDevice.set(conn.deviceId, channels);
}
const seen = new Set<string>();
diff --git a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
index 8a33493c4df..418d3503d8e 100644
--- a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
+++ b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
@@ -85,18 +85,24 @@ describe('DeviceProxy', () => {
expect(result).toEqual([]);
});
- it('should transform connectedAt to lastSeen and set online: true', async () => {
+ it('should map device-centric channels to lastSeen + online and flatten channels', async () => {
mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
- const connectedAt = '2025-01-15T10:30:00Z';
+ const connectedAt = Date.parse('2025-01-15T10:30:00Z');
+ const iso = new Date(connectedAt).toISOString();
mockClient.queryDeviceList.mockResolvedValue([
{
+ channels: [
+ { channel: 'desktop', connectedAt, connectionId: 'conn-a' },
+ { channel: 'cli', connectedAt, connectionId: 'conn-b' },
+ ],
connectedAt,
deviceId: 'dev-1',
hostname: 'my-laptop',
platform: 'darwin',
},
{
+ channels: [{ channel: 'desktop', connectedAt, connectionId: 'conn-c' }],
connectedAt,
deviceId: 'dev-2',
hostname: 'my-desktop',
@@ -109,16 +115,21 @@ describe('DeviceProxy', () => {
expect(result).toEqual([
{
+ channels: [
+ { channel: 'desktop', connectedAt: iso, connectionId: 'conn-a' },
+ { channel: 'cli', connectedAt: iso, connectionId: 'conn-b' },
+ ],
deviceId: 'dev-1',
hostname: 'my-laptop',
- lastSeen: new Date(connectedAt).toISOString(),
+ lastSeen: iso,
online: true,
platform: 'darwin',
},
{
+ channels: [{ channel: 'desktop', connectedAt: iso, connectionId: 'conn-c' }],
deviceId: 'dev-2',
hostname: 'my-desktop',
- lastSeen: new Date(connectedAt).toISOString(),
+ lastSeen: iso,
online: true,
platform: 'win32',
},
@@ -126,6 +137,29 @@ describe('DeviceProxy', () => {
expect(mockClient.queryDeviceList).toHaveBeenCalledWith('user-1');
});
+ it('tolerates a legacy gateway response without channels', async () => {
+ 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.mockResolvedValue([
+ { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },
+ ]);
+
+ const proxy = new DeviceProxy();
+ const result = await proxy.queryDeviceList('user-1');
+
+ expect(result).toEqual([
+ {
+ channels: [],
+ deviceId: 'dev-1',
+ hostname: 'my-laptop',
+ lastSeen: new Date(connectedAt).toISOString(),
+ online: true,
+ platform: 'darwin',
+ },
+ ]);
+ });
+
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/src/server/services/toolExecution/deviceProxy.ts b/src/server/services/toolExecution/deviceProxy.ts
index 8181bb88e2a..4893c8eb9eb 100644
--- a/src/server/services/toolExecution/deviceProxy.ts
+++ b/src/server/services/toolExecution/deviceProxy.ts
@@ -39,9 +39,17 @@ export class DeviceProxy {
try {
const devices = await client.queryDeviceList(userId);
- // Transform gateway format to runtime-expected format
- // All devices from gateway have active WebSocket connections, so they're online
+ // 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.
+ channels: (d.channels ?? []).map((c) => ({
+ channel: c.channel,
+ connectedAt: new Date(c.connectedAt).toISOString(),
+ connectionId: c.connectionId,
+ })),
deviceId: d.deviceId,
hostname: d.hostname,
lastSeen: new Date(d.connectedAt).toISOString(),
diff --git a/tsconfig.json b/tsconfig.json
index c1fe8442cc3..f60aa290dc4 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -33,7 +33,6 @@
"exclude": [
"node_modules",
"apps/desktop/**",
- "apps/device-gateway/**",
"apps/mobile/**",
"tmp",
"temp",