Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion src/web-ui/src/flow_chat/components/ModelSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
status = 'unconfigured';
} else if (availableModels.length === 0) {
status = 'no-enabled-chat-model';
} else if (!nativeModelResolution.model) {
status = 'target-model-unavailable';
} else if (catalogLoadState === 'error') {
status = 'catalog-unavailable';
} else if (nativeModelResolution.recovered) {
Expand All @@ -851,13 +853,14 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({

return {
status,
canSend: configLoadState === 'ready' && availableModels.length > 0,
canSend: configLoadState === 'ready' && nativeModelResolution.model !== null,
};
}, [
allModels.length,
availableModels.length,
catalogLoadState,
configLoadState,
nativeModelResolution.model,
nativeModelResolution.recovered,
]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,29 @@ describe('ModelSelector provider levels', () => {
)).not.toBeNull();
});

it('blocks sending with a missing pinned ID while keeping replacement models selectable', async () => {
const onAvailabilityChange = vi.fn();
flowChatStoreMocks.sessions.set('missing-model-session', {
config: { agentType: 'Standard', modelName: 'removed-id' },
});
vi.mocked(configManager.getConfigs).mockResolvedValue({
'ai.models': CATALOG_MODELS,
'ai.default_models': { primary: 'acme-fast' },
'ai.agent_model_defaults': { mode: 'primary' },
});
await act(async () => {
root.render(<ModelSelector currentMode="Standard" sessionId="missing-model-session"
onAvailabilityChange={onAvailabilityChange} />);
await Promise.resolve();
});
expect(onAvailabilityChange).toHaveBeenLastCalledWith({
status: 'target-model-unavailable', canSend: false,
});
await openMenu();
await openProvider('provider-acme');
expect(modelOption('acme-fast')).not.toBeNull();
});

it('distinguishes configured models from enabled chat models', async () => {
const onAvailabilityChange = vi.fn();
vi.mocked(configManager.getConfigs).mockResolvedValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,29 @@ describe('MessageModule detached dispatch', () => {
});

describe('MessageModule model synchronization', () => {
function modelSyncContext(modelName: string) {
const session = {
sessionId: 'same-name-session',
config: { modelName, workspacePath: '/remote/repo' },
remoteConnectionId: 'ssh-1', remoteSshHost: 'example.test',
maxContextTokens: 32000,
};
const context: any = {
flowChatStore: {
getSurfaceGeneration: () => 0,
getState: () => ({ sessions: new Map([[session.sessionId, session]]) }),
updateSessionModelName: vi.fn(),
updateSessionMaxContextTokens: vi.fn(),
},
};
return { context, session };
}

const sameNameModels = [
{ id: 'model-first', name: 'MOCK-8000', model_name: 'asdf', enabled: true, context_window: 32000 },
{ id: 'asdf', name: 'MOCK-8000-2', model_name: 'asdf', enabled: true, context_window: 64000 },
];

beforeEach(() => {
vi.clearAllMocks();
mockGetConfigs.mockResolvedValue({
Expand All @@ -993,6 +1016,31 @@ describe('MessageModule model synchronization', () => {
mockUpdateSessionModel.mockResolvedValue(undefined);
});

it('sends the exact selected account ID with the original remote routing', async () => {
mockGetConfigs.mockResolvedValue({
'ai.models': sameNameModels, 'ai.default_models': { primary: 'model-first' },
});
const { context, session } = modelSyncContext('asdf');
await syncSessionModelSelection(context, session.sessionId, 'Standard');
expect(context.flowChatStore.updateSessionModelName).not.toHaveBeenCalled();
expect(context.flowChatStore.updateSessionMaxContextTokens).toHaveBeenCalledWith(session.sessionId, 64000);
expect(mockUpdateSessionModel).toHaveBeenCalledWith(expect.objectContaining({
modelName: 'asdf', remoteConnectionId: 'ssh-1', remoteSshHost: 'example.test',
workspacePath: '/remote/repo',
}));
});

it.each(['MOCK-8000', 'asdf', 'removed-model'])('does not replace unavailable ID %s with a name match or Primary', async modelName => {
mockGetConfigs.mockResolvedValue({
'ai.models': [sameNameModels[0]], 'ai.default_models': { primary: 'model-first' },
});
const { context, session } = modelSyncContext(modelName);
await expect(syncSessionModelSelection(context, session.sessionId, 'Standard'))
.rejects.toThrow('model configuration ID');
expect(context.flowChatStore.updateSessionModelName).not.toHaveBeenCalled();
expect(mockUpdateSessionModel).not.toHaveBeenCalled();
});

it('keeps an explicit primary selector when synchronizing before send', async () => {
const session = {
sessionId: 'session-primary',
Expand Down
64 changes: 63 additions & 1 deletion src/web-ui/src/flow_chat/utils/modelResolution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiApi } from '@/infrastructure/api/service-api/AIApi';
import { configManager } from '@/infrastructure/config/services/ConfigManager';
import { setRecentReasoningPreset } from './reasoningPresets';
import { resolveReasoningPresetForSessionCreation } from './modelResolution';
import {
getModelMaxTokens,
resolveModelReference,
resolveModelSelection,
resolveReasoningPresetForSessionCreation,
} from './modelResolution';
import type { AIModelConfig } from '@/infrastructure/config/types';

vi.mock('@/infrastructure/api/service-api/AIApi', () => ({
aiApi: { getModelCatalog: vi.fn() },
Expand All @@ -16,6 +22,62 @@ vi.mock('@/infrastructure/config/services/ConfigManager', () => ({
configManager: { getConfigs: vi.fn() },
}));

describe('configured model identity', () => {
const first: AIModelConfig = {
id: 'model-first', name: 'MOCK-8000', model_name: 'asdf',
provider: 'openai', base_url: 'https://example.test', enabled: true,
category: 'general_chat', capabilities: ['text_chat'], context_window: 32000,
metadata: { provider_instance_id: 'account-1' },
};
const selected: AIModelConfig = {
...first, id: 'asdf', name: 'MOCK-8000-2', context_window: 64000,
metadata: { provider_instance_id: 'account-2' },
};
const models = [first, selected];

it.each([models, [selected, first]])('preserves the selected account regardless of catalog order: %j', (...ordered) => {
const result = resolveModelSelection({ models: ordered, sessionModelId: 'asdf' });
expect(result).toMatchObject({
model: selected, selectorId: 'asdf', concreteModelId: 'asdf',
source: 'session', recovered: false,
});
});

it('does not match a display name even when it equals another config ID', () => {
expect(resolveModelReference([{ ...first, name: 'asdf' }, selected], 'asdf')).toBe(selected);
expect(resolveModelReference(models, 'MOCK-8000-2')).toBeNull();
expect(resolveModelReference([first], 'asdf')).toBeNull();
});

it.each(['primary', 'fast'])('resolves the %s alias through the exact configured ID', selector => {
expect(resolveModelSelection({
models, sessionModelId: selector, defaultModels: { primary: 'asdf', fast: 'asdf' },
})).toMatchObject({ model: selected, selectorId: selector, concreteModelId: 'asdf' });
});

it('keeps Fast fallback to the configured Primary ID', () => {
expect(resolveModelReference(models, 'fast', { fast: 'missing', primary: 'asdf' })).toBe(selected);
});

it.each(['missing', 'MOCK-8000-2'])('marks an unavailable pinned reference %s without choosing another account', sessionModelId => {
expect(resolveModelSelection({ models, sessionModelId, defaultModels: { primary: 'model-first' } }))
.toEqual({ model: null, source: 'session', recovered: true });
});

it('rejects disabled, missing-ID and duplicate-ID entries', () => {
expect(resolveModelReference([first, { ...selected, enabled: false }], 'asdf')).toBeNull();
expect(resolveModelSelection({ models: [{ ...selected, id: undefined }] }).model).toBeNull();
expect(resolveModelReference([selected, { ...first, id: 'asdf' }], 'asdf')).toBeNull();
});

it('uses the selected account context window', async () => {
vi.mocked(configManager.getConfigs).mockResolvedValue({
'ai.models': models, 'ai.default_models': { primary: 'model-first' },
});
await expect(getModelMaxTokens('asdf')).resolves.toBe(64000);
});
});

describe('reasoning preset session creation resolution', () => {
beforeEach(() => {
const storage = new Map<string, string>();
Expand Down
16 changes: 10 additions & 6 deletions src/web-ui/src/flow_chat/utils/modelResolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ export interface ModelSelectionResolution {
function findSelectableModel(models: readonly AIModelConfig[], modelRef: string | null | undefined): AIModelConfig | null {
const value = modelRef?.trim();
if (!value) return null;
return models.find(model => isSelectableTextChatModel(model)
&& (model.id === value || model.name === value || model.model_name === value)
) ?? null;
// Config IDs identify credentials; display and upstream names do not.
const matches = models.filter(model => isSelectableTextChatModel(model) && model.id === value);
return matches.length === 1 ? matches[0] : null;
}

function resolveModelForContextWindow(
Expand Down Expand Up @@ -135,20 +135,24 @@ export function resolveModelSelection({
if (model) {
const selectorId = ref === 'primary' || ref === 'fast'
? ref
: model.id?.trim() || model.model_name.trim();
: model.id;
return {
model,
selectorId,
concreteModelId: model.id?.trim() || model.model_name.trim(),
concreteModelId: model.id,
source: candidate.source,
recovered,
};
}
// A pinned session must not silently switch accounts when its ID is unavailable.
if (candidate.source === 'session') {
return { model: null, source: 'session', recovered: true };
}
recovered = true;
}

const fallback = selectableModels[0];
const concreteModelId = fallback.id?.trim() || fallback.model_name.trim();
const concreteModelId = fallback.id;
return {
model: fallback,
selectorId: concreteModelId,
Expand Down
12 changes: 6 additions & 6 deletions src/web-ui/src/flow_chat/utils/modelSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { configManager } from '@/infrastructure/config/services/ConfigManager';
import type { AIModelConfig, AgentModelDefaultsConfig, DefaultModelsConfig } from '@/infrastructure/config/types';
import { createLogger } from '@/shared/utils/logger';
import type { FlowChatContext } from '../services/flow-chat-manager/types';
import { getModelMaxTokens } from './modelResolution';
import { getModelMaxTokens, resolveModelReference } from './modelResolution';
import { sessionProjectWorkspacePath } from './sessionWorkspace';
import {
getActiveSurfaceScope,
Expand All @@ -34,11 +34,11 @@ function normalizeModelSelection(
return matchedModel ? value : 'primary';
}

const matchedModel = models.find(model =>
model.enabled !== false
&& (model.id === value || model.name === value || model.model_name === value),
);
return matchedModel?.id || 'primary';
const matchedModel = resolveModelReference(models, value);
if (!matchedModel?.id) {
throw new Error(`Unknown, disabled, or ambiguous model configuration ID: ${value}`);
}
return matchedModel.id;
}

export async function syncSessionModelSelection(
Expand Down
Loading