feat: add dynamic model fetching from Anthropic API #2

Merged
AlexKucera merged 10 commits from dynamic-models into master 2025-10-24 11:14:13 +02:00
7 changed files with 412 additions and 65 deletions

No files matched your search

+1 -1
View File
@@ -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;
+44 -9
View File
@@ -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,12 +19,12 @@ export class AnthropicClient {
async cleanupText(
text: string,
model: AnthropicModel,
model: string,
cleanupPrompt: string,
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');
}
@@ -74,10 +75,16 @@ 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: AnthropicModel): Promise<{
async testConnection(model: string): Promise<{
success: boolean;
message: string;
details?: {
@@ -129,13 +136,13 @@ You MUST use exactly these markers. Do not deviate from this format.`;
// MARK: - Private Methods
private async makeRequestWithRetry(request: AnthropicRequest): Promise<string> {
private async makeRequestWithRetry(request: AnthropicRequest): Promise<AnthropicResponse> {
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');
@@ -174,10 +181,38 @@ You MUST use exactly these markers. Do not deviate from this format.`;
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> {
try {
const response = await requestUrl({
url: this.baseUrl,
url: this.messagesUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json',
+21 -5
View File
@@ -2,23 +2,32 @@
// 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() {
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 from already-loaded data
if (data?.modelCache) {
this.modelService.loadCache(data.modelCache);
}
// Register command
this.registerCommand();
@@ -32,12 +41,19 @@ export default class FreewritingCleanupPlugin extends Plugin {
// MARK: - Settings Management
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
async loadSettings(): Promise<FreewritingCleanupData | null> {
const data = await this.loadData() as FreewritingCleanupData | null;
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
return data;
}
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) {
+14 -9
View File
@@ -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, usage } = await this.client.cleanupText(
text,
settings.model,
settings.cleanupPrompt,
@@ -48,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
}
};
@@ -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): {
+182
View File
@@ -0,0 +1,182 @@
// ABOUTME: Service for managing Claude model list from Anthropic API
coderabbitai[bot] commented 2025-10-23 15:09:45 +02:00 (Migrated from github.com)
Review

🛠️ 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.

-    async getAvailableModels(): Promise<ModelOption[]> {
+    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 to fetch from API (bail early without key)
         try {
+            if (!this.anthropicClient.validateApiKey?.()) {
+                const fallback = this.getFallbackModels();
+                // write fallback into cache to honor TTL
+                this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+                return fallback;
+            }
             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();
+            const fallback = this.getFallbackModels();
+            this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+            return fallback;
         }
     }

Note: If you prefer not to synthesize ModelInfo for fallback, adjust cache type to accept ModelOption or store a flag.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In services/modelService.ts around lines 29 to 45, the method currently attempts
an API fetch even when the API key may be missing and returns a hardcoded
fallback without caching it; modify getAvailableModels to first detect a
missing/empty API key and immediately return the fallback while also writing
that fallback into the existing cache (include a fetchedAt timestamp) so
subsequent calls use the cache and don’t repeatedly show Notices; if your cache
expects ModelInfo instead of ModelOption, either synthesize minimal ModelInfo
fields for the fallback or relax the cache type to accept ModelOption/union
before writing the fallback into cache.

✅ Addressed in commits eae4852 to f8427e7

_🛠️ 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. ```diff - async getAvailableModels(): Promise<ModelOption[]> { + 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 to fetch from API (bail early without key) try { + if (!this.anthropicClient.validateApiKey?.()) { + const fallback = this.getFallbackModels(); + // write fallback into cache to honor TTL + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; + } 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(); + const fallback = this.getFallbackModels(); + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; } } ``` Note: If you prefer not to synthesize ModelInfo for fallback, adjust cache type to accept ModelOption or store a flag. > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In services/modelService.ts around lines 29 to 45, the method currently attempts an API fetch even when the API key may be missing and returns a hardcoded fallback without caching it; modify getAvailableModels to first detect a missing/empty API key and immediately return the fallback while also writing that fallback into the existing cache (include a fetchedAt timestamp) so subsequent calls use the cache and don’t repeatedly show Notices; if your cache expects ModelInfo instead of ModelOption, either synthesize minimal ModelInfo fields for the fallback or relax the cache type to accept ModelOption/union before writing the fallback into cache. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits eae4852 to f8427e7
// 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 or API key is missing
*/
async getAvailableModels(): Promise<ModelOption[]> {
// Check if we have a valid cache
if (this.isCacheValid() && this.modelCache) {
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();
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.');
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;
}
}
/**
* Force refresh the model list from API
* 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);
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.');
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;
}
}
/**
* 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;
}
/**
* Get fallback model options (public API for UI components)
* Returns hardcoded model list as ModelOption array
*/
getFallbackOptions(): ModelOption[] {
return this.getFallbackModels();
}
// 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 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
}))
.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
/**
* Get fallback models from hardcoded list
*/
private getFallbackModels(): ModelOption[] {
return ANTHROPIC_MODELS.map(id => ({
id,
displayName: id
}));
}
}
+123 -36
View File
@@ -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, Modal, 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,6 +17,8 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
coderabbitai[bot] commented 2025-10-23 15:09:45 +02:00 (Migrated from github.com)
Review

⚠️ 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:

-    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.

🤖 Prompt for AI Agents
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.

✅ Addressed in commits eae4852 to f8427e7

_⚠️ 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 {
plugin: FreewritingCleanupPlugin;
private modelDropdown: DropdownComponent | null = null;
private availableModels: ModelOption[] = [];
constructor(app: App, plugin: FreewritingCleanupPlugin) {
super(app, plugin);
@@ -28,6 +31,18 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
// 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
containerEl.createEl('h3', { text: 'API Configuration' });
@@ -42,6 +57,16 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
this.plugin.settings.apiKey = value;
await this.plugin.saveSettings();
this.plugin.cleanupService.updateApiKey(value);
// 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 = this.plugin.modelService.getFallbackOptions();
this.populateModelDropdown(this.modelDropdown);
}
}))
.then(setting => {
// Make it a password field
@@ -61,13 +86,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();
});
});
1
@@ -191,6 +215,75 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
}));
}
// 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, 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 and any model changes
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<void> {
@@ -248,53 +341,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();
}
}
+27 -5
View File
@@ -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,16 +61,34 @@ export interface CleanupResult {
};
}
export const ANTHROPIC_MODELS = [
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;
}
// 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 = [
1