Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/cli/src/acp-integration/acpAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,41 @@ vi.mock('@qwen-code/qwen-code-core', () => ({
provider.ownsModel ??
((model: { envKey?: string }) => model.envKey === provider.envKey),
),
findExistingProviderModels: vi.fn(
(
provider: {
envKey?: string | ((...args: unknown[]) => string);
protocol: string;
protocolOptions?: string[];
ownsModel?: (model: { envKey?: string }) => boolean;
},
modelProviders: Record<string, unknown> | undefined,
) => {
const ownsModel =
provider.ownsModel ??
(typeof provider.envKey === 'string'
? (model: { envKey?: string }) => model.envKey === provider.envKey
: undefined);
if (!ownsModel || !modelProviders) return undefined;
const protocols =
provider.protocolOptions && provider.protocolOptions.length > 0
? provider.protocolOptions
: [provider.protocol];
for (const protocol of protocols) {
const raw = modelProviders[protocol];
if (!Array.isArray(raw)) continue;
const models = raw.filter(
(m): m is { id: string; envKey?: string } =>
typeof m === 'object' &&
m !== null &&
typeof (m as { id?: unknown }).id === 'string' &&
ownsModel(m),
);
if (models.length > 0) return { protocol, models };
}
return undefined;
},
),
ExtensionManager: vi.fn().mockImplementation(() => ({
refreshCache: mockExtensionManagerState.refreshCache,
getLoadedExtensions: vi.fn(() => mockExtensionManagerState.extensions),
Expand Down
43 changes: 7 additions & 36 deletions packages/cli/src/acp-integration/acpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
MCPServerStatus,
McpTransportPool,
POOLED_TRANSPORTS_DEFAULT,
resolveOwnsModel,
findExistingProviderModels,
ExtensionManager,
ExtensionSettingScope,
HookEventName,
Expand Down Expand Up @@ -1414,11 +1414,6 @@ function resolveProviderDocumentationUrl(
return undefined;
}

function isProviderModelConfig(value: unknown): value is ProviderModelConfig {
const record = toRecord(value);
return typeof record['id'] === 'string';
}

function readSettingsEnv(
settings: LoadedSettings,
envKey: string | undefined,
Expand All @@ -1429,35 +1424,6 @@ function readSettingsEnv(
return typeof value === 'string' && value.length > 0 ? value : undefined;
}

function readProviderModels(
settings: LoadedSettings,
protocol: string,
): ProviderModelConfig[] {
const modelProviders = toRecord(
(settings.merged as Record<string, unknown>)['modelProviders'],
);
const models = modelProviders[protocol];
return Array.isArray(models) ? models.filter(isProviderModelConfig) : [];
}

function findExistingProviderModels(
config: ProviderConfig,
settings: LoadedSettings,
):
| { protocol: ProviderConfig['protocol']; models: ProviderModelConfig[] }
| undefined {
const ownsModel = resolveOwnsModel(config);
if (!ownsModel) return undefined;
const protocols = config.protocolOptions?.length
? config.protocolOptions
: [config.protocol];
for (const protocol of protocols) {
const models = readProviderModels(settings, protocol).filter(ownsModel);
if (models.length > 0) return { protocol, models };
}
return undefined;
}

function resolveProviderEnvKey(
config: ProviderConfig,
protocol: ProviderConfig['protocol'],
Expand Down Expand Up @@ -1491,7 +1457,12 @@ function readExistingProviderConfig(
config: ProviderConfig,
settings: LoadedSettings,
): Record<string, unknown> | undefined {
const existing = findExistingProviderModels(config, settings);
const existing = findExistingProviderModels(
config,
(settings.merged as Record<string, unknown>)['modelProviders'] as
| Record<string, unknown>
| undefined,
);
const firstModel = existing?.models[0];
const protocol = existing?.protocol ?? config.protocol;
const baseUrl =
Expand Down
73 changes: 73 additions & 0 deletions packages/cli/src/ui/auth/AuthDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { AuthDialog } from './AuthDialog.js';
import { LoadedSettings } from '../../config/settings.js';
import type { Settings } from '../../config/settingsSchema.js';
import type { Config } from '@qwen-code/qwen-code-core';
import { AuthType } from '@qwen-code/qwen-code-core';
import { renderWithProviders } from '../../test-utils/render.js';
Expand Down Expand Up @@ -1255,6 +1256,78 @@ describe('AuthDialog', { timeout: 15000 }, () => {
},
);

itWhenTuiInputReliable(
'should pre-fill the Model IDs step with previously saved custom model IDs',
async () => {
// User previously saved a custom model ID for Token Plan in settings.
const savedSettings = {
security: { auth: { selectedType: undefined } },
ui: { customThemes: {} },
mcpServers: {},
modelProviders: {
openai: [
{
id: 'my-custom-token-model',
name: '[ModelStudio Token Plan] my-custom-token-model',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
envKey: 'BAILIAN_TOKEN_PLAN_API_KEY',
},
],
},
} as unknown as Settings;
const settings: LoadedSettings = new LoadedSettings(
{
settings: { ui: { customThemes: {} }, mcpServers: {} },
originalSettings: { ui: { customThemes: {} }, mcpServers: {} },
path: '',
},
{
settings: {},
originalSettings: {},
path: '',
},
{
settings: savedSettings,
originalSettings: savedSettings,
path: '',
},
{
settings: { ui: { customThemes: {} }, mcpServers: {} },
originalSettings: { ui: { customThemes: {} }, mcpServers: {} },
path: '',
},
true,
new Set(),
);

const { stdin, lastFrame, unmount } = renderAuthDialog(settings);

await waitForSelectedOption(lastFrame, 'Alibaba ModelStudio');
stdin.write('\r');
await waitForSelectedOption(lastFrame, 'Coding Plan');
await moveDownAndWaitForSelection(stdin, lastFrame, 'Token Plan');
await pressEnterAndWaitFor(
stdin,
lastFrame,
'Alibaba ModelStudio · Step 1/2 · API Key',
);

await typeText(stdin, 'sk-token-plan');

await pressEnterAndWaitFor(
stdin,
lastFrame,
'Alibaba ModelStudio · Step 2/2 · Model IDs',
);

// The Model IDs input is pre-filled with the saved custom model id
// (which only exists in settings, never among the built-in defaults).
expect(lastFrame()).toContain('my-custom-token-model');

unmount();
},
);

itWhenTuiInputReliable(
'should return from Token Plan API key input to Token Plan selection',
async () => {
Expand Down
26 changes: 24 additions & 2 deletions packages/cli/src/ui/auth/AuthDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { t } from '../../i18n/index.js';
import {
findProviderById,
findProviderByCredentials,
findExistingProviderModels,
getDefaultModelIds,
customProvider,
ALIBABA_PROVIDERS,
THIRD_PARTY_PROVIDERS,
Expand Down Expand Up @@ -171,11 +173,26 @@ export function AuthDialog(): React.JSX.Element {

const existingEnv = (settings.merged.env ?? {}) as Record<string, string>;

const getExistingModelIds = (providerConfig: ProviderConfig): string[] => {
const saved = findExistingProviderModels(
providerConfig,
settings.merged.modelProviders as Record<string, unknown> | undefined,
);
if (!saved) return [];
const builtinIds = new Set(getDefaultModelIds(providerConfig));
return saved.models.map((m) => m.id).filter((id) => !builtinIds.has(id));
};

const handleProviderSelect = (providerId: string) => {
clearErrors();
const providerConfig = findProviderById(providerId);
if (!providerConfig) return;
setupFlow.start(providerConfig, undefined, existingEnv);
setupFlow.start(
providerConfig,
undefined,
existingEnv,
getExistingModelIds(providerConfig),
);
pushView('provider-setup');
};

Expand Down Expand Up @@ -228,7 +245,12 @@ export function AuthDialog(): React.JSX.Element {
pushView('thirdparty-select');
break;
case 'CUSTOM_PROVIDER':
setupFlow.start(customProvider, undefined, existingEnv);
setupFlow.start(
customProvider,
undefined,
existingEnv,
getExistingModelIds(customProvider),
);
pushView('provider-setup');
break;
default:
Expand Down
8 changes: 7 additions & 1 deletion packages/cli/src/ui/auth/useProviderSetupFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export function useProviderSetupFlow(
config: ProviderConfig,
initialProtocol?: AuthType,
existingEnv?: Record<string, string>,
existingModelIds?: string[],
) => {
setProvider(config);
const steps = getVisibleSteps(config);
Expand Down Expand Up @@ -160,7 +161,12 @@ export function useProviderSetupFlow(
setApiKey(prefillKey);

setApiKeyError(null);
setModelIds(getDefaultModelIds(config).join(', '));
// Built-in defaults go to the recommended list (checked), user-added
// custom IDs go to the input box. The ModelIdsStep component splits
Comment thread
pomelo-nwu marked this conversation as resolved.
Resolved
// flow.state.modelIds automatically based on config.models.
const defaultIds = getDefaultModelIds(config);
const customIds = existingModelIds ?? [];
setModelIds([...defaultIds, ...customIds].join(', '));
setModelIdsError(null);
setThinkingEnabled(false);
setModalityEnabled(false);
Expand Down
12 changes: 6 additions & 6 deletions packages/cli/src/ui/hooks/useProviderUpdates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ describe('useProviderUpdates', () => {
expect(entry?.diff.currentModelAffected).toBe(false);
});

it('reports currentModelAffected when model is removed', async () => {
mockConfig.getModel.mockReturnValue('old-deprecated-model');
it('excludes user-added custom models from the diff', async () => {
mockConfig.getModel.mockReturnValue('my-custom-model');
(mockSettings.merged[PROVIDER_METADATA_NS] as Record<string, unknown>)[
METADATA_KEY
] = {
Expand All @@ -150,10 +150,10 @@ describe('useProviderUpdates', () => {
[AuthType.USE_OPENAI]: [
...chinaTemplate,
{
id: 'old-deprecated-model',
id: 'my-custom-model',
baseUrl: CODING_PLAN_CHINA_BASE_URL,
envKey: CODING_PLAN_ENV_KEY,
name: '[Coding Plan] old-deprecated-model',
name: '[Coding Plan] my-custom-model',
},
],
};
Expand All @@ -171,8 +171,8 @@ describe('useProviderUpdates', () => {
});

const entry = result.current.providerUpdateRequest?.entries[0];
expect(entry?.diff.currentModelAffected).toBe(true);
expect(entry?.diff.removed).toContain('old-deprecated-model');
expect(entry?.diff.removed).not.toContain('my-custom-model');
Comment thread
pomelo-nwu marked this conversation as resolved.
Resolved
expect(entry?.diff.currentModelAffected).toBe(false);
});

it('executes update when user confirms with "update"', async () => {
Expand Down
10 changes: 8 additions & 2 deletions packages/cli/src/ui/hooks/useProviderUpdates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,14 @@ function getInstalledOwnedModelIds(
if (!modelProviders) return [];
const allModels: ProviderModelConfig[] = modelProviders[protocol] ?? [];
const ownsFn = resolveOwnsModel(provider);
if (!ownsFn) return allModels.map((m) => m.id);
return allModels.filter(ownsFn).map((m) => m.id);
const installedIds = ownsFn
? allModels.filter(ownsFn).map((m) => m.id)
: allModels.map((m) => m.id);
// Only compare built-in model IDs — user-added custom models should not
// appear as "removed" in the diff since they were never part of the
// provider's built-in list.
const builtinIds = new Set(getDefaultModelIds(provider));
return installedIds.filter((id) => builtinIds.has(id));
Comment thread
pomelo-nwu marked this conversation as resolved.
Resolved
}

function findAllPendingUpdates(
Expand Down
Loading
Loading