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(cli): wait for daemon startup readiness (#19000)

Neko675e98554e60
diff --git a/apps/cli/package.json b/apps/cli/package.json
index f9fe7bf6544..fcd26e31b49 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -56,6 +56,7 @@
"picocolors": "^1.1.1",
"semver": "^7.8.5",
"superjson": "^2.2.6",
+ "tinyexec": "^1.3.0",
"tree-kill": "^1.2.2",
"tsdown": "^0.21.10",
"typescript": "^6.0.3"
diff --git a/apps/cli/src/commands/connect.integration.test.ts b/apps/cli/src/commands/connect.integration.test.ts
new file mode 100644
index 00000000000..53d99f94935
--- /dev/null
+++ b/apps/cli/src/commands/connect.integration.test.ts
@@ -0,0 +1,166 @@
+import { execFile } from 'node:child_process';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+interface CliResult {
+ exitCode: number;
+ stderr: string;
+ stdout: string;
+}
+
+const tempHomes: string[] = [];
+const servers: Server[] = [];
+
+async function runCli(
+ args: string[],
+ home: string,
+ extraEnv: Record<string, string> = {},
+): Promise<CliResult> {
+ return new Promise((resolve, reject) => {
+ execFile(
+ 'bun',
+ [path.resolve(import.meta.dirname, '../index.ts'), ...args],
+ {
+ cwd: path.resolve(import.meta.dirname, '../..'),
+ env: {
+ ...process.env,
+ HOME: home,
+ LOBEHUB_CLI_API_KEY: '',
+ LOBEHUB_CLI_HOME: '.lobehub',
+ LOBEHUB_JWT: '',
+ ...extraEnv,
+ },
+ timeout: 10_000,
+ },
+ (error, stdout, stderr) => {
+ if (error && typeof error.code !== 'number') {
+ reject(error);
+ return;
+ }
+
+ resolve({
+ exitCode: typeof error?.code === 'number' ? error.code : 0,
+ stderr,
+ stdout,
+ });
+ },
+ );
+ });
+}
+
+afterEach(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ await Promise.all(
+ servers.splice(0).map(
+ (server) =>
+ new Promise<void>((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ }),
+ ),
+ );
+ await Promise.all(tempHomes.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+});
+
+describe('connect daemon startup', () => {
+ it('reports a startup failure instead of claiming the daemon started', async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));
+ tempHomes.push(home);
+ const configDir = path.join(home, '.lobehub');
+ await mkdir(configDir, { recursive: true });
+ await writeFile(path.join(configDir, 'daemon.log'), '─'.repeat(512));
+
+ const result = await runCli(['connect', '--daemon'], home);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.stdout).not.toContain('Daemon started');
+ expect(result.stderr).toContain('No authentication found');
+ });
+
+ it('surfaces the underlying network error when startup retries are exhausted', async () => {
+ const portProbe = createServer();
+ await new Promise<void>((resolve) => portProbe.listen(0, '127.0.0.1', resolve));
+ const { port } = portProbe.address() as AddressInfo;
+ await new Promise<void>((resolve, reject) =>
+ portProbe.close((error) => (error ? reject(error) : resolve())),
+ );
+
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
+ const payload = Buffer.from(JSON.stringify({ sub: 'test-user' })).toString('base64url');
+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));
+ tempHomes.push(home);
+
+ const result = await runCli(['connect', '--workspace', 'workspace-id', '--daemon'], home, {
+ LOBEHUB_JWT: `${header}.${payload}.signature`,
+ LOBEHUB_SERVER: `http://127.0.0.1:${port}`,
+ });
+
+ expect(result.exitCode).toBe(1);
+ expect(result.stdout).not.toContain('Daemon started');
+ expect(result.stderr).toContain('ConnectionRefused');
+ }, 15_000);
+
+ it('does not report startup readiness before workspace registration succeeds', async () => {
+ const requests: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(request.url ?? '');
+ response.setHeader('Content-Type', 'application/json');
+
+ if (request.url?.includes('device.mintWorkspaceConnectToken')) {
+ response.end(
+ JSON.stringify({
+ result: {
+ data: {
+ json: { token: 'workspace-token', workspaceId: 'workspace-id' },
+ },
+ },
+ }),
+ );
+ return;
+ }
+
+ response.statusCode = 409;
+ response.end(
+ JSON.stringify({
+ error: {
+ json: {
+ code: -32_009,
+ data: {
+ code: 'CONFLICT',
+ httpStatus: 409,
+ path: 'device.registerWorkspaceDevice',
+ },
+ message: 'workspace registration rejected',
+ },
+ },
+ }),
+ );
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
+ const payload = Buffer.from(JSON.stringify({ sub: 'test-user' })).toString('base64url');
+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));
+ tempHomes.push(home);
+
+ const result = await runCli(
+ ['connect', '--workspace', 'workspace-id', '--public', '--daemon'],
+ home,
+ {
+ LOBEHUB_JWT: `${header}.${payload}.signature`,
+ LOBEHUB_SERVER: `http://127.0.0.1:${port}`,
+ },
+ );
+
+ expect(requests.some((url) => url.includes('device.registerWorkspaceDevice'))).toBe(true);
+ expect(result.exitCode).toBe(1);
+ expect(result.stdout).not.toContain('Daemon started');
+ expect(result.stderr).toContain('workspace registration rejected');
+ });
+});
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 1ec34e32b50..60c896a8956 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -56,6 +56,7 @@ vi.mock('../daemon/manager', () => ({
readStatus: vi.fn().mockImplementation(() => mockStatus),
removePid: vi.fn(),
removeStatus: vi.fn(),
+ reportDaemonStartupReady: vi.fn().mockResolvedValue(undefined),
spawnDaemon: vi.fn().mockImplementation(() => {
mockSpawnedPid = 99999;
return mockSpawnedPid;
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 8ef9698da00..3b633c6769c 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -38,6 +38,7 @@ import {
readStatus,
removePid,
removeStatus,
+ reportDaemonStartupReady,
spawnDaemon,
stopDaemon,
writeStatus,
@@ -177,12 +178,12 @@ export function registerConnectCommand(program: Command) {
.option('--gateway <url>', 'Device gateway URL')
.option('--device-id <id>', 'Device ID')
.option('-v, --verbose', 'Enable verbose logging')
- .action((options: ConnectOptions) => {
+ .action(async (options: ConnectOptions) => {
const wasStopped = stopDaemon();
if (wasStopped) {
log.info('Stopped existing daemon.');
}
- handleDaemonStart({ ...options, daemon: true });
+ await handleDaemonStart({ ...options, daemon: true });
});
const serviceCmd = connectCmd
@@ -283,7 +284,7 @@ function handleStop() {
}
}
-function handleDaemonStart(options: ConnectOptions) {
+async function handleDaemonStart(options: ConnectOptions) {
const existingPid = getRunningDaemonPid();
if (existingPid !== null) {
log.error(`Daemon is already running (PID ${existingPid}).`);
@@ -293,7 +294,7 @@ function handleDaemonStart(options: ConnectOptions) {
// Build args to re-run with --daemon-child
const args = buildDaemonArgs(options);
- const pid = spawnDaemon(args);
+ const pid = await spawnDaemon(args);
log.info(`Daemon started (PID ${pid}).`);
log.info(` Logs: ${getLogPath()}`);
@@ -807,6 +808,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
}
}
+ await reportDaemonStartupReady();
+
// Connect
await client.connect();
diff --git a/apps/cli/src/daemon/manager.test.ts b/apps/cli/src/daemon/manager.test.ts
index 0d3d3fb349f..d30c0750b6a 100644
--- a/apps/cli/src/daemon/manager.test.ts
+++ b/apps/cli/src/daemon/manager.test.ts
@@ -1,9 +1,9 @@
-import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
+import { xSync } from 'tinyexec';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -36,11 +36,11 @@ vi.mock('node:os', async (importOriginal) => {
};
});
-// Mock only `execFileSync` (used by isDaemonProcess to read a process command
-// line); keep the real `spawn` so nothing else changes.
-vi.mock('node:child_process', async (importOriginal) => {
+// Mock only `xSync` (used by isDaemonProcess to read a process command line);
+// keep the real async executor so daemon integration tests still spawn children.
+vi.mock('tinyexec', async (importOriginal) => {
const actual = await importOriginal<Record<string, any>>();
- return { ...actual, execFileSync: vi.fn() };
+ return { ...actual, xSync: vi.fn() };
});
// A command line that matches the daemon signature (`connect … --daemon-child`).
@@ -51,7 +51,7 @@ describe('daemon manager', () => {
await mkdir(mockDir, { recursive: true });
// Default: any inspected PID looks like our daemon. Tests that need a
// reused / unrelated PID override this per-case.
- vi.mocked(execFileSync).mockReturnValue(DAEMON_COMMAND as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: DAEMON_COMMAND } as any);
});
afterEach(() => {
@@ -96,9 +96,9 @@ describe('daemon manager', () => {
describe('isDaemonProcess', () => {
it('should return true when the command line matches the daemon signature', () => {
- vi.mocked(execFileSync).mockReturnValue(DAEMON_COMMAND as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: DAEMON_COMMAND } as any);
expect(isDaemonProcess(12345)).toBe(true);
- expect(execFileSync).toHaveBeenCalledWith(
+ expect(xSync).toHaveBeenCalledWith(
'ps',
['-ww', '-p', '12345', '-o', 'command='],
expect.any(Object),
@@ -106,18 +106,18 @@ describe('daemon manager', () => {
});
it('should return false for an unrelated process command line', () => {
- vi.mocked(execFileSync).mockReturnValue('/usr/bin/vim notes.txt' as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: '/usr/bin/vim notes.txt' } as any);
expect(isDaemonProcess(12345)).toBe(false);
});
it('should return false when the signature is only partially present', () => {
// `connect` without the internal `--daemon-child` flag is not our daemon.
- vi.mocked(execFileSync).mockReturnValue('/usr/bin/node /path/cli connect' as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: '/usr/bin/node /path/cli connect' } as any);
expect(isDaemonProcess(12345)).toBe(false);
});
it('should return false when ps is unavailable / throws', () => {
- vi.mocked(execFileSync).mockImplementation(() => {
+ vi.mocked(xSync).mockImplementation(() => {
throw new Error('ps: command not found');
});
expect(isDaemonProcess(12345)).toBe(false);
@@ -165,7 +165,7 @@ describe('daemon manager', () => {
pid: process.pid,
startedAt: new Date().toISOString(),
});
- vi.mocked(execFileSync).mockReturnValue('/usr/bin/some-other-process' as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: '/usr/bin/some-other-process' } as any);
expect(getRunningDaemonPid()).toBeNull();
expect(readPid()).toBeNull();
@@ -297,7 +297,7 @@ describe('daemon manager', () => {
it('should NOT SIGTERM a live PID that is not our daemon', () => {
// Stale daemon.pid whose PID was reused by an unrelated, living process.
writePid(process.pid);
- vi.mocked(execFileSync).mockReturnValue('/usr/bin/some-other-process' as any);
+ vi.mocked(xSync).mockReturnValue({ stdout: '/usr/bin/some-other-process' } as any);
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.ts
index d49b4df7785..2c999c20f12 100644
--- a/apps/cli/src/daemon/manager.ts
+++ b/apps/cli/src/daemon/manager.ts
@@ -1,11 +1,15 @@
-import { execFileSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { x, xSync } from 'tinyexec';
+
import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
const MAX_LOG_SIZE = 5 * 1024 * 1024; // 5MB
+const STARTUP_TIMEOUT_MS = 30_000;
+
+type DaemonStartupMessage = { message: string; type: 'startup-error' } | { type: 'startup-ready' };
function getLobehubDir() {
return path.join(os.homedir(), CLI_CONFIG_DIR_NAME);
@@ -90,10 +94,11 @@ export function isDaemonProcess(pid: number): boolean {
try {
// `-ww` disables column truncation so the trailing `--daemon-child` flag is
// never cut off; stderr is silenced so a dead PID just yields an empty match.
- const command = execFileSync('ps', ['-ww', '-p', String(pid), '-o', 'command='], {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'ignore'],
- }).trim();
+ const { stdout } = xSync('ps', ['-ww', '-p', String(pid), '-o', 'command='], {
+ nodeOptions: { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
+ nodePath: false,
+ });
+ const command = stdout.trim();
return command.includes('--daemon-child') && command.includes('connect');
} catch {
return false;
@@ -181,28 +186,121 @@ export function appendLog(line: string): void {
// --- Daemon spawn ---
/**
- * Spawn the current script as a detached daemon process.
- * The parent writes the PID file and returns immediately.
+ * Spawn the current script as a detached daemon process and wait until the
+ * child completes its startup preflight.
*/
-export function spawnDaemon(args: string[]): number {
+export function spawnDaemon(args: string[]): Promise<number> {
ensureDir();
const logFd = fs.openSync(getLogFilePath(), 'a');
+ const logStartOffset = fs.fstatSync(logFd).size;
// Re-run the same entry with --daemon-child (internal flag)
- const child = spawn(process.execPath, [...process.execArgv, ...args, '--daemon-child'], {
- detached: true,
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', LOBEHUB_DAEMON: '1' },
- stdio: ['ignore', logFd, logFd],
+ const daemon = x(process.execPath, [...process.execArgv, ...args, '--daemon-child'], {
+ nodeOptions: {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', LOBEHUB_DAEMON: '1' },
+ stdio: ['ignore', logFd, logFd, 'ipc'],
+ },
+ nodePath: false,
+ persist: true,
});
+ const child = daemon.process;
+
+ if (!child || !daemon.pid) {
+ fs.closeSync(logFd);
+ throw new Error('Daemon process could not start.');
+ }
- child.unref();
- const pid = child.pid!;
+ const pid = daemon.pid;
writePid(pid);
fs.closeSync(logFd);
- return pid;
+ return new Promise((resolve, reject) => {
+ let settled = false;
+
+ const finish = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ child.off('error', onError);
+ child.off('exit', onExit);
+ child.off('message', onMessage);
+ if (child.connected) child.disconnect();
+ child.unref();
+
+ if (error) {
+ removePid();
+ removeStatus();
+ reject(error);
+ return;
+ }
+
+ resolve(pid);
+ };
+
+ const timeout = setTimeout(() => {
+ daemon.kill('SIGTERM');
+ finish(new Error('Daemon startup timed out. See the daemon log for details.'));
+ }, STARTUP_TIMEOUT_MS);
+
+ const onError = (error: Error) => finish(error);
+ const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
+ const startupError = readStartupError(logStartOffset);
+ finish(
+ new Error(
+ startupError ||
+ `Daemon exited before startup completed (${signal ? `signal ${signal}` : `code ${code ?? 1}`}).`,
+ ),
+ );
+ };
+ const onMessage = (message: DaemonStartupMessage) => {
+ if (message?.type === 'startup-ready') {
+ finish();
+ } else if (message?.type === 'startup-error') {
+ finish(new Error(message.message));
+ }
+ };
+
+ child.once('error', onError);
+ child.once('exit', onExit);
+ child.on('message', onMessage);
+ });
+}
+
+function readStartupError(startOffset: number): string | undefined {
+ try {
+ const content = fs.readFileSync(getLogFilePath()).subarray(startOffset).toString('utf8').trim();
+ const lastError = content
+ .split('\n')
+ .toReversed()
+ .find((line) => line.includes('[ERROR]'))
+ ?.trim();
+ return lastError?.replace(/^(?:\[[^\]]+\]|\d{2}:\d{2}:\d{2})\s+\[ERROR\]\s+/, '');
+ } catch {
+ return undefined;
+ }
+}
+
+function sendStartupMessage(message: DaemonStartupMessage): Promise<void> {
+ if (process.env.LOBEHUB_DAEMON !== '1' || !process.send || !process.connected) {
+ return Promise.resolve();
+ }
+
+ return new Promise((resolve) => {
+ process.send!(message, () => {
+ if (process.connected) process.disconnect();
+ resolve();
+ });
+ });
+}
+
+export function reportDaemonStartupError(message: string): Promise<void> {
+ return sendStartupMessage({ message, type: 'startup-error' });
+}
+
+export function reportDaemonStartupReady(): Promise<void> {
+ return sendStartupMessage({ type: 'startup-ready' });
}
/**
diff --git a/apps/cli/src/device/register.test.ts b/apps/cli/src/device/register.test.ts
new file mode 100644
index 00000000000..c65516dffa6
--- /dev/null
+++ b/apps/cli/src/device/register.test.ts
@@ -0,0 +1,58 @@
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { mintWorkspaceConnectToken } from './register';
+
+const servers: Server[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ servers.splice(0).map(
+ (server) =>
+ new Promise<void>((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ }),
+ ),
+ );
+});
+
+describe('mintWorkspaceConnectToken', () => {
+ it('recovers from a transient network failure', async () => {
+ let attempts = 0;
+ const server = createServer((request, response) => {
+ attempts += 1;
+ if (attempts === 1) {
+ request.socket.destroy();
+ return;
+ }
+
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(
+ JSON.stringify({
+ result: {
+ data: {
+ json: { token: 'workspace-token', workspaceId: 'workspace-id' },
+ },
+ },
+ }),
+ );
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+
+ const result = await mintWorkspaceConnectToken(
+ {
+ serverUrl: `http://127.0.0.1:${port}`,
+ token: 'user-token',
+ tokenType: 'jwt',
+ },
+ 'workspace-id',
+ );
+
+ expect(result).toEqual({ token: 'workspace-token', workspaceId: 'workspace-id' });
+ expect(attempts).toBe(2);
+ });
+});
diff --git a/apps/cli/src/device/register.ts b/apps/cli/src/device/register.ts
index e925731f87a..1ae50c64c4d 100644
--- a/apps/cli/src/device/register.ts
+++ b/apps/cli/src/device/register.ts
@@ -4,6 +4,21 @@ import type { DeviceIdentity } from '@lobechat/device-identity';
import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';
import { createLambdaClient } from '../api/client';
+import { isTransientNetworkError } from '../utils/error';
+
+const WORKSPACE_TOKEN_RETRY_DELAYS_MS = [250, 1000, 2500];
+
+async function withWorkspaceTokenRetry<T>(operation: () => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ return await operation();
+ } catch (error) {
+ const delay = WORKSPACE_TOKEN_RETRY_DELAYS_MS[attempt];
+ if (delay === undefined || !isTransientNetworkError(error)) throw error;
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+}
/**
* Resolve a stable device identity. An explicit `--device-id` wins (lets a user
@@ -73,7 +88,7 @@ export async function mintWorkspaceConnectToken(
workspaceId: string,
): Promise<{ token: string; workspaceId: string }> {
const trpc = createLambdaClient(auth, workspaceId);
- return trpc.device.mintWorkspaceConnectToken.mutate();
+ return withWorkspaceTokenRetry(() => trpc.device.mintWorkspaceConnectToken.mutate());
}
/**
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index ceb4474a31a..a1453d4ea31 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -1,10 +1,13 @@
+import { reportDaemonStartupError } from './daemon/manager';
import { createProgram } from './program';
+import { formatError } from './utils/error';
import { log } from './utils/logger';
void createProgram()
.parseAsync(process.argv, { from: 'node' })
- .catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
+ .catch(async (error: unknown) => {
+ const message = formatError(error);
+ await reportDaemonStartupError(message);
log.error(message);
process.exit(1);
});
diff --git a/apps/cli/src/utils/error.test.ts b/apps/cli/src/utils/error.test.ts
new file mode 100644
index 00000000000..1a7d6818f5a
--- /dev/null
+++ b/apps/cli/src/utils/error.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatError, isTransientNetworkError } from './error';
+
+describe('error utilities', () => {
+ it('formats unique messages and codes from the cause chain', () => {
+ const cause = Object.assign(new Error('Could not connect'), { code: 'ConnectionRefused' });
+ const error = new Error('fetch failed', { cause });
+
+ expect(formatError(error)).toBe('fetch failed: Could not connect: ConnectionRefused');
+ });
+
+ it('handles error-like objects and circular cause chains', () => {
+ const error: { cause?: unknown; code: string; message: string; name: string } = {
+ code: 'ECONNRESET',
+ message: 'socket closed',
+ name: 'NetworkError',
+ };
+ error.cause = error;
+
+ expect(formatError(error)).toBe('socket closed: ECONNRESET');
+ });
+
+ it.each([
+ new TypeError('fetch failed'),
+ new Error('request failed', { cause: { code: 'ECONNRESET' } }),
+ new Error('request failed', { cause: { code: 'ConnectionRefused' } }),
+ ])('recognizes transient fetch failures through their cause chain', (error) => {
+ expect(isTransientNetworkError(error)).toBe(true);
+ });
+
+ it('does not classify application errors as transient network failures', () => {
+ expect(isTransientNetworkError(new Error('Unauthorized'))).toBe(false);
+ });
+});
diff --git a/apps/cli/src/utils/error.ts b/apps/cli/src/utils/error.ts
new file mode 100644
index 00000000000..525f528388b
--- /dev/null
+++ b/apps/cli/src/utils/error.ts
@@ -0,0 +1,71 @@
+import { errorCauseFrom, errorMessageFrom } from '@lobechat/utils/error';
+import { toRecord } from '@lobechat/utils/object';
+
+const TRANSIENT_NETWORK_ERROR_CODES = new Set([
+ 'EAI_AGAIN',
+ 'ConnectionRefused',
+ 'ECONNREFUSED',
+ 'ECONNRESET',
+ 'ENETDOWN',
+ 'ENETUNREACH',
+ 'ENOTFOUND',
+ 'ETIMEDOUT',
+ 'UND_ERR_CONNECT_TIMEOUT',
+ 'UND_ERR_HEADERS_TIMEOUT',
+ 'UND_ERR_SOCKET',
+]);
+
+function getErrorCause(error: unknown): unknown {
+ return errorCauseFrom(error) ?? toRecord(error)?.cause;
+}
+
+function getErrorCode(error: unknown): string | undefined {
+ const code = toRecord(error)?.code;
+ return typeof code === 'string' ? code : undefined;
+}
+
+function getErrorMessage(error: unknown): string | undefined {
+ const message = errorMessageFrom(error) ?? toRecord(error)?.message;
+ return typeof message === 'string' ? message : undefined;
+}
+
+function getErrorChain(error: unknown): unknown[] {
+ const chain: unknown[] = [];
+ const seen = new Set<unknown>();
+ let current = error;
+
+ while (current !== null && current !== undefined && !seen.has(current)) {
+ seen.add(current);
+ chain.push(current);
+
+ const cause = getErrorCause(current);
+ if (cause === undefined) break;
+ current = cause;
+ }
+
+ return chain;
+}
+
+export function formatError(error: unknown): string {
+ const details: string[] = [];
+
+ for (const current of getErrorChain(error)) {
+ const message = getErrorMessage(current);
+ if (message && !details.includes(message)) details.push(message);
+
+ const code = getErrorCode(current);
+ if (code && !details.includes(code)) details.push(code);
+ }
+
+ return details.join(': ') || String(error);
+}
+
+export function isTransientNetworkError(error: unknown): boolean {
+ return getErrorChain(error).some((current) => {
+ const message = getErrorMessage(current);
+ if (message && /^(?:fetch failed|failed to fetch)$/i.test(message)) return true;
+
+ const code = getErrorCode(current);
+ return code !== undefined && TRANSIENT_NETWORK_ERROR_CODES.has(code);
+ });
+}