Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8ddeaeb2d | ||
|
|
e5788910e6 | ||
|
|
4efa8a1282 | ||
|
|
c5ebfceea6 | ||
|
|
ab5e134a12 | ||
|
|
bb6cc929f5 | ||
|
|
306e6819a3 | ||
|
|
d50f11269b | ||
|
|
20c27b45ce | ||
|
|
e29539c8eb | ||
|
|
ecb57d794c | ||
|
|
5e77136370 | ||
|
|
58575c1880 | ||
|
|
e6b357f3f2 | ||
|
|
58abaf7e91 | ||
|
|
2edf2e5c28 | ||
|
|
d0666a4967 | ||
|
|
d9489a82dc | ||
|
|
bd5321b69e | ||
|
|
e43d4a0631 | ||
|
|
ee892b3231 | ||
|
|
0f3d6ec7a3 | ||
|
|
f5730ac692 | ||
|
|
f8427e72a0 | ||
|
|
de98d4a52d | ||
|
|
5c8314a986 | ||
|
|
3d1227dc45 | ||
|
|
fcc495aa8f | ||
|
|
c3d4888c98 | ||
|
|
4db5639160 | ||
|
|
b63ab214b3 | ||
|
|
eae48521c5 | ||
|
|
7b23ed6615 | ||
|
|
b119923300 | ||
|
|
13b2567672 | ||
|
|
69a92e02d2 | ||
|
|
565cddf86c | ||
|
|
fe51d1efd2 | ||
|
|
e90eef0f95 | ||
|
|
bf683b2983 | ||
|
|
733147f8a8 | ||
|
|
2783552ed0 | ||
|
|
40ee33f3a0 | ||
|
|
f5bd806733 | ||
|
|
ba2b29361a | ||
|
|
fe33bbc8c3 |
No files matched your search
@@ -108,7 +108,7 @@ jobs:
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
|
||||
+33
-2
@@ -7,7 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.0.2] - 2025-01-21
|
||||
## [1.1.0] - 2025-10-25
|
||||
|
||||
### Added
|
||||
- Dynamic model fetching from Anthropic API with automatic fallback and caching
|
||||
- Token usage tracking for text cleanup requests
|
||||
- Debounce mechanism for settings save operations
|
||||
- Error notice throttling for improved user experience
|
||||
- Validation for custom commentary style
|
||||
|
||||
### Changed
|
||||
- Improved API error handling with detailed error messages and selective retries
|
||||
- Enhanced model loading in settings with fallback strategy
|
||||
- Optimized settings and model cache loading
|
||||
- Refactored Anthropic model type and list handling
|
||||
- Enforced display name requirement for model selection
|
||||
- Updated Anthropic API limits with detailed documentation
|
||||
- Simplified text selection validation method
|
||||
- Improved plugin settings loading and command registration
|
||||
- Enhanced code documentation and structure throughout plugin
|
||||
- Refactored confirmation modal with better Obsidian integration
|
||||
|
||||
### Fixed
|
||||
- Removed duplicate error notification in cleanup service
|
||||
- Resolved potential null reference errors in settings
|
||||
- Handled model changes gracefully when current model becomes unavailable
|
||||
- Updated ModelsListResponse types to handle empty model lists
|
||||
- Corrected type definition for stop_sequence parameter
|
||||
- Improved custom commentary error message clarity
|
||||
- Removed unnecessary text selection validation check
|
||||
|
||||
## [1.0.2] - 2025-09-21
|
||||
|
||||
### Security
|
||||
- Fix innerHTML usage in settings to prevent XSS vulnerabilities
|
||||
@@ -58,7 +88,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **Settings Management**: Persistent settings with validation and testing capabilities
|
||||
- **Modular Architecture**: Clean separation of concerns across services, commands, and API layers
|
||||
|
||||
[Unreleased]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/compare/1.0.2...HEAD
|
||||
[Unreleased]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/compare/1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/compare/1.0.2...1.1.0
|
||||
[1.0.2]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/compare/1.0.1...1.0.2
|
||||
[1.0.1]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/compare/1.0.0...1.0.1
|
||||
[1.0.0]: https://github.com/alexanderkucera/obsidian-freewriting-cleanup/releases/tag/1.0.0
|
||||
@@ -48,15 +48,20 @@ Manual testing requires copying build artifacts (`main.js`, `manifest.json`, `st
|
||||
- **Production**: Minified output without sourcemaps
|
||||
|
||||
### Plugin Structure
|
||||
The plugin follows Obsidian's standard plugin architecture:
|
||||
- **Main Plugin Class**: `MyPlugin` extends `Plugin` from obsidian API
|
||||
The plugin follows a modular architecture extending Obsidian's standard plugin system:
|
||||
- **Main Plugin Class**: `FreewritingCleanupPlugin` extends `Plugin` from obsidian API
|
||||
- **Service Layer**: `CleanupService` handles AI API interactions
|
||||
- **Command Layer**: `CleanupCommand` implements text processing logic
|
||||
- **Settings System**: Interface-based settings with persistence via `loadData()`/`saveData()`
|
||||
- **Commands**: Registered via `addCommand()` with unique IDs
|
||||
- **UI Components**: Modal and settings tab classes
|
||||
- **Lifecycle Management**: Uses `registerDomEvent()`, `registerInterval()` for cleanup
|
||||
- **Type Definitions**: Centralized in `types.ts` for consistency
|
||||
- **Lifecycle Management**: Uses proper initialization and cleanup patterns
|
||||
|
||||
### Key Files
|
||||
- `main.ts`: Plugin entry point containing all core functionality
|
||||
- `main.ts`: Plugin entry point coordinating services and commands
|
||||
- `types.ts`: TypeScript interfaces for settings, API responses, and plugin configuration
|
||||
- `settings.ts`: Settings tab implementation and default configuration
|
||||
- `services/cleanupService.ts`: AI service integration and API handling
|
||||
- `commands/cleanupCommand.ts`: Command execution and text processing
|
||||
- `manifest.json`: Plugin metadata (ID, version, compatibility)
|
||||
- `package.json`: npm configuration with build scripts
|
||||
- `esbuild.config.mjs`: Build configuration
|
||||
@@ -66,33 +71,48 @@ The plugin follows Obsidian's standard plugin architecture:
|
||||
## Plugin Architecture Patterns
|
||||
|
||||
### Settings Management
|
||||
Settings are defined as TypeScript interfaces with default values and persisted automatically:
|
||||
Settings use the `FreewritingCleanupSettings` interface with modular defaults:
|
||||
```typescript
|
||||
interface MyPluginSettings {
|
||||
mySetting: string;
|
||||
interface FreewritingCleanupSettings {
|
||||
apiKey: string;
|
||||
model: string; // Dynamic model ID fetched from Anthropic API
|
||||
cleanupPrompt: string;
|
||||
enableCommentary: boolean;
|
||||
commentaryStyle: CommentaryStyle;
|
||||
customCommentaryPrompt: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: MyPluginSettings = {
|
||||
mySetting: 'default'
|
||||
const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||
apiKey: '',
|
||||
model: 'claude-3-5-haiku-latest',
|
||||
cleanupPrompt: 'I did some free writing. Please correct my jumbled typo mess...',
|
||||
enableCommentary: false,
|
||||
commentaryStyle: 'constructive',
|
||||
customCommentaryPrompt: 'Provide thoughtful feedback...'
|
||||
}
|
||||
```
|
||||
|
||||
### Command Registration
|
||||
Commands should have stable IDs and descriptive names:
|
||||
- Use `addCommand()` for simple commands
|
||||
- Use `editorCallback` for editor-specific commands
|
||||
- Use `checkCallback` for conditional commands
|
||||
Commands use dedicated command classes with service injection:
|
||||
- Main plugin registers commands via `addCommand()` with stable IDs
|
||||
- `CleanupCommand` class handles execution logic and editor interaction
|
||||
- Service dependencies injected during plugin initialization
|
||||
|
||||
### Service Architecture
|
||||
- `CleanupService` manages Anthropic API integration and connection testing
|
||||
- Service instances created during plugin load and updated when settings change
|
||||
- Clean separation between API logic and UI components
|
||||
|
||||
### UI Components
|
||||
- Modals extend `Modal` class with `onOpen()`/`onClose()` lifecycle
|
||||
- Settings tabs extend `PluginSettingTab` with `display()` method
|
||||
- Use Obsidian's `Setting` class for form controls
|
||||
- `FreewritingCleanupSettingTab` extends `PluginSettingTab` with comprehensive configuration
|
||||
- Custom confirmation modal for destructive operations
|
||||
- Dynamic UI updates based on setting states (e.g., commentary options)
|
||||
|
||||
### Resource Cleanup
|
||||
Critical for plugin stability:
|
||||
- Use `registerDomEvent()` for DOM listeners
|
||||
- Use `registerInterval()` for timers
|
||||
- Use `registerEvent()` for Obsidian app events
|
||||
Standard Obsidian plugin lifecycle with service coordination:
|
||||
- Services initialized in `onload()` with proper dependency injection
|
||||
- Settings persistence triggers service updates automatically
|
||||
- Clean separation allows for easy testing and maintenance
|
||||
|
||||
## Release Process
|
||||
1. Update `manifest.json` version (semantic versioning)
|
||||
@@ -102,7 +122,8 @@ Critical for plugin stability:
|
||||
5. Attach `manifest.json`, `main.js`, and `styles.css` as release assets
|
||||
|
||||
## Development Notes
|
||||
- This is currently the default Obsidian sample plugin template
|
||||
- All functionality is in `main.ts` - consider splitting into modules for real development
|
||||
- Plugin demonstrates ribbon icons, status bar, commands, modals, and settings
|
||||
- Plugin uses modular architecture with separate services, commands, and settings
|
||||
- Build process bundles all TypeScript modules into single `main.js` artifact
|
||||
- Service layer enables clean testing and API interaction separation
|
||||
- Settings system provides comprehensive user configuration with dynamic UI updates
|
||||
- Mobile compatibility controlled by `isDesktopOnly` flag in manifest
|
||||
@@ -1,7 +1,9 @@
|
||||
# Freewriting Cleanup
|
||||
|
||||
[](https://github.com/alexanderkucera/obsidian-freewriting-cleanup/releases)
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
[](https://github.com/AlexKucera/freewriting-cleanup/releases)
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
[](https://github.com/AlexKucera/freewriting-cleanup/releases)
|
||||
[](https://coderabbit.ai/)
|
||||

|
||||
|
||||
Transform your messy freewriting into polished prose using AI. Clean up typos, improve grammar, and format your stream-of-consciousness writing into readable paragraphs with a single command.
|
||||
@@ -73,7 +75,7 @@ Write without the ability to delete or edit - just like pen on paper. Perfect fo
|
||||
|
||||
### Method 2: Manual Installation
|
||||
|
||||
1. Go to [GitHub Releases](https://github.com/alexanderkucera/obsidian-freewriting-cleanup/releases)
|
||||
1. Go to [GitHub Releases](https://github.com/AlexKucera/freewriting-cleanup/releases)
|
||||
2. Download the latest `main.js`, `manifest.json`, and `styles.css`
|
||||
3. Create a folder `{VaultFolder}/.obsidian/plugins/freewriting-cleanup/`
|
||||
4. Place the downloaded files in this folder
|
||||
@@ -83,7 +85,7 @@ Write without the ability to delete or edit - just like pen on paper. Perfect fo
|
||||
### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
|
||||
|
||||
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
||||
2. Add this repository: `alexanderkucera/obsidian-freewriting-cleanup`
|
||||
2. Add this repository: `https://github.com/AlexKucera/freewriting-cleanup`
|
||||
3. Enable the plugin after installation
|
||||
|
||||
## Quick Start
|
||||
|
||||
+198
-25
@@ -2,34 +2,72 @@
|
||||
// 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';
|
||||
import {
|
||||
ApiKeyError,
|
||||
TextTooLongError,
|
||||
ConfigurationError,
|
||||
ServiceUnavailableError,
|
||||
InvalidResponseError,
|
||||
NetworkError,
|
||||
ApiError
|
||||
} from '../errors';
|
||||
|
||||
/**
|
||||
* Client for interacting with the Anthropic Claude API
|
||||
*
|
||||
* Handles text cleanup operations using Claude models, including retry logic,
|
||||
* error handling, and structured response parsing. Supports optional AI commentary
|
||||
* on freewriting sessions.
|
||||
*/
|
||||
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
|
||||
|
||||
/**
|
||||
* Creates a new Anthropic API client
|
||||
*
|
||||
* @param apiKey - Anthropic API key for authentication
|
||||
*/
|
||||
constructor(apiKey: string) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/**
|
||||
* Cleans up freewriting text using Claude AI
|
||||
*
|
||||
* Sends text to Claude with specified cleanup instructions and optionally
|
||||
* requests commentary on the writing. Uses structured output markers to
|
||||
* reliably extract cleaned text and commentary from the response.
|
||||
*
|
||||
* @param text - The freewriting text to clean up
|
||||
* @param model - Claude model identifier (e.g., 'claude-3-5-haiku-latest')
|
||||
* @param cleanupPrompt - Instructions for how to clean up the text
|
||||
* @param enableCommentary - Whether to include AI commentary on the writing
|
||||
* @param commentaryStyle - Style of commentary to provide (if enabled)
|
||||
* @param customCommentaryPrompt - Custom prompt for commentary (used when style is 'custom')
|
||||
* @returns Object containing cleaned text, optional commentary, and token usage
|
||||
* @throws Error if API key is missing, text exceeds character limits, or API request fails
|
||||
*/
|
||||
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');
|
||||
throw new ApiKeyError('API key is required');
|
||||
}
|
||||
|
||||
if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) {
|
||||
throw new Error(`Text too long. Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters allowed.`);
|
||||
throw new TextTooLongError(`Text too long. Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters allowed.`);
|
||||
}
|
||||
|
||||
// Get commentary prompt if enabled
|
||||
@@ -37,6 +75,8 @@ export class AnthropicClient {
|
||||
if (enableCommentary) {
|
||||
if (commentaryStyle === 'custom' && customCommentaryPrompt) {
|
||||
commentaryPrompt = customCommentaryPrompt;
|
||||
} else if (commentaryStyle === 'custom') {
|
||||
throw new ConfigurationError('Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.');
|
||||
} else {
|
||||
commentaryPrompt = COMMENTARY_PRESETS[commentaryStyle as Exclude<CommentaryStyle, 'custom'>];
|
||||
}
|
||||
@@ -69,15 +109,31 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
const request: AnthropicRequest = {
|
||||
model,
|
||||
max_tokens: ANTHROPIC_LIMITS.DEFAULT_MAX_OUTPUT_TOKENS,
|
||||
messages: [{ role: 'user', content: userMessage }],
|
||||
system: systemPrompt
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: userMessage }] }],
|
||||
system: [{ type: 'text', text: systemPrompt }]
|
||||
};
|
||||
|
||||
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<{
|
||||
/**
|
||||
* Tests the API connection with a simple request
|
||||
*
|
||||
* Sends a minimal test message to verify the API key is valid and
|
||||
* the connection is working. Returns timing and token usage information
|
||||
* to help diagnose connection issues.
|
||||
*
|
||||
* @param model - Claude model identifier to test with
|
||||
* @returns Object indicating success/failure with optional timing details
|
||||
*/
|
||||
async testConnection(model: string): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: {
|
||||
@@ -100,8 +156,8 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
const testRequest: AnthropicRequest = {
|
||||
model,
|
||||
max_tokens: 50,
|
||||
messages: [{ role: 'user', content: 'Hello! Please respond with just "Test successful."' }],
|
||||
system: 'You are a test assistant. Respond only with "Test successful." and nothing else.'
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello! Please respond with just "Test successful."' }] }],
|
||||
system: [{ type: 'text', text: 'You are a test assistant. Respond only with "Test successful." and nothing else.' }]
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -129,16 +185,37 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private async makeRequestWithRetry(request: AnthropicRequest): Promise<string> {
|
||||
/**
|
||||
* Makes an API request with automatic retry logic
|
||||
*
|
||||
* Retries failed requests up to MAX_RETRIES times with exponential backoff.
|
||||
* Only retries transient failures (network errors, 5xx server errors).
|
||||
* Client errors (4xx, configuration errors, API key errors) fail immediately
|
||||
* since retrying won't help and wastes time and API quota.
|
||||
*
|
||||
* @param request - The Anthropic API request to send
|
||||
* @returns The API response
|
||||
* @throws Error if all retry attempts fail or on non-retryable errors
|
||||
*/
|
||||
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');
|
||||
|
||||
// Don't retry client errors (ApiKeyError, ConfigurationError, ApiError with 4xx status)
|
||||
// Exception: 429 (rate limit) is retryable as it's a transient condition
|
||||
if (error instanceof ApiKeyError || error instanceof ConfigurationError) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500 && error.status !== 429) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (attempt < this.MAX_RETRIES) {
|
||||
const delay = this.RETRY_DELAY_BASE * Math.pow(2, attempt - 1); // Exponential backoff
|
||||
await this.sleep(delay);
|
||||
@@ -147,19 +224,31 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed after ${this.MAX_RETRIES} attempts. Last error: ${lastError.message}`);
|
||||
throw new ServiceUnavailableError(`Failed after ${this.MAX_RETRIES} attempts. Last error: ${lastError.message}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses structured response text from Claude
|
||||
*
|
||||
* Extracts cleaned text and optional commentary using marker-based parsing.
|
||||
* This approach provides reliable extraction even when Claude includes
|
||||
* additional formatting or explanations.
|
||||
*
|
||||
* @param responseText - Raw text response from Claude API
|
||||
* @param expectCommentary - Whether to look for commentary section
|
||||
* @returns Object containing extracted cleaned text and optional commentary
|
||||
* @throws Error if required markers are missing or cleaned text is empty
|
||||
*/
|
||||
private parseStructuredResponse(responseText: string, expectCommentary: boolean): { cleanedText: string; commentary?: string } {
|
||||
// Extract cleaned text
|
||||
const cleanedTextMatch = responseText.match(/===CLEANED TEXT===([\s\S]*?)===END CLEANED TEXT===/);
|
||||
if (!cleanedTextMatch) {
|
||||
throw new Error('Invalid response format: Could not find cleaned text section');
|
||||
throw new InvalidResponseError('Invalid response format: Could not find cleaned text section');
|
||||
}
|
||||
|
||||
const cleanedText = cleanedTextMatch[1].trim();
|
||||
if (!cleanedText) {
|
||||
throw new Error('Empty cleaned text received');
|
||||
throw new InvalidResponseError('Empty cleaned text received');
|
||||
}
|
||||
|
||||
let commentary: string | undefined;
|
||||
@@ -174,10 +263,58 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
return { cleanedText, commentary };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches available Claude models from the Anthropic API
|
||||
*
|
||||
* Retrieves the current list of models with their metadata including
|
||||
* display names and creation timestamps. Used for populating the model
|
||||
* selection dropdown with current options.
|
||||
*
|
||||
* @returns API response containing array of model information
|
||||
* @throws Error if API key is missing or request fails
|
||||
*/
|
||||
async fetchModels(): Promise<ModelsListResponse> {
|
||||
if (!this.apiKey) {
|
||||
throw new ApiKeyError('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 ApiError(`Models API request failed: ${response.status}\n${response.text}`, response.status, response.text);
|
||||
}
|
||||
|
||||
return response.json as ModelsListResponse;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
}
|
||||
throw new NetworkError(`Network request failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a single API request to Claude messages endpoint
|
||||
*
|
||||
* Low-level method that handles the actual HTTP request to Anthropic.
|
||||
* Used by makeRequestWithRetry for the underlying request logic.
|
||||
*
|
||||
* @param request - The Anthropic API request payload
|
||||
* @returns The API response
|
||||
* @throws Error if request fails or returns non-2xx status
|
||||
*/
|
||||
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',
|
||||
@@ -189,7 +326,13 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
const errorBody = response.text || 'Unknown error';
|
||||
throw new Error(`API request failed (${response.status}): ${errorBody}`);
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new ApiKeyError('API key is invalid or unauthorized.');
|
||||
}
|
||||
if (response.status === 429) {
|
||||
throw new ServiceUnavailableError('Rate limited by API. Please retry shortly.');
|
||||
}
|
||||
throw new ApiError(`API request failed (${response.status}): ${errorBody}`, response.status, errorBody);
|
||||
}
|
||||
|
||||
return response.json as AnthropicResponse;
|
||||
@@ -197,33 +340,63 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Network request failed: ${String(error)}`);
|
||||
throw new NetworkError(`Network request failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts text content from an Anthropic API response
|
||||
*
|
||||
* Safely extracts and concatenates all text blocks from the response.
|
||||
* Anthropic can return multiple text blocks; this ensures we capture
|
||||
* all content rather than just the first block.
|
||||
*
|
||||
* @param response - The API response object
|
||||
* @returns Trimmed text content from all response blocks
|
||||
* @throws Error if response has no content or empty text
|
||||
*/
|
||||
private extractTextFromResponse(response: AnthropicResponse): string {
|
||||
if (!response.content || response.content.length === 0) {
|
||||
throw new Error('No content received from API');
|
||||
throw new InvalidResponseError('No content received from API');
|
||||
}
|
||||
|
||||
const text = response.content[0].text;
|
||||
if (!text || text.trim().length === 0) {
|
||||
throw new Error('Empty response from API');
|
||||
const text = response.content.map(c => c.text ?? '').join('').trim();
|
||||
if (!text) {
|
||||
throw new InvalidResponseError('Empty response from API');
|
||||
}
|
||||
|
||||
return text.trim();
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to pause execution for retry delays
|
||||
*
|
||||
* @param ms - Number of milliseconds to sleep
|
||||
* @returns Promise that resolves after the specified delay
|
||||
*/
|
||||
private sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// MARK: - Configuration Methods
|
||||
|
||||
/**
|
||||
* Updates the API key used for authentication
|
||||
*
|
||||
* Allows changing the API key without creating a new client instance.
|
||||
* Used when user updates their API key in settings.
|
||||
*
|
||||
* @param apiKey - New Anthropic API key
|
||||
*/
|
||||
updateApiKey(apiKey: string): void {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that an API key is present and non-empty
|
||||
*
|
||||
* @returns True if API key exists and has non-whitespace content
|
||||
*/
|
||||
validateApiKey(): boolean {
|
||||
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
||||
}
|
||||
|
||||
+66
-57
@@ -3,36 +3,55 @@
|
||||
|
||||
import { Editor, MarkdownView, Notice } from 'obsidian';
|
||||
import { CleanupService } from '../services/cleanupService';
|
||||
import { FreewritingCleanupSettings } from '../types';
|
||||
import { FreewritingCleanupSettings, ANTHROPIC_LIMITS } from '../types';
|
||||
import { ApiKeyError, TextTooLongError, ServiceUnavailableError, ApiError, InvalidResponseError, NetworkError } from '../errors';
|
||||
|
||||
/**
|
||||
* Command handler for freewriting cleanup operations
|
||||
*
|
||||
* Coordinates editor interaction, text selection validation, cleanup execution,
|
||||
* and result insertion. Provides user feedback through notices for all stages
|
||||
* of the cleanup process.
|
||||
*/
|
||||
export class CleanupCommand {
|
||||
private cleanupService: CleanupService;
|
||||
|
||||
/**
|
||||
* Creates a new cleanup command handler
|
||||
*
|
||||
* @param cleanupService - Service for performing text cleanup
|
||||
*/
|
||||
constructor(cleanupService: CleanupService) {
|
||||
this.cleanupService = cleanupService;
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {
|
||||
/**
|
||||
* Executes the cleanup command on selected text
|
||||
*
|
||||
* Gets selected text from editor, validates it, sends to cleanup service,
|
||||
* and inserts formatted result below the selection. Shows persistent loading
|
||||
* notice during processing and error notices if operation fails.
|
||||
*
|
||||
* @param editor - Obsidian editor instance
|
||||
* @param _view - Current markdown view (unused but required by editorCallback signature)
|
||||
* @param settings - Plugin settings for cleanup configuration
|
||||
*/
|
||||
async execute(editor: Editor, _view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {
|
||||
try {
|
||||
// Get selected text
|
||||
const selectedText = editor.getSelection();
|
||||
|
||||
if (!selectedText || selectedText.trim().length === 0) {
|
||||
new Notice('Please select some text to clean up');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate text length before proceeding
|
||||
const limits = CleanupService.isWithinLimits(selectedText);
|
||||
if (!limits.withinCharacterLimit) {
|
||||
new Notice(`Selected text is too long (${limits.characterCount} characters). Maximum: 680,000 characters.`);
|
||||
// Validate text selection before proceeding
|
||||
const validation = this.validateSelection(selectedText);
|
||||
if (!validation.isValid) {
|
||||
new Notice(validation.error || 'Invalid text selection');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show loading notice
|
||||
const loadingNotice = new Notice('Cleaning up text...', 0); // 0 = persistent
|
||||
const loadingNotice = new Notice('Cleaning up text...', 0); // persistent; hide in finally
|
||||
|
||||
try {
|
||||
// Process the text
|
||||
@@ -54,30 +73,37 @@ export class CleanupCommand {
|
||||
editor.setCursor(insertPosition);
|
||||
editor.replaceRange(formattedResult, insertPosition);
|
||||
|
||||
// Clear the loading notice
|
||||
loadingNotice.hide();
|
||||
|
||||
// Show success notice with duration (loadingNotice will be hidden in finally)
|
||||
new Notice(`Text cleanup completed in ${(result.duration / 1000).toFixed(1)}s`);
|
||||
} catch (error) {
|
||||
// Clear loading notice
|
||||
loadingNotice.hide();
|
||||
|
||||
// Handle specific error types
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('API key')) {
|
||||
new Notice('API key error. Please check your settings.');
|
||||
} else if (error.message.includes('too long')) {
|
||||
new Notice('Text is too long for processing.');
|
||||
} else if (error.message.includes('Failed after')) {
|
||||
new Notice('Service temporarily unavailable. Please try again.');
|
||||
// Handle specific error types using instanceof checks
|
||||
if (error instanceof ApiKeyError) {
|
||||
new Notice('API key error. Please check your settings.');
|
||||
} else if (error instanceof TextTooLongError) {
|
||||
new Notice(error.message);
|
||||
} else if (error instanceof ApiError) {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
new Notice('API key was rejected by the server. Please verify your key.');
|
||||
} else if (error.status === 429) {
|
||||
new Notice('Rate limited by API. Please wait and try again.');
|
||||
} else {
|
||||
new Notice(`Cleanup failed: ${error.message}`);
|
||||
new Notice(`API error (${error.status}): ${error.message}`);
|
||||
}
|
||||
} else if (error instanceof ServiceUnavailableError) {
|
||||
new Notice(error.message);
|
||||
} else if (error instanceof InvalidResponseError) {
|
||||
new Notice('Received an unexpected response from Claude. Please try again.');
|
||||
} else if (error instanceof NetworkError) {
|
||||
new Notice('Network error. Check your connection and try again.');
|
||||
} else if (error instanceof Error) {
|
||||
new Notice(`Cleanup failed: ${error.message}`);
|
||||
} else {
|
||||
new Notice('An unexpected error occurred during cleanup.');
|
||||
}
|
||||
|
||||
console.error('Cleanup command error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
loadingNotice.hide();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -85,36 +111,20 @@ export class CleanupCommand {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helper Methods
|
||||
|
||||
private getInsertionPosition(editor: Editor): { line: number; ch: number } {
|
||||
const selection = editor.listSelections()[0];
|
||||
if (selection) {
|
||||
// Insert after the selection
|
||||
return {
|
||||
line: selection.head.line,
|
||||
ch: editor.getLine(selection.head.line).length
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback to current cursor position
|
||||
return editor.getCursor();
|
||||
}
|
||||
|
||||
private formatSelectedTextInfo(text: string): string {
|
||||
const characterCount = text.length;
|
||||
const estimatedTokens = CleanupService.estimateTokenCount(text);
|
||||
const lines = text.split('\n').length;
|
||||
|
||||
return `Selected: ${characterCount} characters, ${lines} lines, ~${estimatedTokens} tokens`;
|
||||
}
|
||||
|
||||
// MARK: - Validation Methods
|
||||
|
||||
/**
|
||||
* Validates text selection against API limits
|
||||
*
|
||||
* Checks that text is non-empty and within both character and token limits.
|
||||
* Returns detailed validation result with error messages.
|
||||
*
|
||||
* @param selectedText - Text to validate
|
||||
* @returns Validation result with status and optional error
|
||||
*/
|
||||
validateSelection(selectedText: string): {
|
||||
isValid: boolean;
|
||||
error?: string;
|
||||
info?: string;
|
||||
} {
|
||||
if (!selectedText || selectedText.trim().length === 0) {
|
||||
return {
|
||||
@@ -128,20 +138,19 @@ export class CleanupCommand {
|
||||
if (!limits.withinCharacterLimit) {
|
||||
return {
|
||||
isValid: false,
|
||||
error: `Text too long: ${limits.characterCount} characters (max: 680,000)`
|
||||
error: `Text too long: ${limits.characterCount.toLocaleString()} characters (max: ${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()})`
|
||||
};
|
||||
}
|
||||
|
||||
if (!limits.withinTokenLimit) {
|
||||
return {
|
||||
isValid: false,
|
||||
error: `Text too long: ~${limits.estimatedTokenCount} tokens (max: 200,000)`
|
||||
error: `Text too long: ~${limits.estimatedTokenCount.toLocaleString()} tokens (max: ${ANTHROPIC_LIMITS.MAX_TOKENS.toLocaleString()})`
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: true,
|
||||
info: this.formatSelectedTextInfo(selectedText)
|
||||
isValid: true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// ABOUTME: Custom error types for more robust error handling
|
||||
// ABOUTME: Provides type-safe error categorization instead of fragile string matching
|
||||
|
||||
/**
|
||||
* Base error class for plugin-specific errors
|
||||
*
|
||||
* Provides common foundation for all custom error types in the plugin.
|
||||
* Ensures proper error name is set for instanceof checks and debugging.
|
||||
*/
|
||||
export class PluginError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
// Maintains proper prototype chain for instanceof checks
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when API key is missing or invalid
|
||||
*
|
||||
* Indicates user needs to configure their Anthropic API key in settings.
|
||||
*/
|
||||
export class ApiKeyError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when text exceeds API character or token limits
|
||||
*
|
||||
* Indicates selected text is too large to process with current API limits.
|
||||
*/
|
||||
export class TextTooLongError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when retry attempts are exhausted
|
||||
*
|
||||
* Indicates the service is temporarily unavailable after multiple retry attempts.
|
||||
*/
|
||||
export class ServiceUnavailableError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when API response format is invalid or empty
|
||||
*
|
||||
* Indicates unexpected response structure from the API that cannot be parsed.
|
||||
*/
|
||||
export class InvalidResponseError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when required configuration is missing
|
||||
*
|
||||
* Indicates user needs to provide additional configuration (e.g., custom prompt).
|
||||
*/
|
||||
export class ConfigurationError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when network request fails
|
||||
*
|
||||
* Indicates connectivity issues or network-level failures.
|
||||
*/
|
||||
export class NetworkError extends PluginError {}
|
||||
|
||||
/**
|
||||
* Thrown when API returns an error status
|
||||
*
|
||||
* Wraps API error responses with status codes and error details.
|
||||
*/
|
||||
export class ApiError extends PluginError {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status?: number,
|
||||
public readonly responseBody?: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,46 @@
|
||||
// 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';
|
||||
|
||||
/**
|
||||
* Main plugin class for Freewriting Cleanup
|
||||
*
|
||||
* Coordinates the plugin lifecycle, manages services, and registers commands.
|
||||
* Uses modular architecture with separate services for cleanup operations,
|
||||
* model management, and command execution.
|
||||
*/
|
||||
export default class FreewritingCleanupPlugin extends Plugin {
|
||||
settings: FreewritingCleanupSettings;
|
||||
cleanupService: CleanupService;
|
||||
modelService: ModelService;
|
||||
cleanupCommand: CleanupCommand;
|
||||
|
||||
/**
|
||||
* Plugin initialization
|
||||
*
|
||||
* Loads settings and model cache, initializes services, registers commands,
|
||||
* and adds settings tab. This implementation avoids redundant data loads by
|
||||
* reusing the settings data for cache restoration.
|
||||
*/
|
||||
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();
|
||||
|
||||
@@ -26,18 +49,50 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
||||
this.addSettingTab(new FreewritingCleanupSettingTab(this.app, this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin cleanup
|
||||
*
|
||||
* Called when plugin is disabled. Currently no cleanup needed as services
|
||||
* are stateless and will be garbage collected.
|
||||
*/
|
||||
onunload() {
|
||||
// Cleanup if needed
|
||||
}
|
||||
|
||||
// MARK: - Settings Management
|
||||
|
||||
async loadSettings() {
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||
/**
|
||||
* Loads plugin settings from Obsidian storage
|
||||
*
|
||||
* Merges stored settings with defaults to ensure all required fields exist.
|
||||
* Excludes modelCache from settings object to keep types clean.
|
||||
* Returns the raw data for reuse in cache loading.
|
||||
*
|
||||
* @returns Raw plugin data including settings and optional cache, or null if no data exists
|
||||
*/
|
||||
async loadSettings(): Promise<FreewritingCleanupData | null> {
|
||||
const data = await this.loadData() as FreewritingCleanupData | null;
|
||||
const { modelCache, ...persisted } = data ?? {};
|
||||
this.settings = {
|
||||
...DEFAULT_SETTINGS,
|
||||
...(persisted as Partial<FreewritingCleanupSettings>)
|
||||
};
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves plugin settings and model cache to Obsidian storage
|
||||
*
|
||||
* Persists current settings along with model cache for faster plugin startup.
|
||||
* Updates the cleanup service with new API key when settings change.
|
||||
*/
|
||||
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) {
|
||||
@@ -47,9 +102,16 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
||||
|
||||
// MARK: - Command Registration
|
||||
|
||||
/**
|
||||
* Registers the cleanup command with Obsidian
|
||||
*
|
||||
* Creates the "Clean up text" command with editor callback that executes
|
||||
* the cleanup operation on selected text. Command ID is prefixed with plugin
|
||||
* ID to avoid future collisions and maintain stability post-release.
|
||||
*/
|
||||
private registerCommand() {
|
||||
this.addCommand({
|
||||
id: 'cleanup-text',
|
||||
id: 'freewriting-cleanup-cleanup-text',
|
||||
name: 'Clean up text',
|
||||
editorCallback: async (editor: Editor, view: MarkdownView) => {
|
||||
await this.executeCleanupCommand(editor, view);
|
||||
@@ -59,6 +121,15 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
||||
|
||||
// MARK: - Command Implementation
|
||||
|
||||
/**
|
||||
* Executes the cleanup command
|
||||
*
|
||||
* Delegates to the CleanupCommand instance with current settings.
|
||||
* Catches and logs any errors that occur during execution.
|
||||
*
|
||||
* @param editor - Obsidian editor instance
|
||||
* @param view - Current markdown view
|
||||
*/
|
||||
private async executeCleanupCommand(editor: Editor, view: MarkdownView): Promise<void> {
|
||||
try {
|
||||
await this.cleanupCommand.execute(editor, view, this.settings);
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "freewriting-cleanup",
|
||||
"name": "Freewriting Cleanup",
|
||||
"version": "1.0.2",
|
||||
"version": "1.1.0",
|
||||
"minAppVersion": "1.9.12",
|
||||
"description": "Use AI to clean up your freewriting typos and create a proper paragraph.",
|
||||
"author": "Alexander Kucera",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "freewriting-cleanup",
|
||||
"version": "1.0.2",
|
||||
"version": "1.1.0",
|
||||
"description": "Use AI to clean up your freewriting typos and create a proper paragraph.",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
|
||||
+118
-18
@@ -4,35 +4,68 @@
|
||||
import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||
import { ApiKeyError, TextTooLongError } from '../errors';
|
||||
|
||||
/**
|
||||
* Service for orchestrating text cleanup operations
|
||||
*
|
||||
* Coordinates validation, API requests, and result formatting for freewriting
|
||||
* cleanup. Acts as the main business logic layer between the command layer
|
||||
* and the API client.
|
||||
*/
|
||||
export class CleanupService {
|
||||
private anthropicClient: AnthropicClient;
|
||||
private client: AnthropicClient;
|
||||
|
||||
/**
|
||||
* Exposes the Anthropic client for ModelService
|
||||
*
|
||||
* @returns The underlying Anthropic API client
|
||||
*/
|
||||
get anthropicClient(): AnthropicClient {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new cleanup service
|
||||
*
|
||||
* @param apiKey - Anthropic API key for authentication
|
||||
*/
|
||||
constructor(apiKey: string) {
|
||||
this.anthropicClient = new AnthropicClient(apiKey);
|
||||
this.client = new AnthropicClient(apiKey);
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/**
|
||||
* Cleans up freewriting text using Claude AI
|
||||
*
|
||||
* Validates input text, makes API request through client, and returns
|
||||
* structured result with metadata. Shows user notices for timing feedback.
|
||||
*
|
||||
* @param text - The freewriting text to clean up
|
||||
* @param settings - Plugin settings including model, prompts, and commentary options
|
||||
* @returns Cleanup result with original text, cleaned text, optional commentary, and usage stats
|
||||
* @throws Error if text is empty, too long, API key is invalid, or API request fails
|
||||
*/
|
||||
async cleanupText(text: string, settings: FreewritingCleanupSettings): Promise<CleanupResult> {
|
||||
// Validate input
|
||||
if (!text || text.trim().length === 0) {
|
||||
throw new Error('No text selected for cleanup');
|
||||
}
|
||||
|
||||
if (!this.anthropicClient.validateApiKey()) {
|
||||
throw new Error('API key is not configured. Please check your plugin settings.');
|
||||
if (!this.client.validateApiKey()) {
|
||||
throw new ApiKeyError('API key is not configured. Please check your plugin settings.');
|
||||
}
|
||||
|
||||
// Check text length limits
|
||||
if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) {
|
||||
throw new Error(`Selected text is too long (${text.length} characters). Maximum allowed: ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters.`);
|
||||
throw new TextTooLongError(`Selected text is too long (${text.length} characters). Maximum allowed: ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters.`);
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -41,6 +74,8 @@ export class CleanupService {
|
||||
settings.customCommentaryPrompt
|
||||
);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
const result: CleanupResult = {
|
||||
originalText: text,
|
||||
cleanedText,
|
||||
@@ -48,22 +83,28 @@ 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
|
||||
},
|
||||
duration
|
||||
};
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
new Notice(`Text cleanup completed in ${(duration / 1000).toFixed(1)}s`);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
new Notice(`Text cleanup failed: ${errorMessage}`);
|
||||
// Let the command layer handle user feedback to avoid duplicate notices
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the API connection using current settings
|
||||
*
|
||||
* Validates API key and makes a test request to verify connectivity.
|
||||
* Returns detailed result for user feedback in settings UI.
|
||||
*
|
||||
* @param settings - Plugin settings containing API key and model
|
||||
* @returns Test result with success status, message, and optional timing details
|
||||
*/
|
||||
async testConnection(settings: FreewritingCleanupSettings): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
@@ -74,7 +115,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 +123,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 {
|
||||
@@ -92,6 +133,15 @@ export class CleanupService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats cleanup result for insertion into editor
|
||||
*
|
||||
* Creates markdown-formatted output with separators between sections.
|
||||
* Includes cleaned text and optional commentary section.
|
||||
*
|
||||
* @param result - Cleanup result to format
|
||||
* @returns Formatted string ready for editor insertion
|
||||
*/
|
||||
formatCleanupResult(result: CleanupResult): string {
|
||||
let formatted = `\n\n---\n\nAI Cleanup:\n\n${result.cleanedText}`;
|
||||
|
||||
@@ -104,10 +154,27 @@ export class CleanupService {
|
||||
|
||||
// MARK: - Configuration Methods
|
||||
|
||||
/**
|
||||
* Updates the API key used by the underlying client
|
||||
*
|
||||
* Called when user changes API key in settings to update the client
|
||||
* without recreating the service instance.
|
||||
*
|
||||
* @param apiKey - New Anthropic API key
|
||||
*/
|
||||
updateApiKey(apiKey: string): void {
|
||||
this.anthropicClient.updateApiKey(apiKey);
|
||||
this.client.updateApiKey(apiKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates plugin settings for completeness
|
||||
*
|
||||
* Checks that all required settings are present and valid. Used to
|
||||
* provide user feedback before attempting operations.
|
||||
*
|
||||
* @param settings - Plugin settings to validate
|
||||
* @returns Validation result with boolean flag and list of errors
|
||||
*/
|
||||
validateSettings(settings: FreewritingCleanupSettings): {
|
||||
isValid: boolean;
|
||||
errors: string[];
|
||||
@@ -126,6 +193,12 @@ export class CleanupService {
|
||||
errors.push('Cleanup prompt is required');
|
||||
}
|
||||
|
||||
if (settings.enableCommentary &&
|
||||
settings.commentaryStyle === 'custom' &&
|
||||
(!settings.customCommentaryPrompt || settings.customCommentaryPrompt.trim().length === 0)) {
|
||||
errors.push('Custom commentary prompt is required when commentary style is "custom"');
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: errors.length === 0,
|
||||
errors
|
||||
@@ -134,15 +207,42 @@ export class CleanupService {
|
||||
|
||||
// MARK: - Utility Methods
|
||||
|
||||
/**
|
||||
* Gets the character count of text
|
||||
*
|
||||
* @param text - Text to count characters in
|
||||
* @returns Number of characters
|
||||
*/
|
||||
static getCharacterCount(text: string): number {
|
||||
return text.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimates token count from character count
|
||||
*
|
||||
* Uses rough approximation of 1 token per 4 characters for English text.
|
||||
* Adds a 10% safety margin to account for estimation inaccuracy and reduce
|
||||
* the chance of near-limit failures.
|
||||
*
|
||||
* @param text - Text to estimate tokens for
|
||||
* @returns Estimated token count with safety margin
|
||||
*/
|
||||
static estimateTokenCount(text: string): number {
|
||||
// Rough estimation: 1 token ≈ 4 characters for English text
|
||||
return Math.ceil(text.length / 4);
|
||||
const baseEstimate = Math.ceil(text.length / 4);
|
||||
// Add 10% safety margin to reduce near-limit failures
|
||||
return Math.ceil(baseEstimate * 1.1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if text is within API limits
|
||||
*
|
||||
* Validates text against both character and token limits defined by
|
||||
* Anthropic API. Returns detailed information for user feedback.
|
||||
*
|
||||
* @param text - Text to validate
|
||||
* @returns Object with limit validation flags and counts
|
||||
*/
|
||||
static isWithinLimits(text: string): {
|
||||
withinCharacterLimit: boolean;
|
||||
withinTokenLimit: boolean;
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
// 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';
|
||||
|
||||
/**
|
||||
* Simplified model option for UI display
|
||||
*/
|
||||
export interface ModelOption {
|
||||
/** Model identifier used in API requests */
|
||||
id: string;
|
||||
/** User-friendly display name for dropdowns */
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for managing available Claude models
|
||||
*
|
||||
* Fetches model lists from the Anthropic API with 24-hour caching to minimize
|
||||
* API calls. Falls back to hardcoded model list when API is unavailable or
|
||||
* API key is not configured. This implementation ensures the UI always has
|
||||
* model options available even during offline use or before API key setup.
|
||||
*/
|
||||
export class ModelService {
|
||||
private anthropicClient: AnthropicClient;
|
||||
private modelCache: ModelCache | null = null;
|
||||
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
private lastErrorNoticeTime = 0;
|
||||
private readonly ERROR_NOTICE_THROTTLE_MS = 60 * 1000; // 1 minute
|
||||
|
||||
/**
|
||||
* Creates a new model service
|
||||
*
|
||||
* @param anthropicClient - Anthropic API client for fetching models
|
||||
*/
|
||||
constructor(anthropicClient: AnthropicClient) {
|
||||
this.anthropicClient = anthropicClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts ModelOption to ModelInfo format
|
||||
*
|
||||
* Helper to maintain consistent shape when caching fallback models.
|
||||
* Keeps the mapping logic in one place for easier maintenance.
|
||||
*
|
||||
* @param opt - Model option to convert
|
||||
* @returns ModelInfo with empty metadata fields
|
||||
*/
|
||||
private toModelInfo(opt: ModelOption): ModelInfo {
|
||||
return {
|
||||
id: opt.id,
|
||||
display_name: opt.displayName,
|
||||
created_at: '',
|
||||
type: 'model'
|
||||
};
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/**
|
||||
* Gets available models with caching and fallback logic
|
||||
*
|
||||
* Returns models from cache if valid (< 24 hours old), otherwise fetches
|
||||
* fresh data from the API. Automatically falls back to hardcoded model list
|
||||
* if API key is missing or API request fails. This ensures the settings UI
|
||||
* always has model options available.
|
||||
*
|
||||
* @returns Array of model options for UI display
|
||||
*/
|
||||
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()) {
|
||||
return this.cacheFallbackModels();
|
||||
}
|
||||
|
||||
// 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);
|
||||
this.showThrottledErrorNotice();
|
||||
return this.cacheFallbackModels();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces a refresh of the model list from the API
|
||||
*
|
||||
* Bypasses cache and fetches fresh model data from Anthropic. Used when
|
||||
* the user changes their API key or manually requests a refresh. Falls back
|
||||
* to hardcoded models if the API is unavailable.
|
||||
*
|
||||
* @returns Array of model options for UI display
|
||||
*/
|
||||
async refreshModels(): Promise<ModelOption[]> {
|
||||
// If no API key, immediately return and cache fallback
|
||||
if (!this.anthropicClient.validateApiKey()) {
|
||||
return this.cacheFallbackModels();
|
||||
}
|
||||
|
||||
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);
|
||||
this.showThrottledErrorNotice();
|
||||
return this.cacheFallbackModels();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads model cache from plugin data
|
||||
*
|
||||
* Restores previously cached model data when the plugin initializes.
|
||||
* This allows the plugin to avoid an API call on startup if cache is
|
||||
* still valid.
|
||||
*
|
||||
* @param cache - Cached model data from plugin storage
|
||||
*/
|
||||
loadCache(cache: ModelCache | null): void {
|
||||
this.modelCache = cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets current cache for persisting to plugin data
|
||||
*
|
||||
* @returns Current model cache or null if no cache exists
|
||||
*/
|
||||
getCache(): ModelCache | null {
|
||||
return this.modelCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the cache to force fresh fetch on next request
|
||||
*
|
||||
* Used for testing or when manual refresh is needed
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.modelCache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets fallback model options for UI components
|
||||
*
|
||||
* Public API that returns the hardcoded model list formatted as
|
||||
* ModelOption array. Used by settings UI when API is unavailable.
|
||||
*
|
||||
* @returns Array of hardcoded model options
|
||||
*/
|
||||
getFallbackOptions(): ModelOption[] {
|
||||
return this.getFallbackModels();
|
||||
}
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
/**
|
||||
* Caches fallback models as ModelInfo for consistency
|
||||
*
|
||||
* Helper that retrieves fallback models and updates the cache with them
|
||||
* converted to ModelInfo format. This consolidates the common pattern of
|
||||
* falling back to hardcoded models when the API is unavailable.
|
||||
*
|
||||
* @returns Array of fallback model options
|
||||
*/
|
||||
private cacheFallbackModels(): ModelOption[] {
|
||||
const fallback = this.getFallbackModels();
|
||||
this.updateCache(fallback.map(f => this.toModelInfo(f)));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows throttled error notice for API failures
|
||||
*
|
||||
* Prevents spamming user with error notices when API is persistently down.
|
||||
* Only shows notice once per minute to avoid notification fatigue.
|
||||
*/
|
||||
private showThrottledErrorNotice(): void {
|
||||
const now = Date.now();
|
||||
if (now - this.lastErrorNoticeTime > this.ERROR_NOTICE_THROTTLE_MS) {
|
||||
new Notice('Fetching current models failed. Using hardcoded fallback list.');
|
||||
this.lastErrorNoticeTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current cache is still valid
|
||||
*
|
||||
* Cache is considered valid if it exists and is less than 24 hours old.
|
||||
* This implementation reduces unnecessary API calls while keeping model
|
||||
* data reasonably current.
|
||||
*
|
||||
* @returns True if cache exists and is 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates cache with new model data
|
||||
*
|
||||
* Stores fetched models along with current timestamp for TTL tracking.
|
||||
*
|
||||
* @param models - Array of model information from API
|
||||
*/
|
||||
private updateCache(models: ModelInfo[]): void {
|
||||
this.modelCache = {
|
||||
models,
|
||||
fetchedAt: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats ModelInfo array to ModelOption array for dropdowns
|
||||
*
|
||||
* Converts API model data to simplified format for UI display. Uses
|
||||
* display_name from API for user-friendly model names. Results are
|
||||
* sorted alphabetically for consistent UX regardless of API ordering.
|
||||
*
|
||||
* @param models - Array of model information from API
|
||||
* @returns Formatted and sorted model options
|
||||
*/
|
||||
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||
return models
|
||||
.map(model => ({
|
||||
id: model.id,
|
||||
displayName: model.display_name
|
||||
}))
|
||||
.sort((a, b) => a.displayName.localeCompare(b.displayName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets fallback models from hardcoded list
|
||||
*
|
||||
* Returns the static model list defined in types.ts, formatted as
|
||||
* ModelOption array. Used when API is unavailable or before API key
|
||||
* is configured.
|
||||
*
|
||||
* @returns Array of hardcoded model options
|
||||
*/
|
||||
private getFallbackModels(): ModelOption[] {
|
||||
return ANTHROPIC_MODELS.map(id => ({
|
||||
id,
|
||||
displayName: id
|
||||
}));
|
||||
}
|
||||
}
|
||||
+237
-40
@@ -1,10 +1,17 @@
|
||||
// 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, ANTHROPIC_LIMITS } from './types';
|
||||
import { ModelOption } from './services/modelService';
|
||||
|
||||
/**
|
||||
* Default plugin settings
|
||||
*
|
||||
* Provides sensible defaults for all settings when plugin is first installed
|
||||
* or when settings are reset.
|
||||
*/
|
||||
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||
apiKey: '',
|
||||
model: 'claude-3-5-haiku-latest' as const,
|
||||
@@ -14,20 +21,69 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||
customCommentaryPrompt: 'Provide thoughtful feedback on this freewriting session, considering the writer\'s flow of thoughts and ideas.'
|
||||
};
|
||||
|
||||
/**
|
||||
* Settings tab for the Freewriting Cleanup plugin
|
||||
*
|
||||
* Provides UI for configuring API key, model selection, cleanup prompts,
|
||||
* and commentary options. Handles model list loading, API key testing,
|
||||
* and settings reset functionality.
|
||||
*/
|
||||
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
plugin: FreewritingCleanupPlugin;
|
||||
private modelDropdown: DropdownComponent | null = null;
|
||||
private availableModels: ModelOption[] = [];
|
||||
private saveDebounce: number | null = null;
|
||||
|
||||
/**
|
||||
* Creates a new settings tab
|
||||
*
|
||||
* @param app - Obsidian app instance
|
||||
* @param plugin - Plugin instance
|
||||
*/
|
||||
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a debounced save to reduce disk IO
|
||||
*
|
||||
* Debounces save operations to prevent excessive writes during rapid
|
||||
* user input (e.g., typing in text fields). Uses 300ms delay.
|
||||
*/
|
||||
private scheduleSave(): void {
|
||||
if (this.saveDebounce !== null) window.clearTimeout(this.saveDebounce);
|
||||
this.saveDebounce = window.setTimeout(() => {
|
||||
this.plugin.saveSettings();
|
||||
this.saveDebounce = null;
|
||||
}, 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the settings UI
|
||||
*
|
||||
* Creates all settings controls including API configuration, model selection,
|
||||
* cleanup prompts, commentary options, and usage information. Loads models
|
||||
* asynchronously in the background.
|
||||
*/
|
||||
display(): void {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
|
||||
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' });
|
||||
@@ -40,8 +96,18 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.apiKey)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.apiKey = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.scheduleSave();
|
||||
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 +127,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();
|
||||
});
|
||||
});
|
||||
@@ -85,7 +150,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.cleanupPrompt)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cleanupPrompt = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.scheduleSave();
|
||||
});
|
||||
|
||||
// Style the textarea
|
||||
@@ -104,7 +169,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.enableCommentary)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.enableCommentary = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.scheduleSave();
|
||||
this.display(); // Refresh to show/hide commentary options
|
||||
}));
|
||||
|
||||
@@ -121,7 +186,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.commentaryStyle)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.commentaryStyle = value as CommentaryStyle;
|
||||
await this.plugin.saveSettings();
|
||||
this.scheduleSave();
|
||||
this.display(); // Refresh to show/hide custom prompt
|
||||
});
|
||||
});
|
||||
@@ -136,7 +201,7 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.customCommentaryPrompt)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.customCommentaryPrompt = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.scheduleSave();
|
||||
});
|
||||
|
||||
// Style the textarea
|
||||
@@ -165,12 +230,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
|
||||
const list = usageDiv.createEl('ol');
|
||||
list.createEl('li', { text: 'Select the text you want to clean up in any note' });
|
||||
list.createEl('li', { text: 'Run the "Clean Up Freewriting" command (Ctrl/Cmd+P)' });
|
||||
list.createEl('li', { text: 'Run the "Clean up text" command (Ctrl/Cmd+P)' });
|
||||
list.createEl('li', { text: 'The cleaned text will appear below your original text' });
|
||||
|
||||
const limits = usageDiv.createEl('p');
|
||||
limits.createEl('strong', { text: 'Limits: ' });
|
||||
limits.appendText('Maximum 680,000 characters (~150,000 words) per cleanup');
|
||||
limits.appendText(`Maximum ${ANTHROPIC_LIMITS.MAX_TOKENS.toLocaleString()} tokens per cleanup (~${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()} characters, varies by language)`);
|
||||
|
||||
const format = usageDiv.createEl('p');
|
||||
format.createEl('strong', { text: 'Format: ' });
|
||||
@@ -191,8 +256,106 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
}));
|
||||
}
|
||||
|
||||
// MARK: - Model Loading
|
||||
|
||||
/**
|
||||
* Loads available models from model service
|
||||
*
|
||||
* Fetches current model list (from cache or API) and updates the
|
||||
* availableModels array for dropdown population.
|
||||
*/
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the model dropdown with available options
|
||||
*
|
||||
* Updates dropdown with current model list or shows loading state.
|
||||
* Disables dropdown if no models are available yet.
|
||||
*
|
||||
* @param dropdown - Dropdown component to populate
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes model list from API
|
||||
*
|
||||
* Forces a fresh fetch of models, updates the dropdown UI, and handles
|
||||
* the case where the currently selected model is no longer available.
|
||||
* Shows loading state during refresh.
|
||||
*/
|
||||
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
|
||||
|
||||
/**
|
||||
* Tests the API key connection
|
||||
*
|
||||
* Makes a test API request and shows user feedback via notices.
|
||||
* Updates button state during testing.
|
||||
*
|
||||
* @param button - Button component that triggered the test
|
||||
*/
|
||||
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||
const originalText = button.buttonEl.textContent;
|
||||
button.setButtonText('Testing...');
|
||||
@@ -218,6 +381,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets settings to defaults
|
||||
*
|
||||
* Shows confirmation dialog and resets all settings except API key to
|
||||
* their default values. Refreshes the settings UI after reset.
|
||||
*/
|
||||
private async resetSettings(): Promise<void> {
|
||||
// Confirm the reset
|
||||
const confirmed = await this.showConfirmDialog('Reset Settings',
|
||||
@@ -238,6 +407,15 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a confirmation dialog
|
||||
*
|
||||
* Creates a modal dialog asking user to confirm an action.
|
||||
*
|
||||
* @param title - Dialog title
|
||||
* @param message - Confirmation message
|
||||
* @returns Promise that resolves to true if user confirmed, false if cancelled
|
||||
*/
|
||||
private async showConfirmDialog(title: string, message: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ConfirmModal(this.app, title, message, (result) => {
|
||||
@@ -248,50 +426,69 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||
}
|
||||
}
|
||||
|
||||
// Simple confirmation modal
|
||||
class ConfirmModal {
|
||||
private app: App;
|
||||
/**
|
||||
* Confirmation modal for destructive actions
|
||||
*
|
||||
* Uses Obsidian's Modal class for consistent styling and accessibility.
|
||||
* Provides Cancel and Confirm buttons with appropriate focus handling.
|
||||
*/
|
||||
class ConfirmModal extends Modal {
|
||||
private title: string;
|
||||
private message: string;
|
||||
private callback: (result: boolean) => void;
|
||||
private modalEl: HTMLElement;
|
||||
|
||||
/**
|
||||
* Creates a new confirmation modal
|
||||
*
|
||||
* @param app - Obsidian app instance
|
||||
* @param title - Modal title
|
||||
* @param message - Confirmation message
|
||||
* @param callback - Callback invoked with true (confirmed) or false (cancelled)
|
||||
*/
|
||||
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';
|
||||
/**
|
||||
* Renders the modal content
|
||||
*
|
||||
* Creates title, message, and Cancel/Confirm buttons. Sets focus to
|
||||
* Confirm button for keyboard accessibility.
|
||||
*/
|
||||
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);
|
||||
|
||||
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.callback(result);
|
||||
/**
|
||||
* Cleans up modal content when closed
|
||||
*/
|
||||
onClose(): void {
|
||||
const { contentEl } = this;
|
||||
contentEl.empty();
|
||||
}
|
||||
}
|
||||
@@ -1,68 +1,201 @@
|
||||
// ABOUTME: Type definitions for the Freewriting Cleanup plugin
|
||||
// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration
|
||||
|
||||
/**
|
||||
* Plugin settings interface
|
||||
*
|
||||
* Defines all configurable options for the Freewriting Cleanup plugin.
|
||||
* Settings are persisted to Obsidian's plugin data storage.
|
||||
*/
|
||||
export interface FreewritingCleanupSettings {
|
||||
/** Anthropic API key for authentication */
|
||||
apiKey: string;
|
||||
model: AnthropicModel;
|
||||
/** Claude model identifier (dynamically fetched from API) */
|
||||
model: string;
|
||||
/** Instructions for how Claude should clean up text */
|
||||
cleanupPrompt: string;
|
||||
/** Whether to include AI commentary on the writing */
|
||||
enableCommentary: boolean;
|
||||
/** Style of commentary to provide */
|
||||
commentaryStyle: CommentaryStyle;
|
||||
/** Custom prompt for commentary (when style is 'custom') */
|
||||
customCommentaryPrompt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin data structure for storage
|
||||
*
|
||||
* Extends settings with optional model cache for persisting fetched model data
|
||||
* across plugin reloads.
|
||||
*/
|
||||
export interface FreewritingCleanupData extends FreewritingCleanupSettings {
|
||||
/** Cached model list with timestamp */
|
||||
modelCache?: ModelCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anthropic API message format
|
||||
*
|
||||
* Represents a single message in the conversation with Claude.
|
||||
*/
|
||||
export interface AnthropicMessage {
|
||||
/** Message sender role */
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface AnthropicRequest {
|
||||
model: string;
|
||||
max_tokens: number;
|
||||
messages: AnthropicMessage[];
|
||||
system?: string;
|
||||
}
|
||||
|
||||
export interface AnthropicResponse {
|
||||
/** Message content blocks */
|
||||
content: Array<{
|
||||
/** Content block type */
|
||||
type: string;
|
||||
/** Text content */
|
||||
text: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anthropic API request payload
|
||||
*
|
||||
* Structure for messages API requests to Claude.
|
||||
*/
|
||||
export interface AnthropicRequest {
|
||||
/** Model identifier to use */
|
||||
model: string;
|
||||
/** Maximum tokens to generate in response */
|
||||
max_tokens: number;
|
||||
/** Conversation messages */
|
||||
messages: AnthropicMessage[];
|
||||
/** Optional system prompt */
|
||||
system?: Array<{
|
||||
/** Content block type */
|
||||
type: string;
|
||||
/** System prompt text */
|
||||
text: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anthropic API response format
|
||||
*
|
||||
* Structure of the response from Claude messages API.
|
||||
*/
|
||||
export interface AnthropicResponse {
|
||||
/** Response content blocks */
|
||||
content: Array<{
|
||||
/** Generated text */
|
||||
text: string;
|
||||
/** Content type */
|
||||
type: 'text';
|
||||
}>;
|
||||
/** Unique response identifier */
|
||||
id: string;
|
||||
/** Model used for generation */
|
||||
model: string;
|
||||
/** Response role (always 'assistant') */
|
||||
role: 'assistant';
|
||||
/** Reason generation stopped */
|
||||
stop_reason: string;
|
||||
stop_sequence: null;
|
||||
/** Stop sequence that triggered end (if any) - string | null */
|
||||
stop_sequence: string | null;
|
||||
/** Response type */
|
||||
type: 'message';
|
||||
/** Token usage statistics */
|
||||
usage: {
|
||||
/** Input tokens consumed */
|
||||
input_tokens: number;
|
||||
/** Output tokens generated */
|
||||
output_tokens: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a text cleanup operation
|
||||
*
|
||||
* Contains the processed text along with metadata about the operation.
|
||||
*/
|
||||
export interface CleanupResult {
|
||||
/** Original freewriting text */
|
||||
originalText: string;
|
||||
/** Cleaned up text */
|
||||
cleanedText: string;
|
||||
/** Optional AI commentary on the writing */
|
||||
commentary?: string;
|
||||
/** Timestamp of cleanup operation */
|
||||
timestamp: Date;
|
||||
/** Model used for cleanup */
|
||||
model: string;
|
||||
/** Token usage for the operation */
|
||||
tokensUsed: {
|
||||
/** Input tokens */
|
||||
input: number;
|
||||
/** Output tokens */
|
||||
output: number;
|
||||
};
|
||||
/** Duration of the cleanup operation in milliseconds */
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export const ANTHROPIC_MODELS = [
|
||||
/**
|
||||
* Model information from Anthropic API
|
||||
*
|
||||
* Metadata about an available Claude model.
|
||||
*/
|
||||
export interface ModelInfo {
|
||||
/** Model identifier */
|
||||
id: string;
|
||||
/** Human-readable model name */
|
||||
display_name: string;
|
||||
/** Model creation timestamp */
|
||||
created_at: string;
|
||||
/** Model type */
|
||||
type: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from models list API
|
||||
*
|
||||
* Contains array of available models with pagination metadata.
|
||||
*/
|
||||
export interface ModelsListResponse {
|
||||
/** Array of model information */
|
||||
data: ModelInfo[];
|
||||
/** ID of first model in list (null when data is empty) */
|
||||
first_id: string | null;
|
||||
/** Whether more models are available */
|
||||
has_more: boolean;
|
||||
/** ID of last model in list (null when data is empty) */
|
||||
last_id: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached model data
|
||||
*
|
||||
* Stores fetched models with timestamp for TTL-based cache invalidation.
|
||||
*/
|
||||
export interface ModelCache {
|
||||
/** Cached model list */
|
||||
models: ModelInfo[];
|
||||
/** Unix timestamp when cache was populated */
|
||||
fetchedAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback model list
|
||||
*
|
||||
* Hardcoded list of Claude models used when API is unavailable or API key
|
||||
* is not configured. Provides a baseline set of models for the settings UI.
|
||||
*/
|
||||
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
|
||||
/**
|
||||
* Available commentary style options
|
||||
*
|
||||
* Defines the preset styles users can choose for AI commentary on their writing.
|
||||
*/
|
||||
export const COMMENTARY_STYLES = [
|
||||
'constructive',
|
||||
'encouraging',
|
||||
@@ -71,9 +204,19 @@ export const COMMENTARY_STYLES = [
|
||||
'custom'
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Commentary style type
|
||||
*
|
||||
* Union type of all available commentary styles.
|
||||
*/
|
||||
export type CommentaryStyle = typeof COMMENTARY_STYLES[number];
|
||||
|
||||
// Preset commentary prompts
|
||||
/**
|
||||
* Preset commentary prompts
|
||||
*
|
||||
* Maps each non-custom commentary style to its corresponding prompt text.
|
||||
* These prompts guide Claude in providing the appropriate type of feedback.
|
||||
*/
|
||||
export const COMMENTARY_PRESETS: Record<Exclude<CommentaryStyle, 'custom'>, string> = {
|
||||
constructive: 'Provide balanced feedback on this freewriting, noting strengths and areas for development. Consider the flow of ideas, creativity, and any interesting themes that emerged.',
|
||||
encouraging: 'Offer positive, supportive observations about this freewriting session. Focus on what worked well, creative insights, and encouraging the writer to continue exploring these ideas.',
|
||||
@@ -81,9 +224,31 @@ export const COMMENTARY_PRESETS: Record<Exclude<CommentaryStyle, 'custom'>, stri
|
||||
brief: 'Give 2-3 concise observations about this freewriting session. Keep it short but insightful.'
|
||||
};
|
||||
|
||||
// Constants for Anthropic API limits
|
||||
/**
|
||||
* Anthropic API limits
|
||||
*
|
||||
* Constants defining the maximum input/output sizes for Claude API requests.
|
||||
* Used for validation before making API calls.
|
||||
*/
|
||||
export const ANTHROPIC_LIMITS = {
|
||||
/** Maximum input tokens allowed by Claude API */
|
||||
MAX_TOKENS: 200000,
|
||||
MAX_CHARACTERS: 680000,
|
||||
DEFAULT_MAX_OUTPUT_TOKENS: 4000
|
||||
/**
|
||||
* Approximate maximum input characters
|
||||
*
|
||||
* Character count is approximate and depends on tokenization.
|
||||
* Uses rough estimate of ≈ 4 characters per token, which varies by language
|
||||
* and text structure. Actual token count may differ from this estimation.
|
||||
*/
|
||||
MAX_CHARACTERS: 800000, // Derived from MAX_TOKENS * 4 (conservative estimate)
|
||||
/**
|
||||
* Default maximum output tokens per request
|
||||
*
|
||||
* Set to 8192 which works for most current Claude models:
|
||||
* - Claude 3 Haiku: 4096 tokens (will be capped by API)
|
||||
* - Claude 3.5 Sonnet: 8192 tokens
|
||||
* - Claude 3.5 Haiku: 8192 tokens
|
||||
* - Future models may support higher limits
|
||||
*/
|
||||
DEFAULT_MAX_OUTPUT_TOKENS: 8192
|
||||
} as const;
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"1.0.0": "1.9.12",
|
||||
"1.0.1": "1.9.12",
|
||||
"1.0.2": "1.9.12"
|
||||
"1.0.2": "1.9.12",
|
||||
"1.1.0": "1.9.12"
|
||||
}
|
||||
Reference in new issue
Block a user