From 7b23ed6615a2847422d240abff35f054e3813a40 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 23 Oct 2025 10:25:22 +0200 Subject: [PATCH 01/10] feat: add dynamic model fetching from Anthropic API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace hardcoded model list with dynamic API-based model fetching that queries the Anthropic models endpoint. Implements 24-hour caching with automatic fallback to hardcoded models if API is unavailable. Changes: - Add ModelService to fetch and cache available models from API - Implement 24-hour TTL cache persisted in plugin data - Update AnthropicClient with fetchModels() method - Modify settings UI to load models asynchronously with loading states - Auto-refresh models when API key is entered or changed - Display model names using display_name field from API - Preserve user's selected model across updates and restarts - Show notice when falling back to hardcoded model list - Change model type from strict enum to string for dynamic support Technical details: - New ModelInfo and ModelsListResponse interfaces for API response - ModelCache interface with timestamp for TTL validation - FreewritingCleanupData extends settings to include cache - Settings dropdown disabled during model fetch/refresh - Fallback to ANTHROPIC_MODELS constant on API failure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- api/anthropicClient.ts | 39 +++++++++-- main.ts | 18 +++++- services/cleanupService.ts | 19 ++++-- services/modelService.ts | 129 +++++++++++++++++++++++++++++++++++++ settings.ts | 86 +++++++++++++++++++++++-- types.ts | 25 ++++++- 6 files changed, 294 insertions(+), 22 deletions(-) create mode 100644 services/modelService.ts diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index cebf5a9..57ff09c 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -2,11 +2,12 @@ // ABOUTME: Handles API requests, error handling, retry logic, and response parsing 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 { 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 RETRY_DELAY_BASE = 1000; // 1 second base delay @@ -18,7 +19,7 @@ export class AnthropicClient { async cleanupText( text: string, - model: AnthropicModel, + model: string, cleanupPrompt: string, enableCommentary = false, commentaryStyle: CommentaryStyle = 'constructive', @@ -77,7 +78,7 @@ You MUST use exactly these markers. Do not deviate from this format.`; return this.parseStructuredResponse(response, enableCommentary); } - async testConnection(model: AnthropicModel): Promise<{ + async testConnection(model: string): Promise<{ success: boolean; message: string; details?: { @@ -174,10 +175,38 @@ You MUST use exactly these markers. Do not deviate from this format.`; return { cleanedText, commentary }; } + async fetchModels(): Promise { + 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 { try { const response = await requestUrl({ - url: this.baseUrl, + url: this.messagesUrl, method: 'POST', headers: { 'Content-Type': 'application/json', diff --git a/main.ts b/main.ts index 72f1d69..a0b0bcc 100644 --- a/main.ts +++ b/main.ts @@ -2,14 +2,16 @@ // ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle import { Editor, MarkdownView, Plugin } from 'obsidian'; -import { FreewritingCleanupSettings } from './types'; +import { FreewritingCleanupSettings, FreewritingCleanupData } from './types'; import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings'; import { CleanupService } from './services/cleanupService'; +import { ModelService } from './services/modelService'; import { CleanupCommand } from './commands/cleanupCommand'; export default class FreewritingCleanupPlugin extends Plugin { settings: FreewritingCleanupSettings; cleanupService: CleanupService; + modelService: ModelService; cleanupCommand: CleanupCommand; async onload() { @@ -17,8 +19,15 @@ export default class FreewritingCleanupPlugin extends Plugin { // Initialize services this.cleanupService = new CleanupService(this.settings.apiKey); + this.modelService = new ModelService(this.cleanupService.anthropicClient); 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 this.registerCommand(); @@ -37,7 +46,12 @@ export default class FreewritingCleanupPlugin extends Plugin { } 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 if (this.cleanupService) { diff --git a/services/cleanupService.ts b/services/cleanupService.ts index f569170..7be0734 100644 --- a/services/cleanupService.ts +++ b/services/cleanupService.ts @@ -6,10 +6,15 @@ import { AnthropicClient } from '../api/anthropicClient'; import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types'; export class CleanupService { - private anthropicClient: AnthropicClient; + private client: AnthropicClient; + + // Expose client for ModelService + get anthropicClient(): AnthropicClient { + return this.client; + } constructor(apiKey: string) { - this.anthropicClient = new AnthropicClient(apiKey); + this.client = new AnthropicClient(apiKey); } // MARK: - Public Methods @@ -20,7 +25,7 @@ export class CleanupService { 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.'); } @@ -32,7 +37,7 @@ export class CleanupService { const startTime = Date.now(); try { - const { cleanedText, commentary } = await this.anthropicClient.cleanupText( + const { cleanedText, commentary } = await this.client.cleanupText( text, settings.model, settings.cleanupPrompt, @@ -74,7 +79,7 @@ export class CleanupService { outputTokens?: number; }; }> { - if (!this.anthropicClient.validateApiKey()) { + if (!this.client.validateApiKey()) { return { success: false, message: 'API key is not configured' @@ -82,7 +87,7 @@ export class CleanupService { } try { - const result = await this.anthropicClient.testConnection(settings.model); + const result = await this.client.testConnection(settings.model); return result; } catch (error) { return { @@ -105,7 +110,7 @@ export class CleanupService { // MARK: - Configuration Methods updateApiKey(apiKey: string): void { - this.anthropicClient.updateApiKey(apiKey); + this.client.updateApiKey(apiKey); } validateSettings(settings: FreewritingCleanupSettings): { diff --git a/services/modelService.ts b/services/modelService.ts new file mode 100644 index 0000000..44ebf63 --- /dev/null +++ b/services/modelService.ts @@ -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 { + // 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 { + 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 + })); + } +} diff --git a/settings.ts b/settings.ts index c449d85..21b5336 100644 --- a/settings.ts +++ b/settings.ts @@ -1,9 +1,10 @@ // ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin // 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 { 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 = { apiKey: '', @@ -16,18 +17,23 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = { export class FreewritingCleanupSettingTab extends PluginSettingTab { plugin: FreewritingCleanupPlugin; + private modelDropdown: DropdownComponent | null = null; + private availableModels: ModelOption[] = []; constructor(app: App, plugin: FreewritingCleanupPlugin) { super(app, plugin); this.plugin = plugin; } - display(): void { + async display(): Promise { const { containerEl } = this; containerEl.empty(); containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' }); + // Load models asynchronously + await this.loadModels(); + // MARK: - API Configuration containerEl.createEl('h3', { text: 'API Configuration' }); @@ -42,6 +48,11 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); this.plugin.cleanupService.updateApiKey(value); + + // Trigger model refresh when API key is entered + if (value.trim().length > 0) { + await this.refreshModels(); + } })) .then(setting => { // Make it a password field @@ -61,13 +72,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { .setName('Claude Model') .setDesc('Which Claude model to use for text cleanup') .addDropdown(dropdown => { - ANTHROPIC_MODELS.forEach(model => { - dropdown.addOption(model, model); - }); + this.modelDropdown = dropdown; + this.populateModelDropdown(dropdown); dropdown .setValue(this.plugin.settings.model) .onChange(async (value) => { - this.plugin.settings.model = value as AnthropicModel; + this.plugin.settings.model = value; await this.plugin.saveSettings(); }); }); @@ -191,6 +201,68 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { })); } + // MARK: - Model Loading + + private async loadModels(): Promise { + 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 { + 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 private async testApiKey(button: ButtonComponent): Promise { diff --git a/types.ts b/types.ts index fccce8c..1668210 100644 --- a/types.ts +++ b/types.ts @@ -3,13 +3,17 @@ export interface FreewritingCleanupSettings { apiKey: string; - model: AnthropicModel; + model: string; // Changed from AnthropicModel to string to support dynamic models cleanupPrompt: string; enableCommentary: boolean; commentaryStyle: CommentaryStyle; customCommentaryPrompt: string; } +export interface FreewritingCleanupData extends FreewritingCleanupSettings { + modelCache?: ModelCache; +} + export interface AnthropicMessage { role: 'user' | 'assistant' | 'system'; 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 = [ 'claude-opus-4-1-20250805', 'claude-opus-4-20250514', -- 2.36.6 From eae48521c5ee38fa6c8b49bfefe2a3702023287b Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 10:44:53 +0200 Subject: [PATCH 02/10] Refactors confirmation modal with Obsidian integration Replaces custom modal implementation with Obsidian's Modal class for improved consistency and accessibility Enhances API key management with dynamic model refreshing and fallback handling Improves event handling and modal interaction patterns --- settings.ts | 65 ++++++++++++++++++++++++++--------------------------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/settings.ts b/settings.ts index 21b5336..a316379 100644 --- a/settings.ts +++ b/settings.ts @@ -1,7 +1,7 @@ // ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin // ABOUTME: Handles user configuration including API key, model selection, and prompt customization -import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, Setting } from 'obsidian'; +import { App, ButtonComponent, DropdownComponent, Modal, Notice, PluginSettingTab, Setting } from 'obsidian'; import FreewritingCleanupPlugin from './main'; import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types'; import { ModelOption } from './services/modelService'; @@ -49,9 +49,14 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { await this.plugin.saveSettings(); this.plugin.cleanupService.updateApiKey(value); - // Trigger model refresh when API key is entered - if (value.trim().length > 0) { + // Refresh when key is entered; revert to fallback when cleared + const hasKey = value.trim().length > 0; + if (hasKey) { await this.refreshModels(); + } else if (this.modelDropdown) { + // Show fallback immediately when key is cleared + this.availableModels = await this.plugin.modelService.getAvailableModels(); + this.populateModelDropdown(this.modelDropdown); } })) .then(setting => { @@ -320,53 +325,47 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { } } -// Simple confirmation modal -class ConfirmModal { - private app: App; +// Confirmation modal using Obsidian's Modal class for consistent styling and accessibility +class ConfirmModal extends Modal { private title: string; private message: string; private callback: (result: boolean) => void; - private modalEl: HTMLElement | null = null; constructor(app: App, title: string, message: string, callback: (result: boolean) => void) { - this.app = app; + super(app); this.title = title; this.message = message; this.callback = callback; } - open(): void { - // Create modal backdrop - this.modalEl = document.createElement('div'); - this.modalEl.className = 'modal-container mod-dim'; + onOpen(): void { + const { contentEl } = this; - // Create modal content - const modal = this.modalEl.createDiv('modal'); - const header = modal.createDiv('modal-header'); - header.createEl('h3', { text: this.title }); + contentEl.createEl('h2', { text: this.title }); + contentEl.createEl('p', { text: this.message }); - const content = modal.createDiv('modal-content'); - content.createEl('p', { text: this.message }); + const buttonContainer = contentEl.createDiv({ cls: 'modal-button-container' }); - const buttons = modal.createDiv('modal-button-container'); + const cancelButton = buttonContainer.createEl('button', { text: 'Cancel' }); + cancelButton.addEventListener('click', () => { + this.close(); + this.callback(false); + }); - const cancelButton = buttons.createEl('button', { text: 'Cancel' }); - cancelButton.onclick = () => this.close(false); + const confirmButton = buttonContainer.createEl('button', { + text: 'Confirm', + cls: 'mod-warning' + }); + confirmButton.addEventListener('click', () => { + this.close(); + this.callback(true); + }); - const confirmButton = buttons.createEl('button', { text: 'Confirm', cls: 'mod-warning' }); - confirmButton.onclick = () => this.close(true); - - if (this.modalEl) { - document.body.appendChild(this.modalEl); - } confirmButton.focus(); } - private close(result: boolean): void { - if (this.modalEl && this.modalEl.parentNode) { - this.modalEl.parentNode.removeChild(this.modalEl); - } - this.modalEl = null; - this.callback(result); + onClose(): void { + const { contentEl } = this; + contentEl.empty(); } } \ No newline at end of file -- 2.36.6 From b63ab214b31fcb406ebd129095ac30246b5bf242 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 10:53:54 +0200 Subject: [PATCH 03/10] Refactors Anthropic model type and list handling Removes strict type definition for Anthropic models to enable more dynamic model selection Allows for flexible model ID fetching from Anthropic API Provides a fallback list of models when direct API access is limited Supports more adaptable model configuration in the application --- CLAUDE.md | 2 +- types.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a8ae80b..3c4c8d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,7 @@ Settings use the `FreewritingCleanupSettings` interface with modular defaults: ```typescript interface FreewritingCleanupSettings { apiKey: string; - model: AnthropicModel; + model: string; // Dynamic model ID fetched from Anthropic API cleanupPrompt: string; enableCommentary: boolean; commentaryStyle: CommentaryStyle; diff --git a/types.ts b/types.ts index 1668210..87b6584 100644 --- a/types.ts +++ b/types.ts @@ -80,16 +80,15 @@ export interface ModelCache { fetchedAt: number; } -export const ANTHROPIC_MODELS = [ +// Fallback model list used when API key is not set or API fetch fails +export const ANTHROPIC_MODELS: readonly string[] = [ 'claude-opus-4-1-20250805', 'claude-opus-4-20250514', 'claude-sonnet-4-20250514', 'claude-3-7-sonnet-latest', 'claude-3-5-haiku-latest', 'claude-3-haiku-20240307' -] as const; - -export type AnthropicModel = typeof ANTHROPIC_MODELS[number]; +]; // Commentary style options export const COMMENTARY_STYLES = [ -- 2.36.6 From 4db56391601bc1d1ccb0425d0b0ce54b8c431675 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 10:55:54 +0200 Subject: [PATCH 04/10] Adds token usage tracking for text cleanup requests Enhances Anthropic API client to return token usage information Modifies cleanup service to capture and store input and output token counts from API responses Refactors request and response handling to extract and pass usage metrics Provides more detailed tracking of API request resource consumption --- api/anthropicClient.ts | 14 ++++++++++---- services/cleanupService.ts | 6 +++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 57ff09c..c0cc232 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -24,7 +24,7 @@ export class AnthropicClient { enableCommentary = false, commentaryStyle: CommentaryStyle = 'constructive', customCommentaryPrompt?: string - ): Promise<{ cleanedText: string; commentary?: string }> { + ): Promise<{ cleanedText: string; commentary?: string; usage?: { input_tokens: number; output_tokens: number } }> { if (!this.apiKey) { throw new Error('API key is required'); } @@ -75,7 +75,13 @@ You MUST use exactly these markers. Do not deviate from this format.`; }; const response = await this.makeRequestWithRetry(request); - return this.parseStructuredResponse(response, enableCommentary); + const responseText = this.extractTextFromResponse(response); + const parsed = this.parseStructuredResponse(responseText, enableCommentary); + + return { + ...parsed, + usage: response.usage + }; } async testConnection(model: string): Promise<{ @@ -130,13 +136,13 @@ You MUST use exactly these markers. Do not deviate from this format.`; // MARK: - Private Methods - private async makeRequestWithRetry(request: AnthropicRequest): Promise { + private async makeRequestWithRetry(request: AnthropicRequest): Promise { let lastError: Error = new Error('No attempts made'); for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) { try { const response = await this.makeRequest(request); - return this.extractTextFromResponse(response); + return response; } catch (error) { lastError = error instanceof Error ? error : new Error('Unknown error'); diff --git a/services/cleanupService.ts b/services/cleanupService.ts index 7be0734..f6c8dc3 100644 --- a/services/cleanupService.ts +++ b/services/cleanupService.ts @@ -37,7 +37,7 @@ export class CleanupService { const startTime = Date.now(); try { - const { cleanedText, commentary } = await this.client.cleanupText( + const { cleanedText, commentary, usage } = await this.client.cleanupText( text, settings.model, settings.cleanupPrompt, @@ -53,8 +53,8 @@ export class CleanupService { timestamp: new Date(), model: settings.model, tokensUsed: { - input: 0, // We don't have access to this from the response - output: 0 // We don't have access to this from the response + input: usage?.input_tokens ?? 0, + output: usage?.output_tokens ?? 0 } }; -- 2.36.6 From c3d4888c986c8180434345f32eb23c8a1cafe917 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 10:57:47 +0200 Subject: [PATCH 05/10] Optimizes settings and model cache loading Refactors loadSettings method to avoid redundant data loading Reduces duplicate loadData() calls by reusing loaded data Improves efficiency of plugin initialization process --- main.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/main.ts b/main.ts index a0b0bcc..46d41dc 100644 --- a/main.ts +++ b/main.ts @@ -15,15 +15,15 @@ export default class FreewritingCleanupPlugin extends Plugin { cleanupCommand: CleanupCommand; async onload() { - await this.loadSettings(); + // Load settings and reuse the data to avoid double loadData() call + const data = await this.loadSettings(); // Initialize services this.cleanupService = new CleanupService(this.settings.apiKey); this.modelService = new ModelService(this.cleanupService.anthropicClient); this.cleanupCommand = new CleanupCommand(this.cleanupService); - // Load model cache - const data = await this.loadData() as FreewritingCleanupData | null; + // Load model cache from already-loaded data if (data?.modelCache) { this.modelService.loadCache(data.modelCache); } @@ -41,8 +41,10 @@ export default class FreewritingCleanupPlugin extends Plugin { // MARK: - Settings Management - async loadSettings() { - this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + async loadSettings(): Promise { + const data = await this.loadData() as FreewritingCleanupData | null; + this.settings = Object.assign({}, DEFAULT_SETTINGS, data); + return data; } async saveSettings() { -- 2.36.6 From fcc495aa8fc417a79923d7d479069d0e6c09283d Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:00:42 +0200 Subject: [PATCH 06/10] 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 --- services/modelService.ts | 42 +++++++++++++++++++++++++++++++++++----- settings.ts | 2 +- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 44ebf63..6329102 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -49,6 +49,19 @@ export class ModelService { * Used when user changes API key */ async refreshModels(): Promise { + // 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)); } /** diff --git a/settings.ts b/settings.ts index a316379..c250018 100644 --- a/settings.ts +++ b/settings.ts @@ -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); } })) -- 2.36.6 From 3d1227dc45124a22f8d7d206752430791fa5bff6 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:03:30 +0200 Subject: [PATCH 07/10] Improves model fallback and caching strategy Adds API key validation before fetching models Ensures consistent fallback model caching on API errors or missing key Reduces redundant code by centralizing fallback model caching logic Relates to dynamic-models branch --- services/modelService.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 6329102..579def9 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -24,7 +24,7 @@ export class ModelService { /** * 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 + * Falls back to hardcoded list if API fails or API key is missing */ async getAvailableModels(): Promise { // Check if we have a valid cache @@ -32,6 +32,19 @@ export class ModelService { return this.formatModels(this.modelCache.models); } + // If no API key, immediately return and cache fallback (no Notice needed) + 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 to fetch from API try { const response = await this.anthropicClient.fetchModels(); @@ -40,7 +53,15 @@ export class ModelService { } catch (error) { console.error('Failed to fetch 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; } } -- 2.36.6 From 5c8314a986687c5012a28a0412eb2636d2c0e577 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:04:35 +0200 Subject: [PATCH 08/10] Enhances model loading in settings display Modifies display method to load models asynchronously in the background Improves user experience by: - Removing async modifier from display method - Handling model loading as a background task - Adding error handling for model loading - Preparing to update UI dynamically when models are loaded --- settings.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/settings.ts b/settings.ts index c250018..253ad7a 100644 --- a/settings.ts +++ b/settings.ts @@ -25,14 +25,23 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { this.plugin = plugin; } - async display(): Promise { + display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' }); - // Load models asynchronously - await this.loadModels(); + // Load models asynchronously in the background + this.loadModels() + .then(() => { + // Update dropdown UI when models are loaded + if (this.modelDropdown) { + this.populateModelDropdown(this.modelDropdown); + } + }) + .catch((error) => { + console.error('Error loading models in background:', error); + }); // MARK: - API Configuration -- 2.36.6 From de98d4a52d88665d4043f1007a6df4cfbd8f7a06 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:05:45 +0200 Subject: [PATCH 09/10] Handles model changes when current model unavailable Improves model selection logic to automatically switch to the first available model when the current model is no longer valid Adds fallback mechanism to prevent potential configuration errors Logs model switching for debugging and transparency --- settings.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/settings.ts b/settings.ts index 253ad7a..d26090d 100644 --- a/settings.ts +++ b/settings.ts @@ -261,15 +261,22 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { if (this.modelDropdown) { this.populateModelDropdown(this.modelDropdown); - // Restore selected model if it still exists + // Restore selected model if it still exists, otherwise use first available const currentModel = this.plugin.settings.model; const modelExists = this.availableModels.some(m => m.id === currentModel); + if (modelExists) { this.modelDropdown.setValue(currentModel); + } else if (this.availableModels.length > 0) { + // Model no longer available - update to first available model + const newModel = this.availableModels[0].id; + this.plugin.settings.model = newModel; + this.modelDropdown.setValue(newModel); + console.log(`Model '${currentModel}' no longer available, switched to '${newModel}'`); } } - // Save updated cache + // Save updated cache and any model changes await this.plugin.saveSettings(); } catch (error) { console.error('Error refreshing models:', error); -- 2.36.6 From f8427e72a0ab1fd5edfa8f0964559167036ac74f Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:06:48 +0200 Subject: [PATCH 10/10] Enforces display name for model selection Removes fallback to model ID for display names Ensures consistent and user-friendly model representation Improves model dropdown experience by requiring display names from API --- services/modelService.ts | 4 ++-- types.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 579def9..0bfbeea 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -158,14 +158,14 @@ export class ModelService { /** * Format ModelInfo array to ModelOption array for dropdown - * Uses display_name if available, otherwise falls back to id + * Uses display_name from API for user-friendly model names * 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 + displayName: model.display_name })) .sort((a, b) => a.displayName.localeCompare(b.displayName)); } diff --git a/types.ts b/types.ts index 87b6584..b13e426 100644 --- a/types.ts +++ b/types.ts @@ -63,7 +63,7 @@ export interface CleanupResult { export interface ModelInfo { id: string; - display_name?: string; + display_name: string; created_at: string; type: string; } -- 2.36.6