feat: add dynamic model fetching from Anthropic API #2
No files matched your search
+34
-5
@@ -2,11 +2,12 @@
|
|||||||
// ABOUTME: Handles API requests, error handling, retry logic, and response parsing
|
// ABOUTME: Handles API requests, error handling, retry logic, and response parsing
|
||||||
|
|
||||||
import { requestUrl } from 'obsidian';
|
import { requestUrl } from 'obsidian';
|
||||||
import { AnthropicRequest, AnthropicResponse, AnthropicModel, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS } from '../types';
|
import { AnthropicRequest, AnthropicResponse, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS, ModelsListResponse } from '../types';
|
||||||
|
|
||||||
export class AnthropicClient {
|
export class AnthropicClient {
|
||||||
private apiKey: string;
|
private apiKey: string;
|
||||||
private baseUrl = 'https://api.anthropic.com/v1/messages';
|
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
||||||
|
private modelsUrl = 'https://api.anthropic.com/v1/models';
|
||||||
private readonly MAX_RETRIES = 3;
|
private readonly MAX_RETRIES = 3;
|
||||||
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
async cleanupText(
|
async cleanupText(
|
||||||
text: string,
|
text: string,
|
||||||
model: AnthropicModel,
|
model: string,
|
||||||
cleanupPrompt: string,
|
cleanupPrompt: string,
|
||||||
enableCommentary = false,
|
enableCommentary = false,
|
||||||
commentaryStyle: CommentaryStyle = 'constructive',
|
commentaryStyle: CommentaryStyle = 'constructive',
|
||||||
@@ -77,7 +78,7 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
return this.parseStructuredResponse(response, enableCommentary);
|
return this.parseStructuredResponse(response, enableCommentary);
|
||||||
}
|
}
|
||||||
|
|
||||||
async testConnection(model: AnthropicModel): Promise<{
|
async testConnection(model: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
details?: {
|
details?: {
|
||||||
@@ -174,10 +175,38 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
return { cleanedText, commentary };
|
return { cleanedText, commentary };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fetchModels(): Promise<ModelsListResponse> {
|
||||||
|
if (!this.apiKey) {
|
||||||
|
throw new Error('API key is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await requestUrl({
|
||||||
|
url: this.modelsUrl,
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'x-api-key': this.apiKey,
|
||||||
|
'anthropic-version': '2023-06-01'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 300) {
|
||||||
|
throw new Error(`Models API request failed: ${response.status}\n${response.text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json as ModelsListResponse;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error(`Network request failed: ${String(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||||
try {
|
try {
|
||||||
const response = await requestUrl({
|
const response = await requestUrl({
|
||||||
url: this.baseUrl,
|
url: this.messagesUrl,
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
|||||||
@@ -2,14 +2,16 @@
|
|||||||
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
||||||
|
|
||||||
import { Editor, MarkdownView, Plugin } from 'obsidian';
|
import { Editor, MarkdownView, Plugin } from 'obsidian';
|
||||||
import { FreewritingCleanupSettings } from './types';
|
import { FreewritingCleanupSettings, FreewritingCleanupData } from './types';
|
||||||
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
|
import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings';
|
||||||
import { CleanupService } from './services/cleanupService';
|
import { CleanupService } from './services/cleanupService';
|
||||||
|
import { ModelService } from './services/modelService';
|
||||||
import { CleanupCommand } from './commands/cleanupCommand';
|
import { CleanupCommand } from './commands/cleanupCommand';
|
||||||
|
|
||||||
export default class FreewritingCleanupPlugin extends Plugin {
|
export default class FreewritingCleanupPlugin extends Plugin {
|
||||||
settings: FreewritingCleanupSettings;
|
settings: FreewritingCleanupSettings;
|
||||||
cleanupService: CleanupService;
|
cleanupService: CleanupService;
|
||||||
|
modelService: ModelService;
|
||||||
cleanupCommand: CleanupCommand;
|
cleanupCommand: CleanupCommand;
|
||||||
|
|
||||||
async onload() {
|
async onload() {
|
||||||
@@ -17,8 +19,15 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
|
|
||||||
// Initialize services
|
// Initialize services
|
||||||
this.cleanupService = new CleanupService(this.settings.apiKey);
|
this.cleanupService = new CleanupService(this.settings.apiKey);
|
||||||
|
this.modelService = new ModelService(this.cleanupService.anthropicClient);
|
||||||
this.cleanupCommand = new CleanupCommand(this.cleanupService);
|
this.cleanupCommand = new CleanupCommand(this.cleanupService);
|
||||||
|
|
||||||
|
// Load model cache
|
||||||
|
const data = await this.loadData() as FreewritingCleanupData | null;
|
||||||
|
if (data?.modelCache) {
|
||||||
|
this.modelService.loadCache(data.modelCache);
|
||||||
|
}
|
||||||
|
|
||||||
// Register command
|
// Register command
|
||||||
this.registerCommand();
|
this.registerCommand();
|
||||||
|
|
||||||
@@ -37,7 +46,12 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async saveSettings() {
|
async saveSettings() {
|
||||||
await this.saveData(this.settings);
|
// Save settings with model cache
|
||||||
|
const data: FreewritingCleanupData = {
|
||||||
|
...this.settings,
|
||||||
|
modelCache: this.modelService?.getCache() || undefined
|
||||||
|
};
|
||||||
|
await this.saveData(data);
|
||||||
|
|
||||||
// Update the cleanup service with new settings
|
// Update the cleanup service with new settings
|
||||||
if (this.cleanupService) {
|
if (this.cleanupService) {
|
||||||
|
|||||||
@@ -6,10 +6,15 @@ import { AnthropicClient } from '../api/anthropicClient';
|
|||||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||||
|
|
||||||
export class CleanupService {
|
export class CleanupService {
|
||||||
private anthropicClient: AnthropicClient;
|
private client: AnthropicClient;
|
||||||
|
|
||||||
|
// Expose client for ModelService
|
||||||
|
get anthropicClient(): AnthropicClient {
|
||||||
|
return this.client;
|
||||||
|
}
|
||||||
|
|
||||||
constructor(apiKey: string) {
|
constructor(apiKey: string) {
|
||||||
this.anthropicClient = new AnthropicClient(apiKey);
|
this.client = new AnthropicClient(apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
@@ -20,7 +25,7 @@ export class CleanupService {
|
|||||||
throw new Error('No text selected for cleanup');
|
throw new Error('No text selected for cleanup');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.anthropicClient.validateApiKey()) {
|
if (!this.client.validateApiKey()) {
|
||||||
throw new Error('API key is not configured. Please check your plugin settings.');
|
throw new Error('API key is not configured. Please check your plugin settings.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,7 +37,7 @@ export class CleanupService {
|
|||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { cleanedText, commentary } = await this.anthropicClient.cleanupText(
|
const { cleanedText, commentary } = await this.client.cleanupText(
|
||||||
text,
|
text,
|
||||||
settings.model,
|
settings.model,
|
||||||
settings.cleanupPrompt,
|
settings.cleanupPrompt,
|
||||||
@@ -74,7 +79,7 @@ export class CleanupService {
|
|||||||
outputTokens?: number;
|
outputTokens?: number;
|
||||||
};
|
};
|
||||||
}> {
|
}> {
|
||||||
if (!this.anthropicClient.validateApiKey()) {
|
if (!this.client.validateApiKey()) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'API key is not configured'
|
message: 'API key is not configured'
|
||||||
@@ -82,7 +87,7 @@ export class CleanupService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await this.anthropicClient.testConnection(settings.model);
|
const result = await this.client.testConnection(settings.model);
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return {
|
return {
|
||||||
@@ -105,7 +110,7 @@ export class CleanupService {
|
|||||||
// MARK: - Configuration Methods
|
// MARK: - Configuration Methods
|
||||||
|
|
||||||
updateApiKey(apiKey: string): void {
|
updateApiKey(apiKey: string): void {
|
||||||
this.anthropicClient.updateApiKey(apiKey);
|
this.client.updateApiKey(apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
validateSettings(settings: FreewritingCleanupSettings): {
|
validateSettings(settings: FreewritingCleanupSettings): {
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
// ABOUTME: Service for managing Claude model list from Anthropic API
|
||||||
|
|
|||||||
|
// ABOUTME: Handles fetching, caching with 24-hour TTL, and fallback to hardcoded list
|
||||||
|
|
||||||
|
import { Notice } from 'obsidian';
|
||||||
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
|
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||||
|
|
||||||
|
export interface ModelOption {
|
||||||
|
id: string;
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModelService {
|
||||||
|
private anthropicClient: AnthropicClient;
|
||||||
|
private modelCache: ModelCache | null = null;
|
||||||
|
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
constructor(anthropicClient: AnthropicClient) {
|
||||||
|
this.anthropicClient = anthropicClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get available models with caching and fallback logic
|
||||||
|
* Returns models from cache if valid, otherwise fetches from API
|
||||||
|
* Falls back to hardcoded list if API fails
|
||||||
|
*/
|
||||||
|
async getAvailableModels(): Promise<ModelOption[]> {
|
||||||
|
// Check if we have a valid cache
|
||||||
|
if (this.isCacheValid() && this.modelCache) {
|
||||||
|
return this.formatModels(this.modelCache.models);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to fetch from API
|
||||||
|
try {
|
||||||
|
const response = await this.anthropicClient.fetchModels();
|
||||||
|
this.updateCache(response.data);
|
||||||
|
return this.formatModels(response.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch models from API:', error);
|
||||||
|
new Notice('Fetching current models failed. Using hardcoded fallback list.');
|
||||||
|
return this.getFallbackModels();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force refresh the model list from API
|
||||||
|
* Used when user changes API key
|
||||||
|
*/
|
||||||
|
async refreshModels(): Promise<ModelOption[]> {
|
||||||
|
try {
|
||||||
|
const response = await this.anthropicClient.fetchModels();
|
||||||
|
this.updateCache(response.data);
|
||||||
|
return this.formatModels(response.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to refresh models from API:', error);
|
||||||
|
new Notice('Fetching current models failed. Using hardcoded fallback list.');
|
||||||
|
return this.getFallbackModels();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load cache from plugin data
|
||||||
|
*/
|
||||||
|
loadCache(cache: ModelCache | null): void {
|
||||||
|
this.modelCache = cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current cache for saving to plugin data
|
||||||
|
*/
|
||||||
|
getCache(): ModelCache | null {
|
||||||
|
return this.modelCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the cache (for testing or manual refresh)
|
||||||
|
*/
|
||||||
|
clearCache(): void {
|
||||||
|
this.modelCache = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the current cache is still valid (within TTL)
|
||||||
|
*/
|
||||||
|
private isCacheValid(): boolean {
|
||||||
|
if (!this.modelCache) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const age = now - this.modelCache.fetchedAt;
|
||||||
|
return age < this.CACHE_TTL_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update cache with new model data
|
||||||
|
*/
|
||||||
|
private updateCache(models: ModelInfo[]): void {
|
||||||
|
this.modelCache = {
|
||||||
|
models,
|
||||||
|
fetchedAt: Date.now()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format ModelInfo array to ModelOption array for dropdown
|
||||||
|
* Uses display_name if available, otherwise falls back to id
|
||||||
|
*/
|
||||||
|
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||||
|
return models.map(model => ({
|
||||||
|
id: model.id,
|
||||||
|
displayName: model.display_name || model.id
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get fallback models from hardcoded list
|
||||||
|
*/
|
||||||
|
private getFallbackModels(): ModelOption[] {
|
||||||
|
return ANTHROPIC_MODELS.map(id => ({
|
||||||
|
id,
|
||||||
|
displayName: id
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
+79
-7
@@ -1,9 +1,10 @@
|
|||||||
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin
|
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin
|
||||||
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization
|
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization
|
||||||
|
|
||||||
import { App, ButtonComponent, Notice, PluginSettingTab, Setting } from 'obsidian';
|
import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, Setting } from 'obsidian';
|
||||||
import FreewritingCleanupPlugin from './main';
|
import FreewritingCleanupPlugin from './main';
|
||||||
import { FreewritingCleanupSettings, ANTHROPIC_MODELS, AnthropicModel, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
||||||
|
import { ModelOption } from './services/modelService';
|
||||||
|
|
||||||
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
@@ -16,18 +17,23 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
|||||||
|
|
||||||
|
⚠️ Potential issue | 🔴 Critical Do not make display() async; Obsidian expects display(): void. PluginSettingTab.display is typed as void. Overriding with Promise can break type compatibility and Obsidian won’t await it. Load models asynchronously without changing the signature. Apply:
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🔴 Critical_
**Do not make display() async; Obsidian expects display(): void.**
PluginSettingTab.display is typed as void. Overriding with Promise<void> can break type compatibility and Obsidian won’t await it. Load models asynchronously without changing the signature.
Apply:
```diff
- async display(): Promise<void> {
+ display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
- // Load models asynchronously
- await this.loadModels();
+ // Begin async model load; UI will update when done
+ void this.loadModels().then(async () => {
+ if (this.modelDropdown) {
+ this.populateModelDropdown(this.modelDropdown);
+ const current = this.plugin.settings.model;
+ const exists = this.availableModels.some(m => m.id === current);
+ const fallback = this.availableModels[0]?.id;
+ if (!exists && fallback) {
+ this.modelDropdown.setValue(fallback);
+ this.plugin.settings.model = fallback;
+ await this.plugin.saveSettings();
+ }
+ }
+ });
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In settings.ts around lines 28 to 36, do not change display() to async; keep the
signature display(): void and remove the Promise return. Call this.loadModels()
without awaiting it (e.g., this.loadModels().then(() => { /* update UI if needed
*/ }).catch(err => { console.error(err); })), or start it in the background and
update the UI when it resolves. Ensure any UI updates that depend on models run
inside the then() callback (or use an internal async helper invoked but not
awaited) and surface load errors via console/logging instead of making the
display method async.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits eae4852 to f8427e7
|
|||||||
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||||
plugin: FreewritingCleanupPlugin;
|
plugin: FreewritingCleanupPlugin;
|
||||||
|
private modelDropdown: DropdownComponent | null = null;
|
||||||
|
private availableModels: ModelOption[] = [];
|
||||||
|
|
||||||
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
||||||
super(app, plugin);
|
super(app, plugin);
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
display(): void {
|
async display(): Promise<void> {
|
||||||
const { containerEl } = this;
|
const { containerEl } = this;
|
||||||
containerEl.empty();
|
containerEl.empty();
|
||||||
|
|
||||||
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
|
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
|
||||||
|
|
||||||
|
// Load models asynchronously
|
||||||
|
await this.loadModels();
|
||||||
|
|
||||||
// MARK: - API Configuration
|
// MARK: - API Configuration
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'API Configuration' });
|
containerEl.createEl('h3', { text: 'API Configuration' });
|
||||||
@@ -42,6 +48,11 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
this.plugin.settings.apiKey = value;
|
this.plugin.settings.apiKey = value;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
this.plugin.cleanupService.updateApiKey(value);
|
this.plugin.cleanupService.updateApiKey(value);
|
||||||
|
|
||||||
|
// Trigger model refresh when API key is entered
|
||||||
|
if (value.trim().length > 0) {
|
||||||
|
await this.refreshModels();
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
// Make it a password field
|
// Make it a password field
|
||||||
@@ -61,13 +72,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
.setName('Claude Model')
|
.setName('Claude Model')
|
||||||
.setDesc('Which Claude model to use for text cleanup')
|
.setDesc('Which Claude model to use for text cleanup')
|
||||||
.addDropdown(dropdown => {
|
.addDropdown(dropdown => {
|
||||||
ANTHROPIC_MODELS.forEach(model => {
|
this.modelDropdown = dropdown;
|
||||||
dropdown.addOption(model, model);
|
this.populateModelDropdown(dropdown);
|
||||||
});
|
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(this.plugin.settings.model)
|
.setValue(this.plugin.settings.model)
|
||||||
.onChange(async (value) => {
|
.onChange(async (value) => {
|
||||||
this.plugin.settings.model = value as AnthropicModel;
|
this.plugin.settings.model = value;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -191,6 +201,68 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
}));
|
}));
|
||||||
|
⚠️ Potential issue | 🔴 Critical Persist a valid selection when the current model disappears. If the user’s saved model isn’t in the refreshed list, settings.model remains stale and later API calls may fail. Pick the first available option and save. 🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🔴 Critical_
**Persist a valid selection when the current model disappears.**
If the user’s saved model isn’t in the refreshed list, settings.model remains stale and later API calls may fail. Pick the first available option and save.
```diff
- if (modelExists) {
- this.modelDropdown.setValue(currentModel);
- }
+ if (modelExists) {
+ this.modelDropdown.setValue(currentModel);
+ } else {
+ const fallback = this.availableModels[0]?.id;
+ if (fallback) {
+ this.modelDropdown.setValue(fallback);
+ this.plugin.settings.model = fallback;
+ await this.plugin.saveSettings();
+ }
+ }
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In settings.ts around lines 250 to 256, if the saved model is no longer in
availableModels you must replace the stale this.plugin.settings.model with a
valid choice: set this.plugin.settings.model = this.availableModels[0].id (or
the first available model's id), call this.modelDropdown.setValue(...) with that
id, and persist the change by invoking the repository's save method (e.g., await
this.plugin.saveSettings() or the existing saveSettings helper) so the new
selection is stored.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits eae4852 to f8427e7
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Model Loading
|
||||||
|
|
||||||
|
private async loadModels(): Promise<void> {
|
||||||
|
try {
|
||||||
|
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading models:', error);
|
||||||
|
// Error already shown by ModelService via Notice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private populateModelDropdown(dropdown: DropdownComponent): void {
|
||||||
|
if (this.availableModels.length === 0) {
|
||||||
|
// No models available yet, disable dropdown
|
||||||
|
dropdown.addOption('', 'Loading models...');
|
||||||
|
dropdown.setDisabled(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear existing options
|
||||||
|
dropdown.selectEl.empty();
|
||||||
|
|
||||||
|
// Add all available models
|
||||||
|
this.availableModels.forEach(model => {
|
||||||
|
dropdown.addOption(model.id, model.displayName);
|
||||||
|
});
|
||||||
|
|
||||||
|
dropdown.setDisabled(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async refreshModels(): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Disable dropdown during refresh
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.modelDropdown.setDisabled(true);
|
||||||
|
this.modelDropdown.selectEl.empty();
|
||||||
|
this.modelDropdown.addOption('', 'Refreshing models...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch new models
|
||||||
|
this.availableModels = await this.plugin.modelService.refreshModels();
|
||||||
|
|
||||||
|
// Update dropdown
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.populateModelDropdown(this.modelDropdown);
|
||||||
|
|
||||||
|
// Restore selected model if it still exists
|
||||||
|
const currentModel = this.plugin.settings.model;
|
||||||
|
const modelExists = this.availableModels.some(m => m.id === currentModel);
|
||||||
|
if (modelExists) {
|
||||||
|
this.modelDropdown.setValue(currentModel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save updated cache
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error refreshing models:', error);
|
||||||
|
// Error already shown by ModelService via Notice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
private async testApiKey(button: ButtonComponent): Promise<void> {
|
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||||
|
|||||||
@@ -3,13 +3,17 @@
|
|||||||
|
|
||||||
export interface FreewritingCleanupSettings {
|
export interface FreewritingCleanupSettings {
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
model: AnthropicModel;
|
model: string; // Changed from AnthropicModel to string to support dynamic models
|
||||||
cleanupPrompt: string;
|
cleanupPrompt: string;
|
||||||
enableCommentary: boolean;
|
enableCommentary: boolean;
|
||||||
commentaryStyle: CommentaryStyle;
|
commentaryStyle: CommentaryStyle;
|
||||||
customCommentaryPrompt: string;
|
customCommentaryPrompt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface FreewritingCleanupData extends FreewritingCleanupSettings {
|
||||||
|
modelCache?: ModelCache;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AnthropicMessage {
|
export interface AnthropicMessage {
|
||||||
role: 'user' | 'assistant' | 'system';
|
role: 'user' | 'assistant' | 'system';
|
||||||
content: Array<{
|
content: Array<{
|
||||||
@@ -57,6 +61,25 @@ export interface CleanupResult {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ModelInfo {
|
||||||
|
id: string;
|
||||||
|
display_name?: string;
|
||||||
|
created_at: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModelsListResponse {
|
||||||
|
data: ModelInfo[];
|
||||||
|
first_id: string;
|
||||||
|
has_more: boolean;
|
||||||
|
last_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModelCache {
|
||||||
|
models: ModelInfo[];
|
||||||
|
fetchedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
export const ANTHROPIC_MODELS = [
|
export const ANTHROPIC_MODELS = [
|
||||||
'claude-opus-4-1-20250805',
|
'claude-opus-4-1-20250805',
|
||||||
'claude-opus-4-20250514',
|
'claude-opus-4-20250514',
|
||||||
|
|||||||
Reference in new issue
Block a user
🛠️ Refactor suggestion | 🟠 Major
Early fallback when API key missing; also cache the fallback to reduce repeated Notices.
Skip network calls if no API key, and write fallback into cache with fetchedAt so subsequent calls don’t spam.
Note: If you prefer not to synthesize ModelInfo for fallback, adjust cache type to accept ModelOption or store a flag.
🤖 Prompt for AI Agents
✅ Addressed in commits
eae4852tof8427e7