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): preserve bot credentials and login gateway settings (#19831)

AmAzing-3d0850a69c20
diff --git a/apps/cli/src/auth/credentials.test.ts b/apps/cli/src/auth/credentials.test.ts
index fdbee8e7abe..d2f6809c39f 100644
--- a/apps/cli/src/auth/credentials.test.ts
+++ b/apps/cli/src/auth/credentials.test.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { resolveCliDirName } from '../constants/identity';
import {
clearCredentials,
loadCredentials,
@@ -13,7 +14,7 @@ import {
// Use a fixed temp path to avoid hoisting issues with vi.mock
const tmpDir = path.join(os.tmpdir(), 'lobehub-cli-test-creds');
-const credentialsDir = path.join(tmpDir, '.lobehub');
+const credentialsDir = path.join(tmpDir, resolveCliDirName());
const credentialsFile = path.join(credentialsDir, 'credentials.json');
vi.mock('node:os', async (importOriginal) => {
diff --git a/apps/cli/src/auth/refresh.test.ts b/apps/cli/src/auth/refresh.test.ts
index 38584a7d058..02c0d60c4d1 100644
--- a/apps/cli/src/auth/refresh.test.ts
+++ b/apps/cli/src/auth/refresh.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { loadSettings } from '../settings';
+import { resolveServerUrl } from '../settings';
import type { StoredCredentials } from './credentials';
import { loadCredentials, saveCredentials } from './credentials';
import { getValidToken } from './refresh';
@@ -10,16 +10,20 @@ vi.mock('./credentials', () => ({
saveCredentials: vi.fn(),
}));
vi.mock('../settings', () => ({
- loadSettings: vi.fn().mockReturnValue({ serverUrl: 'https://app.lobehub.com' }),
+ resolveServerUrl: vi.fn().mockReturnValue('https://app.lobehub.com'),
}));
describe('getValidToken', () => {
beforeEach(() => {
+ vi.mocked(loadCredentials).mockClear();
+ vi.mocked(saveCredentials).mockClear();
+ vi.mocked(resolveServerUrl).mockClear();
+ vi.mocked(resolveServerUrl).mockReturnValue('https://app.lobehub.com');
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
- vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
it('should return null when no credentials stored', async () => {
@@ -196,7 +200,7 @@ describe('getValidToken', () => {
refreshToken: 'my-refresh-token',
};
vi.mocked(loadCredentials).mockReturnValue(creds);
- vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://my-server.com' });
+ vi.mocked(resolveServerUrl).mockReturnValueOnce('https://my-server.com');
vi.mocked(fetch).mockResolvedValue({
json: vi.fn().mockResolvedValue({
diff --git a/apps/cli/src/commands/bot.test.ts b/apps/cli/src/commands/bot.test.ts
index d77738bf71d..96171e6d3d4 100644
--- a/apps/cli/src/commands/bot.test.ts
+++ b/apps/cli/src/commands/bot.test.ts
@@ -1,3 +1,4 @@
+import { BOT_CREDENTIAL_MASK } from '@lobechat/const';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -12,6 +13,8 @@ const { mockTrpcClient } = vi.hoisted(() => ({
delete: { mutate: vi.fn() },
getByAgentId: { query: vi.fn() },
list: { query: vi.fn() },
+ listPlatforms: { query: vi.fn() },
+ testConnection: { mutate: vi.fn() },
update: { mutate: vi.fn() },
},
},
@@ -27,7 +30,9 @@ describe('bot command', () => {
let consoleSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
+ throw new Error(`process.exit ${code}`);
+ });
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
for (const method of Object.values(mockTrpcClient.agentBotProvider)) {
@@ -35,6 +40,32 @@ describe('bot command', () => {
(fn as ReturnType<typeof vi.fn>).mockReset();
}
}
+ mockTrpcClient.agentBotProvider.listPlatforms.query.mockResolvedValue([
+ {
+ id: 'discord',
+ schema: [
+ {
+ key: 'credentials',
+ properties: [
+ { key: 'botToken', required: true },
+ { key: 'publicKey', required: true },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'telegram',
+ schema: [
+ {
+ key: 'credentials',
+ properties: [
+ { key: 'botToken', required: true },
+ { key: 'secretToken', required: false },
+ ],
+ },
+ ],
+ },
+ ]);
});
afterEach(() => {
@@ -113,6 +144,9 @@ describe('bot command', () => {
describe('view', () => {
it('should display bot details', async () => {
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
+ { agentId: 'agent1', id: 'b1', platform: 'discord' },
+ ]);
mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
{
applicationId: 'app123',
@@ -124,17 +158,19 @@ describe('bot command', () => {
]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'bot', 'view', 'b1', '--agent', 'agent1']);
+ await program.parseAsync(['node', 'test', 'bot', 'view', 'b1']);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('discord'));
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('app123'));
});
it('should error when bot not found', async () => {
- mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([]);
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'bot', 'view', 'nonexistent', '--agent', 'agent1']);
+ await expect(
+ program.parseAsync(['node', 'test', 'bot', 'view', 'nonexistent']),
+ ).rejects.toThrow('process.exit 1');
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
expect(exitSpy).toHaveBeenCalledWith(1);
@@ -201,20 +237,22 @@ describe('bot command', () => {
it('should reject invalid platform', async () => {
const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'bot',
- 'add',
- '--agent',
- 'agent1',
- '--platform',
- 'invalid',
- '--app-id',
- 'x',
- '--bot-token',
- 'x',
- ]);
+ await expect(
+ program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'add',
+ '--agent',
+ 'agent1',
+ '--platform',
+ 'invalid',
+ '--app-id',
+ 'x',
+ '--bot-token',
+ 'x',
+ ]),
+ ).rejects.toThrow('process.exit 1');
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Invalid platform'));
expect(exitSpy).toHaveBeenCalledWith(1);
@@ -222,21 +260,23 @@ describe('bot command', () => {
it('should reject missing required credentials', async () => {
const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'bot',
- 'add',
- '--agent',
- 'agent1',
- '--platform',
- 'discord',
- '--app-id',
- 'app123',
- '--bot-token',
- 'tok123',
- // missing --public-key
- ]);
+ await expect(
+ program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'add',
+ '--agent',
+ 'agent1',
+ '--platform',
+ 'discord',
+ '--app-id',
+ 'app123',
+ '--bot-token',
+ 'tok123',
+ // missing --public-key
+ ]),
+ ).rejects.toThrow('process.exit 1');
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Missing required'));
expect(exitSpy).toHaveBeenCalledWith(1);
@@ -244,23 +284,89 @@ describe('bot command', () => {
});
describe('update', () => {
- it('should update bot credentials', async () => {
+ const mockExistingBot = (credentials: Record<string, string>) => {
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
+ { agentId: 'agent1', id: 'b1', platform: 'discord' },
+ ]);
+ mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
+ { agentId: 'agent1', credentials, id: 'b1', platform: 'discord', settings: {} },
+ ]);
+ };
+
+ it('preserves the existing public key when updating the token', async () => {
+ mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });
mockTrpcClient.agentBotProvider.update.mutate.mockResolvedValue({});
const program = createProgram();
await program.parseAsync(['node', 'test', 'bot', 'update', 'b1', '--bot-token', 'new-token']);
- expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith(
- expect.objectContaining({
- credentials: { botToken: 'new-token' },
- id: 'b1',
- }),
- );
+ expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
+ credentials: { botToken: 'new-token', publicKey: 'public-key' },
+ id: 'b1',
+ });
+ });
+
+ it('preserves the existing token mask when updating the public key', async () => {
+ mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'old-public-key' });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'update',
+ 'b1',
+ '--public-key',
+ 'new-public-key',
+ ]);
+
+ expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
+ credentials: { botToken: BOT_CREDENTIAL_MASK, publicKey: 'new-public-key' },
+ id: 'b1',
+ });
+ });
+
+ it('does not send credentials for a settings-only update', async () => {
+ mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'bot', 'update', 'b1', '--dm-policy', 'open']);
+
+ expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
+ id: 'b1',
+ settings: { dmPolicy: 'open' },
+ });
+ });
+
+ it('does not carry credentials from the old platform when changing platform', async () => {
+ mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'discord-public-key' });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'update',
+ 'b1',
+ '--platform',
+ 'telegram',
+ '--bot-token',
+ 'telegram-token',
+ ]);
+
+ expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
+ credentials: { botToken: 'telegram-token' },
+ id: 'b1',
+ platform: 'telegram',
+ });
});
it('should error when no changes specified', async () => {
+ mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });
const program = createProgram();
- await program.parseAsync(['node', 'test', 'bot', 'update', 'b1']);
+ await expect(program.parseAsync(['node', 'test', 'bot', 'update', 'b1'])).rejects.toThrow(
+ 'process.exit 1',
+ );
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No changes'));
expect(exitSpy).toHaveBeenCalledWith(1);
@@ -320,13 +426,16 @@ describe('bot command', () => {
describe('connect', () => {
it('should connect a bot', async () => {
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
+ { agentId: 'agent1', id: 'b1', platform: 'discord' },
+ ]);
mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
{ applicationId: 'app123', id: 'b1', platform: 'discord' },
]);
mockTrpcClient.agentBotProvider.connectBot.mutate.mockResolvedValue({ status: 'connected' });
const program = createProgram();
- await program.parseAsync(['node', 'test', 'bot', 'connect', 'b1', '--agent', 'agent1']);
+ await program.parseAsync(['node', 'test', 'bot', 'connect', 'b1']);
expect(mockTrpcClient.agentBotProvider.connectBot.mutate).toHaveBeenCalledWith({
applicationId: 'app123',
@@ -336,18 +445,12 @@ describe('bot command', () => {
});
it('should error when bot not found', async () => {
- mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([]);
+ mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'bot',
- 'connect',
- 'nonexistent',
- '--agent',
- 'agent1',
- ]);
+ await expect(
+ program.parseAsync(['node', 'test', 'bot', 'connect', 'nonexistent']),
+ ).rejects.toThrow('process.exit 1');
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
expect(exitSpy).toHaveBeenCalledWith(1);
diff --git a/apps/cli/src/commands/bot.ts b/apps/cli/src/commands/bot.ts
index 0fa2362f63a..9875a6c265d 100644
--- a/apps/cli/src/commands/bot.ts
+++ b/apps/cli/src/commands/bot.ts
@@ -745,7 +745,12 @@ export function registerBotCommand(program: Command) {
const platformDef = await resolvePlatform(client, platform);
const { credentials } = extractCredentials(platformDef, options);
- if (Object.keys(credentials).length > 0) input.credentials = credentials;
+ if (Object.keys(credentials).length > 0) {
+ input.credentials =
+ platform === existing.platform
+ ? { ...(existing.credentials as Record<string, string>), ...credentials }
+ : credentials;
+ }
if (options.appId) input.applicationId = options.appId;
if (options.platform) input.platform = options.platform;
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 60c896a8956..e8419111051 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -84,7 +84,7 @@ let connectCalled = false;
let lastSentToolResponse: any = null;
let lastSentSystemInfoResponse: any = null;
vi.mock('@lobechat/device-gateway-client', () => ({
- GatewayClient: vi.fn().mockImplementation((opts: any) => {
+ GatewayClient: vi.fn().mockImplementation(function (opts: any) {
clientOptions = opts;
clientEventHandlers = {};
connectCalled = false;
@@ -113,8 +113,15 @@ vi.mock('@lobechat/device-gateway-client', () => ({
describe('connect command', () => {
let exitSpy: ReturnType<typeof vi.spyOn>;
+ let signalListeners: Map<NodeJS.Signals, Set<(...args: unknown[]) => void>>;
beforeEach(() => {
+ signalListeners = new Map(
+ (['SIGINT', 'SIGTERM'] as const).map((signal) => [
+ signal,
+ new Set(process.listeners(signal)),
+ ]),
+ );
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
mockRunningPid = null;
mockSpawnedPid = 0;
@@ -122,7 +129,12 @@ describe('connect command', () => {
});
afterEach(() => {
- exitSpy.mockRestore();
+ for (const [signal, existing] of signalListeners) {
+ for (const listener of process.listeners(signal)) {
+ if (!existing.has(listener)) process.removeListener(signal, listener);
+ }
+ }
+ vi.restoreAllMocks();
vi.clearAllMocks();
});
diff --git a/apps/cli/src/commands/file.test.ts b/apps/cli/src/commands/file.test.ts
index 0e5ba5bbd84..b62e05c84fe 100644
--- a/apps/cli/src/commands/file.test.ts
+++ b/apps/cli/src/commands/file.test.ts
@@ -231,11 +231,14 @@ describe('file command', () => {
expect(mockTrpcClient.upload.createS3PreSignedUrl.mutate).toHaveBeenCalled();
expect(fetchSpy).toHaveBeenCalledWith(
'https://s3/presigned',
- expect.objectContaining({ method: 'PUT' }),
+ expect.objectContaining({
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
+ method: 'PUT',
+ }),
);
expect(mockTrpcClient.file.createFile.mutate).toHaveBeenCalledWith(
expect.objectContaining({
- fileType: 'text/plain',
+ fileType: 'text/plain; charset=utf-8',
name: path.basename(tmpFile),
url: expect.stringContaining('.txt'),
}),
@@ -263,7 +266,14 @@ describe('file command', () => {
await program.parseAsync(['node', 'test', 'file', 'upload', '--file', tmpFile]);
expect(mockTrpcClient.file.createFile.mutate).toHaveBeenCalledWith(
- expect.objectContaining({ fileType: 'application/json' }),
+ expect.objectContaining({ fileType: 'application/json; charset=utf-8' }),
+ );
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'https://s3/presigned',
+ expect.objectContaining({
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ method: 'PUT',
+ }),
);
} finally {
fetchSpy.mockRestore();
diff --git a/apps/cli/src/commands/login.test.ts b/apps/cli/src/commands/login.test.ts
index e6b39f99342..c20047b2fa4 100644
--- a/apps/cli/src/commands/login.test.ts
+++ b/apps/cli/src/commands/login.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getUserIdFromApiKey } from '../auth/apiKey';
import { saveCredentials } from '../auth/credentials';
+import type * as Settings from '../settings';
import { loadSettings, saveSettings } from '../settings';
import { log } from '../utils/logger';
import { registerLoginCommand, resolveCommandExecutable } from './login';
@@ -15,7 +16,8 @@ vi.mock('../auth/apiKey', () => ({
vi.mock('../auth/credentials', () => ({
saveCredentials: vi.fn(),
}));
-vi.mock('../settings', () => ({
+vi.mock('../settings', async (importOriginal) => ({
+ ...(await importOriginal<typeof Settings>()),
loadSettings: vi.fn().mockReturnValue(null),
saveSettings: vi.fn(),
}));
@@ -38,6 +40,13 @@ describe('login command', () => {
const originalSystemRoot = process.env.SystemRoot;
beforeEach(() => {
+ vi.mocked(getUserIdFromApiKey).mockClear();
+ vi.mocked(saveCredentials).mockClear();
+ vi.mocked(loadSettings).mockClear();
+ vi.mocked(saveSettings).mockClear();
+ vi.mocked(log.info).mockClear();
+ vi.mocked(log.error).mockClear();
+ vi.mocked(log.warn).mockClear();
vi.useFakeTimers();
vi.stubGlobal('fetch', vi.fn());
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
@@ -48,13 +57,18 @@ describe('login command', () => {
afterEach(() => {
vi.useRealTimers();
exitSpy.mockRestore();
- process.env.LOBEHUB_CLI_API_KEY = originalApiKey;
- process.env.PATH = originalPath;
- process.env.PATHEXT = originalPathext;
- process.env.SystemRoot = originalSystemRoot;
- vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ restoreEnv('LOBEHUB_CLI_API_KEY', originalApiKey);
+ restoreEnv('PATH', originalPath);
+ restoreEnv('PATHEXT', originalPathext);
+ restoreEnv('SystemRoot', originalSystemRoot);
});
+ function restoreEnv(name: string, value: string | undefined) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+
function createProgram() {
const program = new Command();
program.exitOverride();
@@ -106,11 +120,19 @@ describe('login command', () => {
async function runLoginAndAdvanceTimers(program: Command, args: string[] = []) {
const parsePromise = runLogin(program, args);
+ let parseError: unknown;
+ const observedParsePromise = parsePromise.then(
+ () => undefined,
+ (error: unknown) => {
+ parseError = error;
+ },
+ );
// Advance timers to let sleep resolve in the polling loop
for (let i = 0; i < 10; i++) {
await vi.advanceTimersByTimeAsync(2000);
}
- return parsePromise;
+ await observedParsePromise;
+ if (parseError) throw parseError;
}
it('should complete login flow successfully', async () => {
@@ -191,6 +213,41 @@ describe('login command', () => {
});
});
+ it('should preserve existing gateway for environment api key on the official server', async () => {
+ process.env.LOBEHUB_CLI_API_KEY = '[REDACTED:api-key]';
+ vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-123');
+ vi.mocked(loadSettings).mockReturnValueOnce({
+ gatewayUrl: 'https://gateway.example.com',
+ serverUrl: undefined,
+ });
+
+ const program = createProgram();
+ await runLogin(program);
+
+ expect(saveSettings).toHaveBeenCalledWith({
+ gatewayUrl: 'https://gateway.example.com',
+ serverUrl: 'https://app.lobehub.com',
+ });
+ });
+
+ it('should preserve existing gateway for OIDC login on the official server', async () => {
+ vi.mocked(loadSettings).mockReturnValueOnce({
+ gatewayUrl: 'https://gateway.example.com',
+ serverUrl: undefined,
+ });
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(deviceAuthResponse())
+ .mockResolvedValueOnce(tokenSuccessResponse());
+
+ const program = createProgram();
+ await runLoginAndAdvanceTimers(program);
+
+ expect(saveSettings).toHaveBeenCalledWith({
+ gatewayUrl: 'https://gateway.example.com',
+ serverUrl: 'https://app.lobehub.com',
+ });
+ });
+
it('should clear existing gateway when logging into a different server', async () => {
vi.mocked(loadSettings).mockReturnValueOnce({
gatewayUrl: 'https://gateway.example.com',
diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.ts
index 954c023d5e3..2d1b94a7c60 100644
--- a/apps/cli/src/commands/login.ts
+++ b/apps/cli/src/commands/login.ts
@@ -71,7 +71,8 @@ export function registerLoginCommand(program: Command) {
await getUserIdFromApiKey(apiKey, serverUrl);
const existingSettings = loadSettings();
- const shouldPreserveGateway = existingSettings?.serverUrl === serverUrl;
+ const existingServerUrl = existingSettings?.serverUrl || OFFICIAL_SERVER_URL;
+ const shouldPreserveGateway = !!existingSettings && existingServerUrl === serverUrl;
saveSettings(
shouldPreserveGateway
@@ -203,7 +204,8 @@ export function registerLoginCommand(program: Command) {
});
const existingSettings = loadSettings();
- const shouldPreserveGateway = existingSettings?.serverUrl === serverUrl;
+ const existingServerUrl = existingSettings?.serverUrl || OFFICIAL_SERVER_URL;
+ const shouldPreserveGateway = !!existingSettings && existingServerUrl === serverUrl;
saveSettings(
shouldPreserveGateway
diff --git a/apps/cli/src/commands/memory.test.ts b/apps/cli/src/commands/memory.test.ts
index edd76317cf3..b4af0fe1860 100644
--- a/apps/cli/src/commands/memory.test.ts
+++ b/apps/cli/src/commands/memory.test.ts
@@ -102,7 +102,10 @@ describe('memory command', () => {
describe('create', () => {
it('should create an identity memory', async () => {
- mockTrpcClient.userMemory.createIdentity.mutate.mockResolvedValue({ id: 'mem-1' });
+ mockTrpcClient.userMemory.createIdentity.mutate.mockResolvedValue({
+ identityId: 'identity-1',
+ userMemoryId: 'mem-1',
+ });
const program = createProgram();
await program.parseAsync([
@@ -120,6 +123,8 @@ describe('memory command', () => {
expect.objectContaining({ description: 'Software dev', type: 'professional' }),
);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('mem-1'));
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('identity: identity-1'));
+ expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining('unknown'));
});
});
diff --git a/apps/cli/src/commands/search.test.ts b/apps/cli/src/commands/search.test.ts
index 60e9370281e..7ea3ca4ea65 100644
--- a/apps/cli/src/commands/search.test.ts
+++ b/apps/cli/src/commands/search.test.ts
@@ -58,7 +58,7 @@ describe('search command', () => {
mockTrpcClient.search.query.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'hello']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'hello']);
expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
expect.objectContaining({ query: 'hello' }),
@@ -69,7 +69,7 @@ describe('search command', () => {
mockTrpcClient.search.query.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'test', '--type', 'agent']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'test', '--type', 'agent']);
expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
expect.objectContaining({ query: 'test', type: 'agent' }),
@@ -80,7 +80,7 @@ describe('search command', () => {
mockTrpcClient.search.query.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'test', '-L', '5']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'test', '-L', '5']);
expect(mockTrpcClient.search.query.query).toHaveBeenCalledWith(
expect.objectContaining({ limitPerType: 5 }),
@@ -92,7 +92,7 @@ describe('search command', () => {
mockTrpcClient.search.query.query.mockResolvedValue(results);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'test', '--json']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'test', '--json']);
expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(results, null, 2));
});
@@ -101,7 +101,7 @@ describe('search command', () => {
mockTrpcClient.search.query.query.mockResolvedValue([]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'nothing']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'nothing']);
expect(consoleSpy).toHaveBeenCalledWith('No results found.');
});
@@ -113,7 +113,7 @@ describe('search command', () => {
]);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'test']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'test']);
// Should display group headers
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('agent'));
@@ -127,7 +127,7 @@ describe('search command', () => {
});
const program = createProgram();
- await program.parseAsync(['node', 'test', 'search', 'test']);
+ await program.parseAsync(['node', 'test', 'search', '-q', 'test']);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('agents'));
});
@@ -135,9 +135,15 @@ describe('search command', () => {
it('should reject invalid type', async () => {
const program = createProgram();
const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- await program.parseAsync(['node', 'test', 'search', 'test', '--type', 'invalid']);
+ exitSpy.mockImplementation(() => {
+ throw new Error('process.exit');
+ });
+ await expect(
+ program.parseAsync(['node', 'test', 'search', '-q', 'test', '--type', 'invalid']),
+ ).rejects.toThrow('process.exit');
expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.search.query.query).not.toHaveBeenCalled();
stderrSpy.mockRestore();
});
diff --git a/apps/cli/src/commands/task.test.ts b/apps/cli/src/commands/task.test.ts
index 94e85b541c1..174199d0046 100644
--- a/apps/cli/src/commands/task.test.ts
+++ b/apps/cli/src/commands/task.test.ts
@@ -60,7 +60,7 @@ describe('task create', () => {
id: 'task_1',
identifier: 'T-1',
name: 'Personal task',
- url: 'https://app.example.com/task/T-1',
+ url: 'https://app.example.com/task/T-1/personal-task',
},
null,
2,
@@ -81,7 +81,7 @@ describe('task create', () => {
expect(mockLogInfo).toHaveBeenCalledWith(expect.stringContaining('LOBE-321'));
expect(consoleSpy).toHaveBeenCalledWith(
- expect.stringContaining('https://app.example.com/lobehub/task/LOBE-321'),
+ expect.stringContaining('https://app.example.com/lobehub/task/LOBE-321/workspace-task'),
);
});
});
diff --git a/apps/cli/src/runtime/runtimeIntegration.test.ts b/apps/cli/src/runtime/runtimeIntegration.test.ts
index cc457c1726e..ad39b083663 100644
--- a/apps/cli/src/runtime/runtimeIntegration.test.ts
+++ b/apps/cli/src/runtime/runtimeIntegration.test.ts
@@ -1,4 +1,4 @@
-import type { AgentRuntimeHost } from '@lobechat/agent-runtime';
+import type { AgentRuntimeHost, AgentState } from '@lobechat/agent-runtime';
import { callTool, callToolsBatch } from '@lobechat/agent-runtime';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -33,21 +33,19 @@ const createUsage = () => ({
tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
});
-const createState = (overrides?: Record<string, unknown>) =>
- ({
- cost: createCost(),
- createdAt: '2026-07-09T00:00:00.000Z',
- lastModified: '2026-07-09T00:00:00.000Z',
- maxSteps: 100,
- messages: [],
- metadata: { agentId: 'agent-1', topicId: 'topic-1' },
- operationId: 'op-1',
- status: 'running',
- stepCount: 0,
- toolManifestMap: {},
- usage: createUsage(),
- ...overrides,
- }) as never;
+const createState = (overrides?: Partial<AgentState>): AgentState => ({
+ cost: createCost(),
+ createdAt: '2026-07-09T00:00:00.000Z',
+ lastModified: '2026-07-09T00:00:00.000Z',
+ maxSteps: 100,
+ messages: [],
+ operationId: 'op-1',
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ status: 'running',
+ stepCount: 0,
+ usage: createUsage(),
+ ...overrides,
+});
const createToolCall = (id = 'tool-call-1') => ({
apiName: 'search',
diff --git a/apps/cli/src/utils/agentStream.test.ts b/apps/cli/src/utils/agentStream.test.ts
index 485ba25c5fc..f3e13aed8d4 100644
--- a/apps/cli/src/utils/agentStream.test.ts
+++ b/apps/cli/src/utils/agentStream.test.ts
@@ -452,7 +452,7 @@ describe('streamAgentEventsViaWebSocket', () => {
capturedWs!.onclose?.({ code: 1011, reason: 'gateway shutdown', type: 'close' });
await expect(promise).rejects.toThrow(
- 'Agent gateway WebSocket closed before completion: [object Object]',
+ 'Agent gateway WebSocket closed before completion (code 1011: gateway shutdown)',
);
});