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): paginate model list requests (#20661)

YuTengjing9359d9ab6117
diff --git a/apps/cli/src/commands/model.test.ts b/apps/cli/src/commands/model.test.ts
index 34f4834f18d..d43d30159c1 100644
--- a/apps/cli/src/commands/model.test.ts
+++ b/apps/cli/src/commands/model.test.ts
@@ -34,6 +34,7 @@ describe('model command', () => {
beforeEach(() => {
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockClear();
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
for (const method of Object.values(mockTrpcClient.aiModel)) {
for (const fn of Object.values(method)) {
@@ -108,6 +109,78 @@ describe('model command', () => {
expect.objectContaining({ id: 'openai', type: 'asr' }),
);
});
+
+ it('should paginate the requested limit with conservative client batches', async () => {
+ const createModels = (count: number, offset: number) =>
+ Array.from({ length: count }, (_, index) => ({ id: `model-${offset + index}` }));
+ mockTrpcClient.aiModel.getAiProviderModelList.query
+ .mockResolvedValueOnce(createModels(50, 0))
+ .mockResolvedValueOnce(createModels(50, 50))
+ .mockResolvedValueOnce(createModels(20, 100));
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'model',
+ 'list',
+ 'openrouter',
+ '--limit',
+ '120',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.aiModel.getAiProviderModelList.query).toHaveBeenNthCalledWith(1, {
+ id: 'openrouter',
+ limit: 50,
+ offset: 0,
+ });
+ expect(mockTrpcClient.aiModel.getAiProviderModelList.query).toHaveBeenNthCalledWith(2, {
+ id: 'openrouter',
+ limit: 50,
+ offset: 50,
+ });
+ expect(mockTrpcClient.aiModel.getAiProviderModelList.query).toHaveBeenNthCalledWith(3, {
+ id: 'openrouter',
+ limit: 20,
+ offset: 100,
+ });
+ expect(JSON.parse(consoleSpy.mock.calls.at(-1)?.[0] as string)).toHaveLength(120);
+ });
+
+ it('should stop pagination after a short page', async () => {
+ const models = [{ id: 'model-1' }, { id: 'model-2' }];
+ mockTrpcClient.aiModel.getAiProviderModelList.query.mockResolvedValue(models);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'model',
+ 'list',
+ 'openrouter',
+ '--limit',
+ '500',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.aiModel.getAiProviderModelList.query).toHaveBeenCalledOnce();
+ expect(mockTrpcClient.aiModel.getAiProviderModelList.query).toHaveBeenCalledWith({
+ id: 'openrouter',
+ limit: 50,
+ offset: 0,
+ });
+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(models, null, 2));
+ });
+
+ it('should reject a non-positive limit before creating the API client', async () => {
+ const program = createProgram();
+
+ await expect(
+ program.parseAsync(['node', 'test', 'model', 'list', 'openai', '--limit', '0']),
+ ).rejects.toThrow('--limit must be a positive integer');
+ expect(mockGetTrpcClient).not.toHaveBeenCalled();
+ });
});
describe('view', () => {
diff --git a/apps/cli/src/commands/model.ts b/apps/cli/src/commands/model.ts
index fff671593dc..267a1e6a646 100644
--- a/apps/cli/src/commands/model.ts
+++ b/apps/cli/src/commands/model.ts
@@ -1,4 +1,4 @@
-import type { Command } from 'commander';
+import { type Command, InvalidArgumentError } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
@@ -7,6 +7,27 @@ import { log } from '../utils/logger';
const isVisibleModel = (model: { visible?: boolean }) => model.visible !== false;
+const DEFAULT_MODEL_LIST_LIMIT = 50;
+
+/**
+ * Use a conservative client batch size instead of mirroring the server's current maximum. This
+ * limits coupling across CLI/server versions; the server must keep accepting this public baseline.
+ */
+const MODEL_LIST_PAGE_SIZE = 50;
+
+const parseModelListLimit = (value: string) => {
+ if (!/^[1-9]\d*$/.test(value)) {
+ throw new InvalidArgumentError('--limit must be a positive integer');
+ }
+
+ const limit = Number(value);
+ if (!Number.isSafeInteger(limit)) {
+ throw new InvalidArgumentError('--limit must be a positive integer');
+ }
+
+ return limit;
+};
+
// The model type `stt` was renamed to the standard `asr`. Accept the legacy
// alias on CLI input and forward/compare `asr`, so existing scripts and muscle
// memory keep working against the new router schema.
@@ -20,7 +41,12 @@ export function registerModelCommand(program: Command) {
model
.command('list <providerId>')
.description('List models for a provider')
- .option('-L, --limit <n>', 'Maximum number of items', '50')
+ .option(
+ '-L, --limit <n>',
+ 'Maximum number of items',
+ parseModelListLimit,
+ DEFAULT_MODEL_LIST_LIMIT,
+ )
.option('--enabled', 'Only show enabled models')
.option(
'--type <type>',
@@ -30,21 +56,30 @@ export function registerModelCommand(program: Command) {
.action(
async (
providerId: string,
- options: { enabled?: boolean; json?: string | boolean; limit?: string; type?: string },
+ options: { enabled?: boolean; json?: string | boolean; limit: number; type?: string },
) => {
const client = await getTrpcClient();
const typeFilter = options.type ? normalizeModelType(options.type) : undefined;
- const input: Record<string, any> = { id: providerId };
- if (options.limit) input.limit = Number.parseInt(options.limit, 10);
- if (options.enabled) input.enabled = true;
- if (typeFilter) input.type = typeFilter;
+ const fetchedItems: any[] = [];
+ let offset = 0;
- const result = await client.aiModel.getAiProviderModelList.query(input as any);
- let items = (Array.isArray(result) ? result : ((result as any).items ?? [])).filter(
- isVisibleModel,
- );
+ while (fetchedItems.length < options.limit) {
+ const pageLimit = Math.min(MODEL_LIST_PAGE_SIZE, options.limit - fetchedItems.length);
+ const input: Record<string, any> = { id: providerId, limit: pageLimit, offset };
+ if (options.enabled) input.enabled = true;
+ if (typeFilter) input.type = typeFilter;
+
+ const result = await client.aiModel.getAiProviderModelList.query(input as any);
+ const pageItems = Array.isArray(result) ? result : ((result as any).items ?? []);
+ fetchedItems.push(...pageItems);
+
+ if (pageItems.length < pageLimit) break;
+ offset += pageItems.length;
+ }
+
+ let items = fetchedItems.slice(0, options.limit).filter(isVisibleModel);
if (typeFilter) {
items = items.filter((m: any) => m.type === typeFilter);