🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(cli): auto-register device on login, matching desktop (#15377)
Arvin Xue14f2e96f6fd
diff --git a/apps/cli/src/auth/resolveToken.ts b/apps/cli/src/auth/resolveToken.tsindex d84fe90ceb7..5b41a68e231 100644--- a/apps/cli/src/auth/resolveToken.ts+++ b/apps/cli/src/auth/resolveToken.ts@@ -20,7 +20,7 @@ interface ResolvedAuth {/*** Parse the `sub` claim from a JWT without verifying the signature.*/-function parseJwtSub(token: string): string | undefined {+export function parseJwtSub(token: string): string | undefined {try {const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());return payload.sub;diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 063d8e905cc..b833e1e49ec 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -8,11 +8,8 @@ import type {ToolCallRequestMessage,} from '@lobechat/device-gateway-client';import { GatewayClient } from '@lobechat/device-gateway-client';-import type { IdentitySource } from '@lobechat/device-identity';-import { deriveDeviceId } from '@lobechat/device-identity';import type { Command } from 'commander';-import { createLambdaClient } from '../api/client';import { getValidToken } from '../auth/refresh';import { resolveToken } from '../auth/resolveToken';import { CLI_API_KEY_ENV } from '../constants/auth';@@ -28,6 +25,7 @@ import {stopDaemon,writeStatus,} from '../daemon/manager';+import { registerDevice, resolveDeviceIdentity } from '../device/register';import { loadOrCreateConnectionId, loadSettings, normalizeUrl, saveSettings } from '../settings';import { executeToolCall } from '../tools';import { cleanupAllProcesses } from '../tools/shell';@@ -198,12 +196,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// Resolve a stable device identity. An explicit `--device-id` wins (lets a// user pin a VM to a fixed identity); otherwise derive from the machine id so// the same machine + user maps to one device across reconnects.- const identity: { deviceId: string; identitySource: IdentitySource } | undefined =- options.deviceId- ? { deviceId: options.deviceId, identitySource: 'fallback' }- : auth.userId- ? deriveDeviceId(auth.userId)- : undefined;+ const identity = resolveDeviceIdentity(auth.userId, options.deviceId);// Freeform channel label (`cli` by default); `LOBEHUB_CLI_CHANNEL` lets a// dev build tag itself `cli-dev` so the gateway can prioritise / display it.@@ -406,19 +399,15 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {});// Register this device in the server registry before opening the WS, so the- // row exists by the time the gateway reports it online. Best-effort: a- // failure must not block the connection.+ // row exists by the time the gateway reports it online. `lh login` already+ // registers, but re-running here is cheap (idempotent upsert) and covers+ // `--token` sessions that never went through login. Best-effort: a failure+ // must not block the connection.if (identity) {try {- // Reuse the already-resolved auth (respects `--token` mode) instead of- // getTrpcClient(), which re-discovers creds and exits when none are found.- const trpc = createLambdaClient(auth);- await trpc.device.register.mutate({- deviceId: identity.deviceId,- hostname: os.hostname(),- identitySource: identity.identitySource,- platform: process.platform,- });+ // Reuse the already-resolved auth (respects `--token` mode) so we don't+ // re-discover creds and exit when none are found.+ await registerDevice(auth, identity);} catch (err) {error(`Device registration failed (non-fatal): ${(err as Error).message}`);}diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.tsindex f4432f8f8c0..1b67e9d8579 100644--- a/apps/cli/src/commands/login.ts+++ b/apps/cli/src/commands/login.ts@@ -6,8 +6,10 @@ import type { Command } from 'commander';import { getUserIdFromApiKey } from '../auth/apiKey';import { saveCredentials } from '../auth/credentials';+import { parseJwtSub } from '../auth/resolveToken';import { CLI_API_KEY_ENV } from '../constants/auth';import { OFFICIAL_SERVER_URL } from '../constants/urls';+import { registerDevice, resolveDeviceIdentity } from '../device/register';import { loadSettings, normalizeUrl, saveSettings } from '../settings';import { log } from '../utils/logger';@@ -213,6 +215,30 @@ export function registerLoginCommand(program: Command) {},);+ // Register this device in the server registry right after auth, so+ // the device row exists without waiting for a later `lh connect`+ // (which only adds the channel-online step). Mirrors the desktop+ // app, which registers on login. Best-effort: a failure here must+ // not fail the login.+ //+ // Skip the `fallback` source: `lh login` has no `--device-id` and+ // persists no fallback id, so a machine without a readable+ // machine-id would derive a *fresh random* id on every login —+ // registering it just spawns orphan device rows that never match+ // the id a later `lh connect` resolves. Defer registration to+ // `connect` in that case, where the same id is reused for the WS.+ const identity = resolveDeviceIdentity(parseJwtSub(body.access_token));+ if (identity && identity.identitySource !== 'fallback') {+ try {+ await registerDevice(+ { serverUrl, token: body.access_token, tokenType: 'jwt' },+ identity,+ );+ } catch (err) {+ log.warn(`Device registration failed (non-fatal): ${(err as Error).message}`);+ }+ }+log.info('Login successful! Credentials saved.');return;}diff --git a/apps/cli/src/device/register.ts b/apps/cli/src/device/register.tsnew file mode 100644index 00000000000..63f36402a47--- /dev/null+++ b/apps/cli/src/device/register.ts@@ -0,0 +1,40 @@+import os from 'node:os';++import type { DeviceIdentity } from '@lobechat/device-identity';+import { deriveDeviceId } from '@lobechat/device-identity';++import { createLambdaClient } from '../api/client';++/**+ * Resolve a stable device identity. An explicit `--device-id` wins (lets a user+ * pin a VM to a fixed identity); otherwise derive from the machine id so the+ * same machine + user maps to one device across reconnects. Returns undefined+ * when neither an explicit id nor a userId is available.+ */+export function resolveDeviceIdentity(+ userId: string | undefined,+ explicitDeviceId?: string,+): DeviceIdentity | undefined {+ if (explicitDeviceId) return { deviceId: explicitDeviceId, identitySource: 'fallback' };+ if (userId) return deriveDeviceId(userId);+ return undefined;+}++/**+ * Register this device in the server registry. Shared by `lh login` (so the+ * device row exists right after auth) and `lh connect` (so the row exists+ * before the WS opens). Best-effort by contract: callers should wrap this in a+ * try/catch and treat any failure as non-fatal.+ */+export async function registerDevice(+ auth: { serverUrl: string; token: string; tokenType: 'apiKey' | 'jwt' | 'serviceToken' },+ identity: DeviceIdentity,+): Promise<void> {+ const trpc = createLambdaClient(auth);+ await trpc.device.register.mutate({+ deviceId: identity.deviceId,+ hostname: os.hostname(),+ identitySource: identity.identitySource,+ platform: process.platform,+ });+}