Enhances model service fallback and caching logic

Improves model retrieval strategy for scenarios with invalid/missing API keys

Adds immediate fallback model generation when API key is invalid
Ensures consistent model caching for both API and fallback scenarios
Sorts model options alphabetically for improved user experience

Introduces new getFallbackOptions() method for direct fallback access
Refactors model refresh and error handling to provide more robust model selection
This commit is contained in:
AlexKucera committed 2025-10-24 11:00:42 +02:00
1 parent c3d4888c98
commit fcc495aa8f
2 files changed
+38 -6

No files matched your search

+37 -5
View File
@@ -49,6 +49,19 @@ export class ModelService {
* Used when user changes API key
*/
async refreshModels(): Promise<ModelOption[]> {
// If no API key, immediately return and cache fallback
if (!this.anthropicClient.validateApiKey()) {
const fallback = this.getFallbackModels();
// Cache fallback models as ModelInfo for consistency
this.updateCache(fallback.map(f => ({
id: f.id,
display_name: f.displayName,
created_at: '',
type: 'model'
} as ModelInfo)));
return fallback;
}
try {
const response = await this.anthropicClient.fetchModels();
this.updateCache(response.data);
@@ -56,7 +69,15 @@ export class ModelService {
} catch (error) {
console.error('Failed to refresh models from API:', error);
new Notice('Fetching current models failed. Using hardcoded fallback list.');
return this.getFallbackModels();
const fallback = this.getFallbackModels();
// Cache fallback models as ModelInfo for consistency
this.updateCache(fallback.map(f => ({
id: f.id,
display_name: f.displayName,
created_at: '',
type: 'model'
} as ModelInfo)));
return fallback;
}
}
@@ -81,6 +102,14 @@ export class ModelService {
this.modelCache = null;
}
/**
* Get fallback model options (public API for UI components)
* Returns hardcoded model list as ModelOption array
*/
getFallbackOptions(): ModelOption[] {
return this.getFallbackModels();
}
// MARK: - Private Methods
/**
@@ -109,12 +138,15 @@ export class ModelService {
/**
* Format ModelInfo array to ModelOption array for dropdown
* Uses display_name if available, otherwise falls back to id
* Sorted by displayName for consistent UX across cache/API ordering
*/
private formatModels(models: ModelInfo[]): ModelOption[] {
return models.map(model => ({
id: model.id,
displayName: model.display_name || model.id
}));
return models
.map(model => ({
id: model.id,
displayName: model.display_name || model.id
}))
.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
/**
+1 -1
View File
@@ -55,7 +55,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
await this.refreshModels();
} else if (this.modelDropdown) {
// Show fallback immediately when key is cleared
this.availableModels = await this.plugin.modelService.getAvailableModels();
this.availableModels = this.plugin.modelService.getFallbackOptions();
this.populateModelDropdown(this.modelDropdown);
}
}))