Enhances code documentation and structure for plugin
Adds comprehensive documentation for all major classes and methods in the Freewriting Cleanup plugin Improves code readability by: - Adding detailed JSDoc comments explaining purpose and functionality - Clarifying method behaviors and input/output expectations - Providing inline context for complex operations Standardizes error handling and adds more robust validation across services
This commit is contained in:
7 files changed
+584
-24
No files matched your search
@@ -4,6 +4,13 @@
|
|||||||
import { requestUrl } from 'obsidian';
|
import { requestUrl } from 'obsidian';
|
||||||
import { AnthropicRequest, AnthropicResponse, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS, ModelsListResponse } from '../types';
|
import { AnthropicRequest, AnthropicResponse, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS, ModelsListResponse } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
export class AnthropicClient {
|
||||||
private apiKey: string;
|
private apiKey: string;
|
||||||
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
||||||
@@ -11,12 +18,33 @@ export class AnthropicClient {
|
|||||||
private readonly MAX_RETRIES = 3;
|
private readonly MAX_RETRIES = 3;
|
||||||
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new Anthropic API client
|
||||||
|
*
|
||||||
|
* @param apiKey - Anthropic API key for authentication
|
||||||
|
*/
|
||||||
constructor(apiKey: string) {
|
constructor(apiKey: string) {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// 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(
|
async cleanupText(
|
||||||
text: string,
|
text: string,
|
||||||
model: string,
|
model: string,
|
||||||
@@ -84,6 +112,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<{
|
async testConnection(model: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -136,6 +174,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes an API request with automatic retry logic
|
||||||
|
*
|
||||||
|
* Retries failed requests up to MAX_RETRIES times with exponential backoff.
|
||||||
|
* This implementation makes the API calls more resilient to transient failures.
|
||||||
|
*
|
||||||
|
* @param request - The Anthropic API request to send
|
||||||
|
* @returns The API response
|
||||||
|
* @throws Error if all retry attempts fail
|
||||||
|
*/
|
||||||
private async makeRequestWithRetry(request: AnthropicRequest): Promise<AnthropicResponse> {
|
private async makeRequestWithRetry(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||||
let lastError: Error = new Error('No attempts made');
|
let lastError: Error = new Error('No attempts made');
|
||||||
|
|
||||||
@@ -157,6 +205,18 @@ 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 Error(`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 } {
|
private parseStructuredResponse(responseText: string, expectCommentary: boolean): { cleanedText: string; commentary?: string } {
|
||||||
// Extract cleaned text
|
// Extract cleaned text
|
||||||
const cleanedTextMatch = responseText.match(/===CLEANED TEXT===([\s\S]*?)===END CLEANED TEXT===/);
|
const cleanedTextMatch = responseText.match(/===CLEANED TEXT===([\s\S]*?)===END CLEANED TEXT===/);
|
||||||
@@ -181,6 +241,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
return { cleanedText, commentary };
|
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> {
|
async fetchModels(): Promise<ModelsListResponse> {
|
||||||
if (!this.apiKey) {
|
if (!this.apiKey) {
|
||||||
throw new Error('API key is required');
|
throw new Error('API key is required');
|
||||||
@@ -209,6 +279,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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> {
|
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||||
try {
|
try {
|
||||||
const response = await requestUrl({
|
const response = await requestUrl({
|
||||||
@@ -236,6 +316,16 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts text content from an Anthropic API response
|
||||||
|
*
|
||||||
|
* Safely extracts the text content from the first message in the response,
|
||||||
|
* with validation to ensure content exists and is not empty.
|
||||||
|
*
|
||||||
|
* @param response - The API response object
|
||||||
|
* @returns Trimmed text content from the response
|
||||||
|
* @throws Error if response has no content or empty text
|
||||||
|
*/
|
||||||
private extractTextFromResponse(response: AnthropicResponse): string {
|
private extractTextFromResponse(response: AnthropicResponse): string {
|
||||||
if (!response.content || response.content.length === 0) {
|
if (!response.content || response.content.length === 0) {
|
||||||
throw new Error('No content received from API');
|
throw new Error('No content received from API');
|
||||||
@@ -249,16 +339,35 @@ You MUST use exactly these markers. Do not deviate from this format.`;
|
|||||||
return text.trim();
|
return text.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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> {
|
private sleep(ms: number): Promise<void> {
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Configuration Methods
|
// 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 {
|
updateApiKey(apiKey: string): void {
|
||||||
this.apiKey = apiKey;
|
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 {
|
validateApiKey(): boolean {
|
||||||
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,15 +5,38 @@ import { Editor, MarkdownView, Notice } from 'obsidian';
|
|||||||
import { CleanupService } from '../services/cleanupService';
|
import { CleanupService } from '../services/cleanupService';
|
||||||
import { FreewritingCleanupSettings } from '../types';
|
import { FreewritingCleanupSettings } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
export class CleanupCommand {
|
||||||
private cleanupService: CleanupService;
|
private cleanupService: CleanupService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new cleanup command handler
|
||||||
|
*
|
||||||
|
* @param cleanupService - Service for performing text cleanup
|
||||||
|
*/
|
||||||
constructor(cleanupService: CleanupService) {
|
constructor(cleanupService: CleanupService) {
|
||||||
this.cleanupService = cleanupService;
|
this.cleanupService = cleanupService;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* @param settings - Plugin settings for cleanup configuration
|
||||||
|
*/
|
||||||
async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {
|
async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// Get selected text
|
// Get selected text
|
||||||
@@ -87,7 +110,15 @@ export class CleanupCommand {
|
|||||||
|
|
||||||
// MARK: - Helper Methods
|
// MARK: - Helper Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats text selection information for user feedback
|
||||||
|
*
|
||||||
|
* Creates a summary string showing character count, line count, and
|
||||||
|
* estimated token usage for the selected text.
|
||||||
|
*
|
||||||
|
* @param text - Selected text to analyze
|
||||||
|
* @returns Formatted information string
|
||||||
|
*/
|
||||||
private formatSelectedTextInfo(text: string): string {
|
private formatSelectedTextInfo(text: string): string {
|
||||||
const characterCount = text.length;
|
const characterCount = text.length;
|
||||||
const estimatedTokens = CleanupService.estimateTokenCount(text);
|
const estimatedTokens = CleanupService.estimateTokenCount(text);
|
||||||
@@ -98,6 +129,15 @@ export class CleanupCommand {
|
|||||||
|
|
||||||
// MARK: - Validation Methods
|
// 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 or info for user feedback.
|
||||||
|
*
|
||||||
|
* @param selectedText - Text to validate
|
||||||
|
* @returns Validation result with status, optional error, and optional info
|
||||||
|
*/
|
||||||
validateSelection(selectedText: string): {
|
validateSelection(selectedText: string): {
|
||||||
isValid: boolean;
|
isValid: boolean;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
|||||||
@@ -8,12 +8,26 @@ import { CleanupService } from './services/cleanupService';
|
|||||||
import { ModelService } from './services/modelService';
|
import { ModelService } from './services/modelService';
|
||||||
import { CleanupCommand } from './commands/cleanupCommand';
|
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 {
|
export default class FreewritingCleanupPlugin extends Plugin {
|
||||||
settings: FreewritingCleanupSettings;
|
settings: FreewritingCleanupSettings;
|
||||||
cleanupService: CleanupService;
|
cleanupService: CleanupService;
|
||||||
modelService: ModelService;
|
modelService: ModelService;
|
||||||
cleanupCommand: CleanupCommand;
|
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() {
|
async onload() {
|
||||||
// Load settings and reuse the data to avoid double loadData() call
|
// Load settings and reuse the data to avoid double loadData() call
|
||||||
const data = await this.loadSettings();
|
const data = await this.loadSettings();
|
||||||
@@ -35,18 +49,38 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
this.addSettingTab(new FreewritingCleanupSettingTab(this.app, this));
|
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() {
|
onunload() {
|
||||||
// Cleanup if needed
|
// Cleanup if needed
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Settings Management
|
// MARK: - Settings Management
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads plugin settings from Obsidian storage
|
||||||
|
*
|
||||||
|
* Merges stored settings with defaults to ensure all required fields exist.
|
||||||
|
* 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> {
|
async loadSettings(): Promise<FreewritingCleanupData | null> {
|
||||||
const data = await this.loadData() as FreewritingCleanupData | null;
|
const data = await this.loadData() as FreewritingCleanupData | null;
|
||||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
|
||||||
return data;
|
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() {
|
async saveSettings() {
|
||||||
// Save settings with model cache
|
// Save settings with model cache
|
||||||
const data: FreewritingCleanupData = {
|
const data: FreewritingCleanupData = {
|
||||||
@@ -63,6 +97,12 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Command Registration
|
// 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.
|
||||||
|
*/
|
||||||
private registerCommand() {
|
private registerCommand() {
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
id: 'cleanup-text',
|
id: 'cleanup-text',
|
||||||
@@ -75,6 +115,15 @@ export default class FreewritingCleanupPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Command Implementation
|
// 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> {
|
private async executeCleanupCommand(editor: Editor, view: MarkdownView): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.cleanupCommand.execute(editor, view, this.settings);
|
await this.cleanupCommand.execute(editor, view, this.settings);
|
||||||
|
|||||||
@@ -5,20 +5,47 @@ import { Notice } from 'obsidian';
|
|||||||
import { AnthropicClient } from '../api/anthropicClient';
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
export class CleanupService {
|
||||||
private client: AnthropicClient;
|
private client: AnthropicClient;
|
||||||
|
|
||||||
// Expose client for ModelService
|
/**
|
||||||
|
* Exposes the Anthropic client for ModelService
|
||||||
|
*
|
||||||
|
* @returns The underlying Anthropic API client
|
||||||
|
*/
|
||||||
get anthropicClient(): AnthropicClient {
|
get anthropicClient(): AnthropicClient {
|
||||||
return this.client;
|
return this.client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new cleanup service
|
||||||
|
*
|
||||||
|
* @param apiKey - Anthropic API key for authentication
|
||||||
|
*/
|
||||||
constructor(apiKey: string) {
|
constructor(apiKey: string) {
|
||||||
this.client = new AnthropicClient(apiKey);
|
this.client = new AnthropicClient(apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// 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> {
|
async cleanupText(text: string, settings: FreewritingCleanupSettings): Promise<CleanupResult> {
|
||||||
// Validate input
|
// Validate input
|
||||||
if (!text || text.trim().length === 0) {
|
if (!text || text.trim().length === 0) {
|
||||||
@@ -69,6 +96,15 @@ export class CleanupService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<{
|
async testConnection(settings: FreewritingCleanupSettings): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -97,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 {
|
formatCleanupResult(result: CleanupResult): string {
|
||||||
let formatted = `\n\n---\n\nAI Cleanup:\n\n${result.cleanedText}`;
|
let formatted = `\n\n---\n\nAI Cleanup:\n\n${result.cleanedText}`;
|
||||||
|
|
||||||
@@ -109,10 +154,27 @@ export class CleanupService {
|
|||||||
|
|
||||||
// MARK: - Configuration Methods
|
// 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 {
|
updateApiKey(apiKey: string): void {
|
||||||
this.client.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): {
|
validateSettings(settings: FreewritingCleanupSettings): {
|
||||||
isValid: boolean;
|
isValid: boolean;
|
||||||
errors: string[];
|
errors: string[];
|
||||||
@@ -139,15 +201,39 @@ export class CleanupService {
|
|||||||
|
|
||||||
// MARK: - Utility Methods
|
// 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 {
|
static getCharacterCount(text: string): number {
|
||||||
return text.length;
|
return text.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estimates token count from character count
|
||||||
|
*
|
||||||
|
* Uses rough approximation of 1 token per 4 characters for English text.
|
||||||
|
* This is used for user feedback before making API requests.
|
||||||
|
*
|
||||||
|
* @param text - Text to estimate tokens for
|
||||||
|
* @returns Estimated token count
|
||||||
|
*/
|
||||||
static estimateTokenCount(text: string): number {
|
static estimateTokenCount(text: string): number {
|
||||||
// Rough estimation: 1 token ≈ 4 characters for English text
|
// Rough estimation: 1 token ≈ 4 characters for English text
|
||||||
return Math.ceil(text.length / 4);
|
return Math.ceil(text.length / 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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): {
|
static isWithinLimits(text: string): {
|
||||||
withinCharacterLimit: boolean;
|
withinCharacterLimit: boolean;
|
||||||
withinTokenLimit: boolean;
|
withinTokenLimit: boolean;
|
||||||
|
|||||||
+79
-16
@@ -5,16 +5,34 @@ import { Notice } from 'obsidian';
|
|||||||
import { AnthropicClient } from '../api/anthropicClient';
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simplified model option for UI display
|
||||||
|
*/
|
||||||
export interface ModelOption {
|
export interface ModelOption {
|
||||||
|
/** Model identifier used in API requests */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** User-friendly display name for dropdowns */
|
||||||
displayName: string;
|
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 {
|
export class ModelService {
|
||||||
private anthropicClient: AnthropicClient;
|
private anthropicClient: AnthropicClient;
|
||||||
private modelCache: ModelCache | null = null;
|
private modelCache: ModelCache | null = null;
|
||||||
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new model service
|
||||||
|
*
|
||||||
|
* @param anthropicClient - Anthropic API client for fetching models
|
||||||
|
*/
|
||||||
constructor(anthropicClient: AnthropicClient) {
|
constructor(anthropicClient: AnthropicClient) {
|
||||||
this.anthropicClient = anthropicClient;
|
this.anthropicClient = anthropicClient;
|
||||||
}
|
}
|
||||||
@@ -22,9 +40,14 @@ export class ModelService {
|
|||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get available models with caching and fallback logic
|
* Gets 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
|
* 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[]> {
|
async getAvailableModels(): Promise<ModelOption[]> {
|
||||||
// Check if we have a valid cache
|
// Check if we have a valid cache
|
||||||
@@ -66,8 +89,13 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Force refresh the model list from API
|
* Forces a refresh of the model list from the API
|
||||||
* Used when user changes API key
|
*
|
||||||
|
* 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[]> {
|
async refreshModels(): Promise<ModelOption[]> {
|
||||||
// If no API key, immediately return and cache fallback
|
// If no API key, immediately return and cache fallback
|
||||||
@@ -103,29 +131,43 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load cache from plugin data
|
* 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 {
|
loadCache(cache: ModelCache | null): void {
|
||||||
this.modelCache = cache;
|
this.modelCache = cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current cache for saving to plugin data
|
* Gets current cache for persisting to plugin data
|
||||||
|
*
|
||||||
|
* @returns Current model cache or null if no cache exists
|
||||||
*/
|
*/
|
||||||
getCache(): ModelCache | null {
|
getCache(): ModelCache | null {
|
||||||
return this.modelCache;
|
return this.modelCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear the cache (for testing or manual refresh)
|
* Clears the cache to force fresh fetch on next request
|
||||||
|
*
|
||||||
|
* Used for testing or when manual refresh is needed
|
||||||
*/
|
*/
|
||||||
clearCache(): void {
|
clearCache(): void {
|
||||||
this.modelCache = null;
|
this.modelCache = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get fallback model options (public API for UI components)
|
* Gets fallback model options for UI components
|
||||||
* Returns hardcoded model list as ModelOption array
|
*
|
||||||
|
* 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[] {
|
getFallbackOptions(): ModelOption[] {
|
||||||
return this.getFallbackModels();
|
return this.getFallbackModels();
|
||||||
@@ -134,7 +176,13 @@ export class ModelService {
|
|||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the current cache is still valid (within TTL)
|
* 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 {
|
private isCacheValid(): boolean {
|
||||||
if (!this.modelCache) {
|
if (!this.modelCache) {
|
||||||
@@ -147,7 +195,11 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update cache with new model data
|
* 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 {
|
private updateCache(models: ModelInfo[]): void {
|
||||||
this.modelCache = {
|
this.modelCache = {
|
||||||
@@ -157,9 +209,14 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format ModelInfo array to ModelOption array for dropdown
|
* Formats ModelInfo array to ModelOption array for dropdowns
|
||||||
* Uses display_name from API for user-friendly model names
|
*
|
||||||
* Sorted by displayName for consistent UX across cache/API ordering
|
* 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[] {
|
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||||
return models
|
return models
|
||||||
@@ -171,7 +228,13 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get fallback models from hardcoded list
|
* 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[] {
|
private getFallbackModels(): ModelOption[] {
|
||||||
return ANTHROPIC_MODELS.map(id => ({
|
return ANTHROPIC_MODELS.map(id => ({
|
||||||
|
|||||||
+93
-1
@@ -6,6 +6,12 @@ import FreewritingCleanupPlugin from './main';
|
|||||||
import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
|
||||||
import { ModelOption } from './services/modelService';
|
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 = {
|
export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
model: 'claude-3-5-haiku-latest' as const,
|
model: 'claude-3-5-haiku-latest' as const,
|
||||||
@@ -15,16 +21,36 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
|
|||||||
customCommentaryPrompt: 'Provide thoughtful feedback on this freewriting session, considering the writer\'s flow of thoughts and ideas.'
|
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 {
|
export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
||||||
plugin: FreewritingCleanupPlugin;
|
plugin: FreewritingCleanupPlugin;
|
||||||
private modelDropdown: DropdownComponent | null = null;
|
private modelDropdown: DropdownComponent | null = null;
|
||||||
private availableModels: ModelOption[] = [];
|
private availableModels: ModelOption[] = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new settings tab
|
||||||
|
*
|
||||||
|
* @param app - Obsidian app instance
|
||||||
|
* @param plugin - Plugin instance
|
||||||
|
*/
|
||||||
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
constructor(app: App, plugin: FreewritingCleanupPlugin) {
|
||||||
super(app, plugin);
|
super(app, plugin);
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
display(): void {
|
||||||
const { containerEl } = this;
|
const { containerEl } = this;
|
||||||
containerEl.empty();
|
containerEl.empty();
|
||||||
@@ -217,6 +243,12 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// MARK: - Model Loading
|
// 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> {
|
private async loadModels(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
||||||
@@ -226,6 +258,14 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
private populateModelDropdown(dropdown: DropdownComponent): void {
|
||||||
if (this.availableModels.length === 0) {
|
if (this.availableModels.length === 0) {
|
||||||
// No models available yet, disable dropdown
|
// No models available yet, disable dropdown
|
||||||
@@ -245,6 +285,13 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
dropdown.setDisabled(false);
|
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> {
|
private async refreshModels(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// Disable dropdown during refresh
|
// Disable dropdown during refresh
|
||||||
@@ -286,6 +333,14 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// MARK: - Private Methods
|
// 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> {
|
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||||
const originalText = button.buttonEl.textContent;
|
const originalText = button.buttonEl.textContent;
|
||||||
button.setButtonText('Testing...');
|
button.setButtonText('Testing...');
|
||||||
@@ -311,6 +366,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> {
|
private async resetSettings(): Promise<void> {
|
||||||
// Confirm the reset
|
// Confirm the reset
|
||||||
const confirmed = await this.showConfirmDialog('Reset Settings',
|
const confirmed = await this.showConfirmDialog('Reset Settings',
|
||||||
@@ -331,6 +392,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> {
|
private async showConfirmDialog(title: string, message: string): Promise<boolean> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const modal = new ConfirmModal(this.app, title, message, (result) => {
|
const modal = new ConfirmModal(this.app, title, message, (result) => {
|
||||||
@@ -341,12 +411,25 @@ export class FreewritingCleanupSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Confirmation modal using Obsidian's Modal class for consistent styling and accessibility
|
/**
|
||||||
|
* 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 {
|
class ConfirmModal extends Modal {
|
||||||
private title: string;
|
private title: string;
|
||||||
private message: string;
|
private message: string;
|
||||||
private callback: (result: boolean) => void;
|
private callback: (result: boolean) => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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) {
|
constructor(app: App, title: string, message: string, callback: (result: boolean) => void) {
|
||||||
super(app);
|
super(app);
|
||||||
this.title = title;
|
this.title = title;
|
||||||
@@ -354,6 +437,12 @@ class ConfirmModal extends Modal {
|
|||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the modal content
|
||||||
|
*
|
||||||
|
* Creates title, message, and Cancel/Confirm buttons. Sets focus to
|
||||||
|
* Confirm button for keyboard accessibility.
|
||||||
|
*/
|
||||||
onOpen(): void {
|
onOpen(): void {
|
||||||
const { contentEl } = this;
|
const { contentEl } = this;
|
||||||
|
|
||||||
@@ -380,6 +469,9 @@ class ConfirmModal extends Modal {
|
|||||||
confirmButton.focus();
|
confirmButton.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleans up modal content when closed
|
||||||
|
*/
|
||||||
onClose(): void {
|
onClose(): void {
|
||||||
const { contentEl } = this;
|
const { contentEl } = this;
|
||||||
contentEl.empty();
|
contentEl.empty();
|
||||||
|
|||||||
@@ -1,86 +1,185 @@
|
|||||||
// ABOUTME: Type definitions for the Freewriting Cleanup plugin
|
// ABOUTME: Type definitions for the Freewriting Cleanup plugin
|
||||||
// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration
|
// 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 {
|
export interface FreewritingCleanupSettings {
|
||||||
|
/** Anthropic API key for authentication */
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
model: string; // Changed from AnthropicModel to string to support dynamic models
|
/** Claude model identifier (dynamically fetched from API) */
|
||||||
|
model: string;
|
||||||
|
/** Instructions for how Claude should clean up text */
|
||||||
cleanupPrompt: string;
|
cleanupPrompt: string;
|
||||||
|
/** Whether to include AI commentary on the writing */
|
||||||
enableCommentary: boolean;
|
enableCommentary: boolean;
|
||||||
|
/** Style of commentary to provide */
|
||||||
commentaryStyle: CommentaryStyle;
|
commentaryStyle: CommentaryStyle;
|
||||||
|
/** Custom prompt for commentary (when style is 'custom') */
|
||||||
customCommentaryPrompt: string;
|
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 {
|
export interface FreewritingCleanupData extends FreewritingCleanupSettings {
|
||||||
|
/** Cached model list with timestamp */
|
||||||
modelCache?: ModelCache;
|
modelCache?: ModelCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Anthropic API message format
|
||||||
|
*
|
||||||
|
* Represents a single message in the conversation with Claude.
|
||||||
|
*/
|
||||||
export interface AnthropicMessage {
|
export interface AnthropicMessage {
|
||||||
|
/** Message sender role */
|
||||||
role: 'user' | 'assistant' | 'system';
|
role: 'user' | 'assistant' | 'system';
|
||||||
|
/** Message content blocks */
|
||||||
content: Array<{
|
content: Array<{
|
||||||
|
/** Content block type */
|
||||||
type: string;
|
type: string;
|
||||||
|
/** Text content */
|
||||||
text: string;
|
text: string;
|
||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Anthropic API request payload
|
||||||
|
*
|
||||||
|
* Structure for messages API requests to Claude.
|
||||||
|
*/
|
||||||
export interface AnthropicRequest {
|
export interface AnthropicRequest {
|
||||||
|
/** Model identifier to use */
|
||||||
model: string;
|
model: string;
|
||||||
|
/** Maximum tokens to generate in response */
|
||||||
max_tokens: number;
|
max_tokens: number;
|
||||||
|
/** Conversation messages */
|
||||||
messages: AnthropicMessage[];
|
messages: AnthropicMessage[];
|
||||||
|
/** Optional system prompt */
|
||||||
system?: Array<{
|
system?: Array<{
|
||||||
|
/** Content block type */
|
||||||
type: string;
|
type: string;
|
||||||
|
/** System prompt text */
|
||||||
text: string;
|
text: string;
|
||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Anthropic API response format
|
||||||
|
*
|
||||||
|
* Structure of the response from Claude messages API.
|
||||||
|
*/
|
||||||
export interface AnthropicResponse {
|
export interface AnthropicResponse {
|
||||||
|
/** Response content blocks */
|
||||||
content: Array<{
|
content: Array<{
|
||||||
|
/** Generated text */
|
||||||
text: string;
|
text: string;
|
||||||
|
/** Content type */
|
||||||
type: 'text';
|
type: 'text';
|
||||||
}>;
|
}>;
|
||||||
|
/** Unique response identifier */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Model used for generation */
|
||||||
model: string;
|
model: string;
|
||||||
|
/** Response role (always 'assistant') */
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
|
/** Reason generation stopped */
|
||||||
stop_reason: string;
|
stop_reason: string;
|
||||||
|
/** Stop sequence that triggered end (if any) */
|
||||||
stop_sequence: null;
|
stop_sequence: null;
|
||||||
|
/** Response type */
|
||||||
type: 'message';
|
type: 'message';
|
||||||
|
/** Token usage statistics */
|
||||||
usage: {
|
usage: {
|
||||||
|
/** Input tokens consumed */
|
||||||
input_tokens: number;
|
input_tokens: number;
|
||||||
|
/** Output tokens generated */
|
||||||
output_tokens: number;
|
output_tokens: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of a text cleanup operation
|
||||||
|
*
|
||||||
|
* Contains the processed text along with metadata about the operation.
|
||||||
|
*/
|
||||||
export interface CleanupResult {
|
export interface CleanupResult {
|
||||||
|
/** Original freewriting text */
|
||||||
originalText: string;
|
originalText: string;
|
||||||
|
/** Cleaned up text */
|
||||||
cleanedText: string;
|
cleanedText: string;
|
||||||
|
/** Optional AI commentary on the writing */
|
||||||
commentary?: string;
|
commentary?: string;
|
||||||
|
/** Timestamp of cleanup operation */
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
|
/** Model used for cleanup */
|
||||||
model: string;
|
model: string;
|
||||||
|
/** Token usage for the operation */
|
||||||
tokensUsed: {
|
tokensUsed: {
|
||||||
|
/** Input tokens */
|
||||||
input: number;
|
input: number;
|
||||||
|
/** Output tokens */
|
||||||
output: number;
|
output: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Model information from Anthropic API
|
||||||
|
*
|
||||||
|
* Metadata about an available Claude model.
|
||||||
|
*/
|
||||||
export interface ModelInfo {
|
export interface ModelInfo {
|
||||||
|
/** Model identifier */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Human-readable model name */
|
||||||
display_name: string;
|
display_name: string;
|
||||||
|
/** Model creation timestamp */
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
/** Model type */
|
||||||
type: string;
|
type: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response from models list API
|
||||||
|
*
|
||||||
|
* Contains array of available models with pagination metadata.
|
||||||
|
*/
|
||||||
export interface ModelsListResponse {
|
export interface ModelsListResponse {
|
||||||
|
/** Array of model information */
|
||||||
data: ModelInfo[];
|
data: ModelInfo[];
|
||||||
|
/** ID of first model in list */
|
||||||
first_id: string;
|
first_id: string;
|
||||||
|
/** Whether more models are available */
|
||||||
has_more: boolean;
|
has_more: boolean;
|
||||||
|
/** ID of last model in list */
|
||||||
last_id: string;
|
last_id: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cached model data
|
||||||
|
*
|
||||||
|
* Stores fetched models with timestamp for TTL-based cache invalidation.
|
||||||
|
*/
|
||||||
export interface ModelCache {
|
export interface ModelCache {
|
||||||
|
/** Cached model list */
|
||||||
models: ModelInfo[];
|
models: ModelInfo[];
|
||||||
|
/** Unix timestamp when cache was populated */
|
||||||
fetchedAt: number;
|
fetchedAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback model list used when API key is not set or API fetch fails
|
/**
|
||||||
|
* 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[] = [
|
export const ANTHROPIC_MODELS: readonly string[] = [
|
||||||
'claude-opus-4-1-20250805',
|
'claude-opus-4-1-20250805',
|
||||||
'claude-opus-4-20250514',
|
'claude-opus-4-20250514',
|
||||||
@@ -90,7 +189,11 @@ export const ANTHROPIC_MODELS: readonly string[] = [
|
|||||||
'claude-3-haiku-20240307'
|
'claude-3-haiku-20240307'
|
||||||
];
|
];
|
||||||
|
|
||||||
// Commentary style options
|
/**
|
||||||
|
* Available commentary style options
|
||||||
|
*
|
||||||
|
* Defines the preset styles users can choose for AI commentary on their writing.
|
||||||
|
*/
|
||||||
export const COMMENTARY_STYLES = [
|
export const COMMENTARY_STYLES = [
|
||||||
'constructive',
|
'constructive',
|
||||||
'encouraging',
|
'encouraging',
|
||||||
@@ -99,9 +202,19 @@ export const COMMENTARY_STYLES = [
|
|||||||
'custom'
|
'custom'
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commentary style type
|
||||||
|
*
|
||||||
|
* Union type of all available commentary styles.
|
||||||
|
*/
|
||||||
export type CommentaryStyle = typeof COMMENTARY_STYLES[number];
|
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> = {
|
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.',
|
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.',
|
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.',
|
||||||
@@ -109,9 +222,17 @@ export const COMMENTARY_PRESETS: Record<Exclude<CommentaryStyle, 'custom'>, stri
|
|||||||
brief: 'Give 2-3 concise observations about this freewriting session. Keep it short but insightful.'
|
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 = {
|
export const ANTHROPIC_LIMITS = {
|
||||||
|
/** Maximum input tokens */
|
||||||
MAX_TOKENS: 200000,
|
MAX_TOKENS: 200000,
|
||||||
|
/** Maximum input characters */
|
||||||
MAX_CHARACTERS: 680000,
|
MAX_CHARACTERS: 680000,
|
||||||
|
/** Default maximum output tokens per request */
|
||||||
DEFAULT_MAX_OUTPUT_TOKENS: 4000
|
DEFAULT_MAX_OUTPUT_TOKENS: 4000
|
||||||
} as const;
|
} as const;
|
||||||
Reference in new issue
Block a user