Enhances code documentation and structure for plugin #3

Merged
AlexKucera merged 20 commits from docstrings into master 2025-10-25 10:50:22 +02:00
AlexKucera commented 2025-10-24 13:17:14 +02:00 (Migrated from github.com)

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

Summary by CodeRabbit

  • New Features

    • Claude-powered text cleanup with optional AI commentary (presets + custom prompt), formatted result insertion, API key testing, connectivity diagnostics, and model discovery/selection.
  • Reliability & UX

    • TTL-backed model cache with persistent storage and manual refresh, retries for API calls, clearer domain-specific error notices, improved validation and limit checks, debounced settings save, and reduced notice spam.
  • Documentation

    • Expanded docs for settings, features, and plugin lifecycle.
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 is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Claude-powered text cleanup with optional AI commentary (presets + custom prompt), formatted result insertion, API key testing, connectivity diagnostics, and model discovery/selection. * **Reliability & UX** * TTL-backed model cache with persistent storage and manual refresh, retries for API calls, clearer domain-specific error notices, improved validation and limit checks, debounced settings save, and reduced notice spam. * **Documentation** * Expanded docs for settings, features, and plugin lifecycle. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
coderabbitai[bot] commented 2025-10-24 13:17:26 +02:00 (Migrated from github.com)

Warning

Rate limit exceeded

@AlexKucera has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 54 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ab5e134a12 and 4efa8a1282.

📒 Files selected for processing (3)
  • commands/cleanupCommand.ts (4 hunks)
  • settings.ts (16 hunks)
  • types.ts (3 hunks)

Walkthrough

Adds a new AnthropicClient with retry and domain-specific errors, a CleanupService and ModelService with TTL caching and fallbacks, expanded types/constants and settings, updated command and plugin lifecycle wiring, and centralized typed error handling and validation.

Changes

Cohort / File(s) Summary
API Client & Errors
api/anthropicClient.ts, errors.ts
New AnthropicClient with methods cleanupText, testConnection, fetchModels, makeRequestWithRetry, makeRequest, response parsing and API key management; exponential-backoff retry logic; new typed errors (PluginError, ApiKeyError, TextTooLongError, ServiceUnavailableError, InvalidResponseError, ConfigurationError, NetworkError, ApiError).
Service Layer
services/cleanupService.ts
New CleanupService that wraps AnthropicClient, validates inputs/settings, exposes cleanupText, testConnection, formatCleanupResult, updateApiKey, settings validation, token/char utilities, and anthropicClient getter.
Model Management
services/modelService.ts, types.ts
ModelService with 24h TTL caching, getAvailableModels/refreshModels, cache persistence (loadCache/getCache/clearCache), fallback models, throttled error notices, and model formatting; new model-related types and constants in types.ts.
Commands
commands/cleanupCommand.ts
CleanupCommand.execute signature updated to accept _view; validation uses ANTHROPIC_LIMITS; removed selection-info helper; loading notice lifecycle moved to finally; error handling updated to handle typed errors and provide specific notices.
Plugin Core / Lifecycle
main.ts
Added loadSettings/saveSettings, initialization of cleanupService and modelService, modelCache persistence/load, registerCommand, and executeCleanupCommand with centralized error handling and settings merge behavior.
Settings & UI
settings.ts
DEFAULT_SETTINGS extended with cleanupPrompt, enableCommentary, commentaryStyle, customCommentaryPrompt; debounced scheduleSave; model dropdown helpers (loadModels/refreshModels/populateModelDropdown); API key test flow and reset confirmation modal.
Types & Public Contracts
types.ts
New/expanded public types and constants: FreewritingCleanupSettings, FreewritingCleanupData, AnthropicMessage, AnthropicRequest, AnthropicResponse, CleanupResult, ModelsListResponse, ModelCache, ModelInfo, CommentaryStyle, ANTHROPIC_LIMITS, ANTHROPIC_MODELS, COMMENTARY_PRESETS, etc.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Command as CleanupCommand
    participant Service as CleanupService
    participant Client as AnthropicClient
    participant API as Claude API

    User->>Command: trigger cleanup
    Command->>Command: validateSelection() [ANTHROPIC_LIMITS]
    alt invalid
        Command-->>User: show validation error
    else valid
        Command->>Service: cleanupText(text, settings)
        Service->>Client: cleanupText(request)
        Client->>Client: makeRequestWithRetry()
        loop retry (exponential backoff)
            Client->>API: POST /v1/messages (structured payload)
            API-->>Client: 2xx response or 4xx/5xx/429
            Note right of Client: maps errors -> typed errors<br/>(ApiKeyError, ApiError, ServiceUnavailableError, ...)
        end
        alt success
            Client->>Service: cleanedText + commentary? + usage
            Service->>Command: formatted markdown result
            Command->>User: insert/replace text
        else failure
            Client-->>Service: throw typed error
            Service-->>Command: propagate error
            Command-->>User: show typed notice
        end
    end

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • AlexKucera/freewriting-cleanup#2 — Related changes to api/anthropicClient.ts, model fetching and caching logic; overlaps with fetchModels and model endpoints.
  • AlexKucera/freewriting-cleanup#1 — Related modifications to Anthropic message/request shapes and types (AnthropicMessage/AnthropicRequest) used by the new client.

Poem

🐰 I hopped through code and tidy stacks,
Gave retries teeth and clearer tracks,
Cached the models, tuned the prompts,
Wrapped errors neat in rabbit fonts,
Cleaned the drafts — a joyful clap!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The PR title states "Enhances code documentation and structure for plugin," suggesting the primary changes involve documentation and organizational improvements. However, the raw_summary reveals substantially more extensive changes that go far beyond documentation: the PR introduces a complete AnthropicClient implementation with domain-specific error handling and retry logic, creates a new CleanupService orchestration layer, adds a comprehensive error hierarchy, implements model caching with 24h TTL, overhauls the plugin lifecycle with new methods, and adds numerous type definitions and API changes. While the PR objectives mention documentation being added, the actual changeset shows major functional and architectural refactoring, not primarily documentation enhancements. The title significantly downplays the scope and nature of the changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

<!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- This is an auto-generated comment: rate limited by coderabbit.ai --> > [!WARNING] > ## Rate limit exceeded > > @AlexKucera has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait **24 minutes and 54 seconds** before requesting another review. > > <details> > <summary>⌛ How to resolve this issue?</summary> > > After the wait time has elapsed, a review can be triggered using the `@coderabbitai review` command as a PR comment. Alternatively, push new commits to this PR. > > We recommend that you space out your commits to avoid hitting the rate limit. > > </details> > > > <details> > <summary>🚦 How do rate limits work?</summary> > > CodeRabbit enforces hourly rate limits for each developer per organization. > > Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. > > Please see our [FAQ](https://docs.coderabbit.ai/faq) for further information. > > </details> > > <details> > <summary>📥 Commits</summary> > > Reviewing files that changed from the base of the PR and between ab5e134a1248b1e3bf260212872ec2af0533273f and 4efa8a1282cc22e266bc3db2bc7d63d78d5ed381. > > </details> > > <details> > <summary>📒 Files selected for processing (3)</summary> > > * `commands/cleanupCommand.ts` (4 hunks) > * `settings.ts` (16 hunks) > * `types.ts` (3 hunks) > > </details> <!-- end of auto-generated comment: rate limited by coderabbit.ai --> <!-- walkthrough_start --> ## Walkthrough Adds a new AnthropicClient with retry and domain-specific errors, a CleanupService and ModelService with TTL caching and fallbacks, expanded types/constants and settings, updated command and plugin lifecycle wiring, and centralized typed error handling and validation. ## Changes | Cohort / File(s) | Summary | |---|---| | **API Client & Errors** <br> `api/anthropicClient.ts`, `errors.ts` | New `AnthropicClient` with methods `cleanupText`, `testConnection`, `fetchModels`, `makeRequestWithRetry`, `makeRequest`, response parsing and API key management; exponential-backoff retry logic; new typed errors (`PluginError`, `ApiKeyError`, `TextTooLongError`, `ServiceUnavailableError`, `InvalidResponseError`, `ConfigurationError`, `NetworkError`, `ApiError`). | | **Service Layer** <br> `services/cleanupService.ts` | New `CleanupService` that wraps `AnthropicClient`, validates inputs/settings, exposes `cleanupText`, `testConnection`, `formatCleanupResult`, `updateApiKey`, settings validation, token/char utilities, and `anthropicClient` getter. | | **Model Management** <br> `services/modelService.ts`, `types.ts` | `ModelService` with 24h TTL caching, `getAvailableModels`/`refreshModels`, cache persistence (`loadCache`/`getCache`/`clearCache`), fallback models, throttled error notices, and model formatting; new model-related types and constants in `types.ts`. | | **Commands** <br> `commands/cleanupCommand.ts` | `CleanupCommand.execute` signature updated to accept `_view`; validation uses `ANTHROPIC_LIMITS`; removed selection-info helper; loading notice lifecycle moved to finally; error handling updated to handle typed errors and provide specific notices. | | **Plugin Core / Lifecycle** <br> `main.ts` | Added `loadSettings`/`saveSettings`, initialization of `cleanupService` and `modelService`, modelCache persistence/load, `registerCommand`, and `executeCleanupCommand` with centralized error handling and settings merge behavior. | | **Settings & UI** <br> `settings.ts` | `DEFAULT_SETTINGS` extended with `cleanupPrompt`, `enableCommentary`, `commentaryStyle`, `customCommentaryPrompt`; debounced `scheduleSave`; model dropdown helpers (`loadModels`/`refreshModels`/`populateModelDropdown`); API key test flow and reset confirmation modal. | | **Types & Public Contracts** <br> `types.ts` | New/expanded public types and constants: `FreewritingCleanupSettings`, `FreewritingCleanupData`, `AnthropicMessage`, `AnthropicRequest`, `AnthropicResponse`, `CleanupResult`, `ModelsListResponse`, `ModelCache`, `ModelInfo`, `CommentaryStyle`, `ANTHROPIC_LIMITS`, `ANTHROPIC_MODELS`, `COMMENTARY_PRESETS`, etc. | ## Sequence Diagram(s) ```mermaid sequenceDiagram participant User participant Command as CleanupCommand participant Service as CleanupService participant Client as AnthropicClient participant API as Claude API User->>Command: trigger cleanup Command->>Command: validateSelection() [ANTHROPIC_LIMITS] alt invalid Command-->>User: show validation error else valid Command->>Service: cleanupText(text, settings) Service->>Client: cleanupText(request) Client->>Client: makeRequestWithRetry() loop retry (exponential backoff) Client->>API: POST /v1/messages (structured payload) API-->>Client: 2xx response or 4xx/5xx/429 Note right of Client: maps errors -> typed errors<br/>(ApiKeyError, ApiError, ServiceUnavailableError, ...) end alt success Client->>Service: cleanedText + commentary? + usage Service->>Command: formatted markdown result Command->>User: insert/replace text else failure Client-->>Service: throw typed error Service-->>Command: propagate error Command-->>User: show typed notice end end ``` ## Estimated code review effort 🎯 4 (Complex) | ⏱️ ~45 minutes ## Possibly related PRs - AlexKucera/freewriting-cleanup#2 — Related changes to `api/anthropicClient.ts`, model fetching and caching logic; overlaps with `fetchModels` and model endpoints. - AlexKucera/freewriting-cleanup#1 — Related modifications to Anthropic message/request shapes and types (`AnthropicMessage`/`AnthropicRequest`) used by the new client. ## Poem > 🐰 I hopped through code and tidy stacks, > Gave retries teeth and clearer tracks, > Cached the models, tuned the prompts, > Wrapped errors neat in rabbit fonts, > Cleaned the drafts — a joyful clap! <!-- walkthrough_end --> <!-- pre_merge_checks_walkthrough_start --> ## Pre-merge checks and finishing touches <details> <summary>❌ Failed checks (2 warnings)</summary> | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------- | | Title Check | ⚠️ Warning | The PR title states "Enhances code documentation and structure for plugin," suggesting the primary changes involve documentation and organizational improvements. However, the raw_summary reveals substantially more extensive changes that go far beyond documentation: the PR introduces a complete AnthropicClient implementation with domain-specific error handling and retry logic, creates a new CleanupService orchestration layer, adds a comprehensive error hierarchy, implements model caching with 24h TTL, overhauls the plugin lifecycle with new methods, and adds numerous type definitions and API changes. While the PR objectives mention documentation being added, the actual changeset shows major functional and architectural refactoring, not primarily documentation enhancements. The title significantly downplays the scope and nature of the changes. | | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | You can run `@coderabbitai generate docstrings` to improve docstring coverage. | </details> <details> <summary>✅ Passed checks (1 passed)</summary> | Check name | Status | Explanation | | :---------------: | :------- | :---------------------------------------------------------- | | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. | </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=AlexKucera/freewriting-cleanup&utm_content=3)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands and usage tips.</sub> <!-- tips_end --> <!-- internal state start --> <!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKPR1AGxJcAohliYDNIKSpC0+AyO7NTw+FiY9Ii4FNhi2BQkkABm+HzcHthE8FgAFLaQZgDMAJSQkAYAqjYAMlywuLjciBwA9D1FuLDYAhpMzD0Agl4AHgDSqco9WRkkAO4U6sVEYAxemNjcPdzYHh49lXWNiJRcUyRzC1SXAMr46UGQAlQYDLBc4QwkhsMERkIAkwhgzlIuE+31+XGYaCSlBeuGo2G6/G4ZEuAGEMtQ6OhOJAAEwABlJAFYwABGclgUkAFmgtNpHFpAHYOUyAFpuBDIY6nSAZACO2GkMLQtFoyDGvBIsDIiEkmQBUQwaPEcWyuXQIsRQn1uyR12QCUgbEGimQxUgg0yADEVutNiDILi9hgDjwCkUMBpPQEQcFirtsKElGj4F56AApZ4AEQiClY7GQSkQDA2ag9xwo3Hw13QGHoWWwPx1GDQHnUsgANIwPM54Fl4AwYnFkPgslaSDb6AIlWgJLEKBay5B7tixETisdcIgem9OnhEE3LcU6+QFFr7jCcnwFTMscpq4gg3BMuVa4h8PY0WXnLR4AAvYKUCj6kO0HdEUt6BlOUrVyTJvwEDEYQkWt4FoLt4hzYtkGuCgxyCZACBQZheHwKQQnAkgZRUWN60A0USDrEi61wWQNCMfRjHAKAyHoXscAIYgyHPIkxjYLUuF4fhhFEcQpBkeQmCUKhVHULQdEYkwoDgVBUEwDjCFIc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nfzub1YCa8snKD6N8DQreWF4DQTibSmb+ZhHBxLr3IX07UA8keWeQHDI6JqVfgwFphk66Zxk4TmCg+DyypQ6EplmQT1W22cILClUILJ9t0HnAjB+cooIzBfTG+yfACIIlr79DmgSKFAQEBODTrqbWAT6q4XcJGT0Ccc7GnHcqyUAGptm6g/DWRGWgV0OBoMGQgQAybLbdgQQMPLEjBBBYJdM2yXWHDSsa0UqZZN7mwC+tHZA4ewEEStloBjQfACsFWG1YgkGDCAGgNEjyNu0nOBmQceYTMixh5AE93UKOttpi2YAyyLG0UR8p1FPIyRASsyOnXZgeN5EXyprwZaOyLrV1yK+uhlwww4gFV6G8Dduto37r8NEEFA+msZBcZqJ7q6ZfyvAPUrr117R9bBto2n7f1tqwDeetA3proNtgD1YiD0r1oKAy5Ig+utjW8rm2RG9deRvzWIHaNgK/SqYC0Pa4qAckBoHJDkgAApInA7D1RVI7w7svUgCgP3CIEoOfgsLsEy431yACMwI6EfCOgHz1kB9IDAeo3UreSt4I3ywD1p8KAAAUWqWn1AdkA08+kBBLsKT7TBOy8XsfcOXiMiw2fQ8iswPUrcDx65g5CjYP+muDih2jYBBazCHdQc7XUEN0aWartgXq9mB+sLW0bAZ0kK2eHNchKgIZuMy2fDOkhBzvphgGxYydUgmQ08ckBGfKegXRAAZw+JUBjNZBpzG5qM9Rcou9mTzqFrkFA8KuirbAENtB6lapAjOfEfptMy2fpCVAHzSF4cDRcQvERazSZji2xarNzOuQDAGln+apCkhELWQcs7SD+RoADzTIEgAGbfO9OInS7Ghx8xIAVM+mtYAHjQAcuJZzt52i81AGkvO05LCliXRJf0BAA=== --> <!-- internal state end -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 13:27:33 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/anthropicClient.ts (1)

64-72: Fix commentary style fallback logic.

When commentaryStyle is 'custom' but customCommentaryPrompt is undefined or empty, the code falls through to line 70 and attempts to access COMMENTARY_PRESETS['custom'] despite the type cast. This could cause a runtime error if the preset doesn't exist.

Apply this diff to handle the missing custom prompt case explicitly:

 // Get commentary prompt if enabled
 let commentaryPrompt = '';
 if (enableCommentary) {
     if (commentaryStyle === 'custom' && customCommentaryPrompt) {
         commentaryPrompt = customCommentaryPrompt;
+    } else if (commentaryStyle === 'custom') {
+        throw new Error('Custom commentary prompt is required when using custom style');
     } else {
         commentaryPrompt = COMMENTARY_PRESETS[commentaryStyle as Exclude<CommentaryStyle, 'custom'>];
     }
 }

Alternatively, provide a sensible default or validate this earlier in the call chain.

🧹 Nitpick comments (11)
commands/cleanupCommand.ts (3)

57-105: Simplify error/notice handling; avoid double logging.

Use a single try/catch/finally so the Notice always hides and errors aren’t rethrown only to be caught again by the outer block. This removes duplicate console.error logs and guarantees cleanup. As per coding guidelines.

-            // Show loading notice
-            const loadingNotice = new Notice('Cleaning up text...', 0); // 0 = persistent
-
-            try {
+            // Show loading notice
+            const loadingNotice = new Notice('Cleaning up text...', 0); // persistent; hide in finally
+            try {
                 // Process the text
                 const result = await this.cleanupService.cleanupText(selectedText, settings);
                 // Format the result with separator
                 const formattedResult = this.cleanupService.formatCleanupResult(result);
                 // Get cursor position and selection range
                 const selectionEnd = editor.getCursor('to');
                 // Insert the formatted result below the selected text
                 const insertPosition = {
                     line: selectionEnd.line,
                     ch: editor.getLine(selectionEnd.line).length
                 };
                 // Move to end of current line and insert new content
                 editor.setCursor(insertPosition);
                 editor.replaceRange(formattedResult, insertPosition);
-
-                // Clear the loading notice
-                loadingNotice.hide();
-
             } 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.');
                     } else {
                         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();
             }

40-41: Silence linter for unused parameter.

view isn’t used; rename to _view to satisfy ESLint without losing signature compatibility for editorCallback.

-    async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {
+    async execute(editor: Editor, _view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> {

153-167: Avoid hardcoded limits; use ANTHROPIC_LIMITS.

Hardcoding 680,000/200,000 risks drift vs types.ts. Import and reference the constants so notices stay accurate. As per coding guidelines.

-import { FreewritingCleanupSettings } from '../types';
+import { FreewritingCleanupSettings, ANTHROPIC_LIMITS } from '../types';
...
-            return {
-                isValid: false,
-                error: `Text too long: ${limits.characterCount} characters (max: 680,000)`
-            };
+            return {
+                isValid: false,
+                error: `Text too long: ${limits.characterCount.toLocaleString()} characters (max: ${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()})`
+            };
...
-            return {
-                isValid: false,
-                error: `Text too long: ~${limits.estimatedTokenCount} tokens (max: 200,000)`
-            };
+            return {
+                isValid: false,
+                error: `Text too long: ~${limits.estimatedTokenCount.toLocaleString()} tokens (max: ${ANTHROPIC_LIMITS.MAX_TOKENS.toLocaleString()})`
+            };
main.ts (2)

72-76: Don’t merge cache into settings.

Object.assign with data also pulls modelCache into this.settings (typed as FreewritingCleanupSettings). Keep types clean by excluding it during merge. As per coding guidelines.

-        const data = await this.loadData() as FreewritingCleanupData | null;
-        this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
-        return data;
+        const data = await this.loadData() as FreewritingCleanupData | null;
+        const { modelCache, ...persisted } = data ?? {};
+        this.settings = {
+            ...DEFAULT_SETTINGS,
+            ...(persisted as Partial<FreewritingCleanupSettings>)
+        };
+        return data;

106-114: Stabilize command ID naming.

Prefix with plugin id to avoid future collisions and keep IDs stable post-release. This also aligns user docs.

-        this.addCommand({
-            id: 'cleanup-text',
+        this.addCommand({
+            id: 'freewriting-cleanup-cleanup-text',
             name: 'Clean up text',
settings.ts (4)

76-101: Debounce saving on API key edits.

Every keystroke persists to disk and triggers model refresh logic. Debounce to reduce IO and flicker. As per coding guidelines.

-import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types';
+import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS, ANTHROPIC_LIMITS } from './types';
@@
 export class FreewritingCleanupSettingTab extends PluginSettingTab {
     plugin: FreewritingCleanupPlugin;
     private modelDropdown: DropdownComponent | null = null;
     private availableModels: ModelOption[] = [];
+    private saveDebounce: number | null = null;
+    private scheduleSave(): void {
+        if (this.saveDebounce !== null) window.clearTimeout(this.saveDebounce);
+        this.saveDebounce = window.setTimeout(() => {
+            this.plugin.saveSettings();
+            this.saveDebounce = null;
+        }, 300);
+    }
@@
                 .onChange(async (value) => {
                     this.plugin.settings.apiKey = value;
-                    await this.plugin.saveSettings();
+                    this.scheduleSave();
                     this.plugin.cleanupService.updateApiKey(value);

129-144: Debounce textarea saves too.

Same rationale for cleanup prompt edits.

-                    .onChange(async (value) => {
-                        this.plugin.settings.cleanupPrompt = value;
-                        await this.plugin.saveSettings();
-                    });
+                    .onChange(async (value) => {
+                        this.plugin.settings.cleanupPrompt = value;
+                        this.scheduleSave();
+                    });

150-160: Debounce commentary settings saves.

Prevent excessive writes while toggling/choosing styles.

-                .onChange(async (value) => {
-                    this.plugin.settings.enableCommentary = value;
-                    await this.plugin.saveSettings();
-                    this.display(); // Refresh to show/hide commentary options
-                }));
+                .onChange(async (value) => {
+                    this.plugin.settings.enableCommentary = value;
+                    this.scheduleSave();
+                    this.display(); // Refresh to show/hide commentary options
+                }));
@@
-                        .onChange(async (value) => {
-                            this.plugin.settings.commentaryStyle = value as CommentaryStyle;
-                            await this.plugin.saveSettings();
-                            this.display(); // Refresh to show/hide custom prompt
-                        });
+                        .onChange(async (value) => {
+                            this.plugin.settings.commentaryStyle = value as CommentaryStyle;
+                            this.scheduleSave();
+                            this.display(); // Refresh to show/hide custom prompt
+                        });
@@
-                            .onChange(async (value) => {
-                                this.plugin.settings.customCommentaryPrompt = value;
-                                await this.plugin.saveSettings();
-                            });
+                            .onChange(async (value) => {
+                                this.plugin.settings.customCommentaryPrompt = value;
+                                this.scheduleSave();
+                            });

Also applies to: 170-177, 179-196


216-224: Align command name and compute limits from constants.

  • Usage text names the command “Clean Up Freewriting” but the actual command is “Clean up text”.
  • Derive limits from ANTHROPIC_LIMITS to prevent drift.
-        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)' });
@@
-        limits.appendText('Maximum 680,000 characters (~150,000 words) per cleanup');
+        limits.appendText(`Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()} characters per cleanup (~${Math.floor(ANTHROPIC_LIMITS.MAX_TOKENS).toLocaleString()} tokens total)`);
services/modelService.ts (2)

71-89: DRY up fallback-to-cache mapping.

The mapping from ModelOption → ModelInfo is duplicated. Extract a helper to keep shape changes in one place.

 export class ModelService {
@@
     private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
+    private toModelInfo(opt: ModelOption): ModelInfo {
+        return {
+            id: opt.id,
+            display_name: opt.displayName,
+            created_at: '',
+            type: 'model'
+        };
+    }
@@
-            // Cache fallback models as ModelInfo for consistency
-            this.updateCache(fallback.map(f => ({
-                id: f.id,
-                display_name: f.displayName,
-                created_at: '',
-                type: 'model'
-            } as ModelInfo)));
+            // Cache fallback models as ModelInfo for consistency
+            this.updateCache(fallback.map(f => this.toModelInfo(f)));
             return fallback;
@@
-            // Cache fallback models as ModelInfo for consistency
-            this.updateCache(fallback.map(f => ({
-                id: f.id,
-                display_name: f.displayName,
-                created_at: '',
-                type: 'model'
-            } as ModelInfo)));
+            // Cache fallback models as ModelInfo for consistency
+            this.updateCache(fallback.map(f => this.toModelInfo(f)));
             return fallback;

Also applies to: 100-131


77-79: Prevent noisy Notices on repeated failures.

If the API is down, these Notices will appear every call. Consider rate-limiting to once per session or per TTL window.

Also applies to: 118-121

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f5730ac692 and 0f3d6ec7a3.

📒 Files selected for processing (7)
  • api/anthropicClient.ts (8 hunks)
  • commands/cleanupCommand.ts (3 hunks)
  • main.ts (4 hunks)
  • services/cleanupService.ts (5 hunks)
  • services/modelService.ts (7 hunks)
  • settings.ts (10 hunks)
  • types.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • api/anthropicClient.ts
  • settings.ts
  • services/cleanupService.ts
  • commands/cleanupCommand.ts
  • main.ts
  • services/modelService.ts
  • types.ts
{settings.ts,src/settings.ts}

📄 CodeRabbit inference engine (AGENTS.md)

Provide a settings tab and sensible defaults when the plugin has configuration

Files:

  • settings.ts
settings.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence

Files:

  • settings.ts
services/cleanupService.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Isolate Anthropic API integration and connection testing in CleanupService

Files:

  • services/cleanupService.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
{main.ts,src/main.ts}

📄 CodeRabbit inference engine (AGENTS.md)

{main.ts,src/main.ts}: Plugin entry point is main.ts, compiled to main.js and loaded by Obsidian
Keep main.ts minimal, focusing on lifecycle (onload, onunload, addCommand) and delegate feature logic
Persist settings using this.loadData() / this.saveData()
Keep startup light; avoid long-running tasks during onload and defer heavy work

Files:

  • main.ts
{src/commands/**/*.ts,{main.ts,src/main.ts}}

📄 CodeRabbit inference engine (AGENTS.md)

{src/commands/**/*.ts,{main.ts,src/main.ts}}: Add user-facing commands via this.addCommand(...)
Use stable command IDs and avoid renaming once released

Files:

  • main.ts
{main.ts,src/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

{main.ts,src/**/*.ts}: Register and clean up DOM/app/interval listeners using this.register* helpers so the plugin unloads safely
Write idempotent load/unload paths so reload/unload doesn’t leak listeners or intervals

Files:

  • main.ts
main.ts

📄 CodeRabbit inference engine (CLAUDE.md)

main.ts: Use main.ts as the single entry point for the plugin (compiled to main.js)
Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Files:

  • main.ts
types.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize TypeScript interfaces and types in types.ts

Files:

  • types.ts
🧠 Learnings (5)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to settings.ts : Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence

Applied to files:

  • settings.ts
  • main.ts
📚 Learning: 2025-09-26T12:24:39.124Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: AGENTS.md:0-0
Timestamp: 2025-09-26T12:24:39.124Z
Learning: Applies to {settings.ts,src/settings.ts} : Provide a settings tab and sensible defaults when the plugin has configuration

Applied to files:

  • settings.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • commands/cleanupCommand.ts
  • main.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • commands/cleanupCommand.ts
  • main.ts
🧬 Code graph analysis (5)
settings.ts (2)
main.ts (1)
  • FreewritingCleanupPlugin (18-134)
services/modelService.ts (1)
  • ModelOption (11-16)
services/cleanupService.ts (1)
api/anthropicClient.ts (1)
  • AnthropicClient (14-374)
commands/cleanupCommand.ts (1)
services/cleanupService.ts (1)
  • CleanupService (15-253)
main.ts (3)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • FreewritingCleanupData (31-34)
services/cleanupService.ts (1)
  • CleanupService (15-253)
commands/cleanupCommand.ts (1)
  • CleanupCommand (15-174)
services/modelService.ts (1)
types.ts (1)
  • ModelCache (170-175)
🔇 Additional comments (13)
settings.ts (1)

295-328: Nice: model refresh handles missing current model.

Good UX preserving selection when possible and falling back deterministically.

commands/cleanupCommand.ts (1)

57-59: Notice persistence confirmed: No changes required.

When timeout is 0, the Notice stays visible until the user manually dismisses it. The implementation is correct.

services/cleanupService.ts (5)

8-34: LGTM! Clear documentation and solid structure.

The class documentation effectively describes the service's role as an orchestration layer. The exposed getter for anthropicClient properly supports integration with ModelService while maintaining encapsulation.


38-97: LGTM! Comprehensive validation and error handling.

The method properly validates all inputs before making the API call, uses async/await as per coding guidelines, and provides user feedback through notices while still propagating errors appropriately.


99-134: LGTM! Clean delegation pattern.

The test connection method appropriately validates the API key upfront and gracefully handles errors, returning a structured result suitable for UI feedback.


136-200: LGTM! Clear utility methods with good validation.

The formatting method produces readable markdown output, and the settings validation comprehensively checks all required fields with helpful error messages.


204-252: LGTM! Well-documented utility methods.

The static helper methods provide clear functionality with appropriate documentation. The token estimation note about the approximation is helpful context.

api/anthropicClient.ts (6)

7-28: LGTM! Clear documentation and sensible retry defaults.

The class documentation effectively describes the client's responsibilities, and the retry configuration (3 attempts with 1-second base delay) is appropriate for API resilience.


115-173: LGTM! Appropriate test design without retry logic.

Good choice to use makeRequest directly instead of makeRequestWithRetry for connection testing, allowing faster feedback on connectivity issues.


177-206: LGTM! Solid retry implementation with exponential backoff.

The retry logic correctly implements exponential backoff (1s, 2s, 4s) and provides clear error context when all attempts fail, making the API calls resilient to transient failures.


208-242: LGTM! Robust marker-based parsing.

The structured response parsing reliably extracts sections using regex markers and provides clear error messages when the expected format is missing.


244-340: LGTM! Comprehensive API request handling.

All three methods properly handle errors, validate responses, and use async/await. The error messages include helpful context for debugging.


342-373: LGTM! Clean utility methods.

The helper methods are straightforward and well-documented. The validateApiKey method appropriately checks for both presence and non-empty content.

**Actionable comments posted: 2** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (1)</summary><blockquote> > > <details> > <summary>api/anthropicClient.ts (1)</summary><blockquote> > > `64-72`: **Fix commentary style fallback logic.** > > When `commentaryStyle` is `'custom'` but `customCommentaryPrompt` is undefined or empty, the code falls through to line 70 and attempts to access `COMMENTARY_PRESETS['custom']` despite the type cast. This could cause a runtime error if the preset doesn't exist. > > > > Apply this diff to handle the missing custom prompt case explicitly: > > ```diff > // Get commentary prompt if enabled > let commentaryPrompt = ''; > if (enableCommentary) { > if (commentaryStyle === 'custom' && customCommentaryPrompt) { > commentaryPrompt = customCommentaryPrompt; > + } else if (commentaryStyle === 'custom') { > + throw new Error('Custom commentary prompt is required when using custom style'); > } else { > commentaryPrompt = COMMENTARY_PRESETS[commentaryStyle as Exclude<CommentaryStyle, 'custom'>]; > } > } > ``` > > Alternatively, provide a sensible default or validate this earlier in the call chain. > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (11)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (3)</summary><blockquote> `57-105`: **Simplify error/notice handling; avoid double logging.** Use a single try/catch/finally so the Notice always hides and errors aren’t rethrown only to be caught again by the outer block. This removes duplicate console.error logs and guarantees cleanup. As per coding guidelines. ```diff - // Show loading notice - const loadingNotice = new Notice('Cleaning up text...', 0); // 0 = persistent - - try { + // Show loading notice + const loadingNotice = new Notice('Cleaning up text...', 0); // persistent; hide in finally + try { // Process the text const result = await this.cleanupService.cleanupText(selectedText, settings); // Format the result with separator const formattedResult = this.cleanupService.formatCleanupResult(result); // Get cursor position and selection range const selectionEnd = editor.getCursor('to'); // Insert the formatted result below the selected text const insertPosition = { line: selectionEnd.line, ch: editor.getLine(selectionEnd.line).length }; // Move to end of current line and insert new content editor.setCursor(insertPosition); editor.replaceRange(formattedResult, insertPosition); - - // Clear the loading notice - loadingNotice.hide(); - } 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.'); } else { 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(); } ``` --- `40-41`: **Silence linter for unused parameter.** view isn’t used; rename to _view to satisfy ESLint without losing signature compatibility for editorCallback. ```diff - async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> { + async execute(editor: Editor, _view: MarkdownView, settings: FreewritingCleanupSettings): Promise<void> { ``` --- `153-167`: **Avoid hardcoded limits; use ANTHROPIC_LIMITS.** Hardcoding 680,000/200,000 risks drift vs types.ts. Import and reference the constants so notices stay accurate. As per coding guidelines. ```diff -import { FreewritingCleanupSettings } from '../types'; +import { FreewritingCleanupSettings, ANTHROPIC_LIMITS } from '../types'; ... - return { - isValid: false, - error: `Text too long: ${limits.characterCount} characters (max: 680,000)` - }; + return { + isValid: false, + error: `Text too long: ${limits.characterCount.toLocaleString()} characters (max: ${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()})` + }; ... - return { - isValid: false, - error: `Text too long: ~${limits.estimatedTokenCount} tokens (max: 200,000)` - }; + return { + isValid: false, + error: `Text too long: ~${limits.estimatedTokenCount.toLocaleString()} tokens (max: ${ANTHROPIC_LIMITS.MAX_TOKENS.toLocaleString()})` + }; ``` </blockquote></details> <details> <summary>main.ts (2)</summary><blockquote> `72-76`: **Don’t merge cache into settings.** Object.assign with data also pulls modelCache into this.settings (typed as FreewritingCleanupSettings). Keep types clean by excluding it during merge. As per coding guidelines. ```diff - const data = await this.loadData() as FreewritingCleanupData | null; - this.settings = Object.assign({}, DEFAULT_SETTINGS, data); - return data; + const data = await this.loadData() as FreewritingCleanupData | null; + const { modelCache, ...persisted } = data ?? {}; + this.settings = { + ...DEFAULT_SETTINGS, + ...(persisted as Partial<FreewritingCleanupSettings>) + }; + return data; ``` --- `106-114`: **Stabilize command ID naming.** Prefix with plugin id to avoid future collisions and keep IDs stable post-release. This also aligns user docs. ```diff - this.addCommand({ - id: 'cleanup-text', + this.addCommand({ + id: 'freewriting-cleanup-cleanup-text', name: 'Clean up text', ``` </blockquote></details> <details> <summary>settings.ts (4)</summary><blockquote> `76-101`: **Debounce saving on API key edits.** Every keystroke persists to disk and triggers model refresh logic. Debounce to reduce IO and flicker. As per coding guidelines. ```diff -import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types'; +import { FreewritingCleanupSettings, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS, ANTHROPIC_LIMITS } from './types'; @@ export class FreewritingCleanupSettingTab extends PluginSettingTab { plugin: FreewritingCleanupPlugin; private modelDropdown: DropdownComponent | null = null; private availableModels: ModelOption[] = []; + private saveDebounce: number | null = null; + private scheduleSave(): void { + if (this.saveDebounce !== null) window.clearTimeout(this.saveDebounce); + this.saveDebounce = window.setTimeout(() => { + this.plugin.saveSettings(); + this.saveDebounce = null; + }, 300); + } @@ .onChange(async (value) => { this.plugin.settings.apiKey = value; - await this.plugin.saveSettings(); + this.scheduleSave(); this.plugin.cleanupService.updateApiKey(value); ``` --- `129-144`: **Debounce textarea saves too.** Same rationale for cleanup prompt edits. ```diff - .onChange(async (value) => { - this.plugin.settings.cleanupPrompt = value; - await this.plugin.saveSettings(); - }); + .onChange(async (value) => { + this.plugin.settings.cleanupPrompt = value; + this.scheduleSave(); + }); ``` --- `150-160`: **Debounce commentary settings saves.** Prevent excessive writes while toggling/choosing styles. ```diff - .onChange(async (value) => { - this.plugin.settings.enableCommentary = value; - await this.plugin.saveSettings(); - this.display(); // Refresh to show/hide commentary options - })); + .onChange(async (value) => { + this.plugin.settings.enableCommentary = value; + this.scheduleSave(); + this.display(); // Refresh to show/hide commentary options + })); @@ - .onChange(async (value) => { - this.plugin.settings.commentaryStyle = value as CommentaryStyle; - await this.plugin.saveSettings(); - this.display(); // Refresh to show/hide custom prompt - }); + .onChange(async (value) => { + this.plugin.settings.commentaryStyle = value as CommentaryStyle; + this.scheduleSave(); + this.display(); // Refresh to show/hide custom prompt + }); @@ - .onChange(async (value) => { - this.plugin.settings.customCommentaryPrompt = value; - await this.plugin.saveSettings(); - }); + .onChange(async (value) => { + this.plugin.settings.customCommentaryPrompt = value; + this.scheduleSave(); + }); ``` Also applies to: 170-177, 179-196 --- `216-224`: **Align command name and compute limits from constants.** - Usage text names the command “Clean Up Freewriting” but the actual command is “Clean up text”. - Derive limits from ANTHROPIC_LIMITS to prevent drift. ```diff - 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)' }); @@ - limits.appendText('Maximum 680,000 characters (~150,000 words) per cleanup'); + limits.appendText(`Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS.toLocaleString()} characters per cleanup (~${Math.floor(ANTHROPIC_LIMITS.MAX_TOKENS).toLocaleString()} tokens total)`); ``` </blockquote></details> <details> <summary>services/modelService.ts (2)</summary><blockquote> `71-89`: **DRY up fallback-to-cache mapping.** The mapping from ModelOption → ModelInfo is duplicated. Extract a helper to keep shape changes in one place. ```diff export class ModelService { @@ private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + private toModelInfo(opt: ModelOption): ModelInfo { + return { + id: opt.id, + display_name: opt.displayName, + created_at: '', + type: 'model' + }; + } @@ - // Cache fallback models as ModelInfo for consistency - this.updateCache(fallback.map(f => ({ - id: f.id, - display_name: f.displayName, - created_at: '', - type: 'model' - } as ModelInfo))); + // Cache fallback models as ModelInfo for consistency + this.updateCache(fallback.map(f => this.toModelInfo(f))); return fallback; @@ - // Cache fallback models as ModelInfo for consistency - this.updateCache(fallback.map(f => ({ - id: f.id, - display_name: f.displayName, - created_at: '', - type: 'model' - } as ModelInfo))); + // Cache fallback models as ModelInfo for consistency + this.updateCache(fallback.map(f => this.toModelInfo(f))); return fallback; ``` Also applies to: 100-131 --- `77-79`: **Prevent noisy Notices on repeated failures.** If the API is down, these Notices will appear every call. Consider rate-limiting to once per session or per TTL window. Also applies to: 118-121 </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between f5730ac69271cfbd0e59f53d11dca653a93ccaca and 0f3d6ec7a32d815a6391a09ae183886d6a39d901. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `api/anthropicClient.ts` (8 hunks) * `commands/cleanupCommand.ts` (3 hunks) * `main.ts` (4 hunks) * `services/cleanupService.ts` (5 hunks) * `services/modelService.ts` (7 hunks) * `settings.ts` (10 hunks) * `types.ts` (3 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (10)</summary> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `api/anthropicClient.ts` - `settings.ts` - `services/cleanupService.ts` - `commands/cleanupCommand.ts` - `main.ts` - `services/modelService.ts` - `types.ts` </details> <details> <summary>{settings.ts,src/settings.ts}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Provide a settings tab and sensible defaults when the plugin has configuration Files: - `settings.ts` </details> <details> <summary>settings.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence Files: - `settings.ts` </details> <details> <summary>services/cleanupService.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Isolate Anthropic API integration and connection testing in CleanupService Files: - `services/cleanupService.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> <details> <summary>{main.ts,src/main.ts}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{main.ts,src/main.ts}`: Plugin entry point is main.ts, compiled to main.js and loaded by Obsidian > Keep main.ts minimal, focusing on lifecycle (onload, onunload, addCommand) and delegate feature logic > Persist settings using this.loadData() / this.saveData() > Keep startup light; avoid long-running tasks during onload and defer heavy work Files: - `main.ts` </details> <details> <summary>{src/commands/**/*.ts,{main.ts,src/main.ts}}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{src/commands/**/*.ts,{main.ts,src/main.ts}}`: Add user-facing commands via this.addCommand(...) > Use stable command IDs and avoid renaming once released Files: - `main.ts` </details> <details> <summary>{main.ts,src/**/*.ts}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{main.ts,src/**/*.ts}`: Register and clean up DOM/app/interval listeners using this.register* helpers so the plugin unloads safely > Write idempotent load/unload paths so reload/unload doesn’t leak listeners or intervals Files: - `main.ts` </details> <details> <summary>main.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > `main.ts`: Use main.ts as the single entry point for the plugin (compiled to main.js) > Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() Files: - `main.ts` </details> <details> <summary>types.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Centralize TypeScript interfaces and types in types.ts Files: - `types.ts` </details> </details><details> <summary>🧠 Learnings (5)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to settings.ts : Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence ``` **Applied to files:** - `settings.ts` - `main.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:24:39.124Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: AGENTS.md:0-0 Timestamp: 2025-09-26T12:24:39.124Z Learning: Applies to {settings.ts,src/settings.ts} : Provide a settings tab and sensible defaults when the plugin has configuration ``` **Applied to files:** - `settings.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `commands/cleanupCommand.ts` - `main.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `commands/cleanupCommand.ts` - `main.ts` </details> </details><details> <summary>🧬 Code graph analysis (5)</summary> <details> <summary>settings.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `FreewritingCleanupPlugin` (18-134) </details> <details> <summary>services/modelService.ts (1)</summary> * `ModelOption` (11-16) </details> </blockquote></details> <details> <summary>services/cleanupService.ts (1)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (14-374) </details> </blockquote></details> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (15-253) </details> </blockquote></details> <details> <summary>main.ts (3)</summary><blockquote> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `FreewritingCleanupData` (31-34) </details> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (15-253) </details> <details> <summary>commands/cleanupCommand.ts (1)</summary> * `CleanupCommand` (15-174) </details> </blockquote></details> <details> <summary>services/modelService.ts (1)</summary><blockquote> <details> <summary>types.ts (1)</summary> * `ModelCache` (170-175) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (13)</summary><blockquote> <details> <summary>settings.ts (1)</summary><blockquote> `295-328`: **Nice: model refresh handles missing current model.** Good UX preserving selection when possible and falling back deterministically. </blockquote></details> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `57-59`: **Notice persistence confirmed: No changes required.** When timeout is 0, the Notice stays visible until the user manually dismisses it. The implementation is correct. </blockquote></details> <details> <summary>services/cleanupService.ts (5)</summary><blockquote> `8-34`: **LGTM! Clear documentation and solid structure.** The class documentation effectively describes the service's role as an orchestration layer. The exposed getter for `anthropicClient` properly supports integration with ModelService while maintaining encapsulation. --- `38-97`: **LGTM! Comprehensive validation and error handling.** The method properly validates all inputs before making the API call, uses async/await as per coding guidelines, and provides user feedback through notices while still propagating errors appropriately. --- `99-134`: **LGTM! Clean delegation pattern.** The test connection method appropriately validates the API key upfront and gracefully handles errors, returning a structured result suitable for UI feedback. --- `136-200`: **LGTM! Clear utility methods with good validation.** The formatting method produces readable markdown output, and the settings validation comprehensively checks all required fields with helpful error messages. --- `204-252`: **LGTM! Well-documented utility methods.** The static helper methods provide clear functionality with appropriate documentation. The token estimation note about the approximation is helpful context. </blockquote></details> <details> <summary>api/anthropicClient.ts (6)</summary><blockquote> `7-28`: **LGTM! Clear documentation and sensible retry defaults.** The class documentation effectively describes the client's responsibilities, and the retry configuration (3 attempts with 1-second base delay) is appropriate for API resilience. --- `115-173`: **LGTM! Appropriate test design without retry logic.** Good choice to use `makeRequest` directly instead of `makeRequestWithRetry` for connection testing, allowing faster feedback on connectivity issues. --- `177-206`: **LGTM! Solid retry implementation with exponential backoff.** The retry logic correctly implements exponential backoff (1s, 2s, 4s) and provides clear error context when all attempts fail, making the API calls resilient to transient failures. --- `208-242`: **LGTM! Robust marker-based parsing.** The structured response parsing reliably extracts sections using regex markers and provides clear error messages when the expected format is missing. --- `244-340`: **LGTM! Comprehensive API request handling.** All three methods properly handle errors, validate responses, and use async/await. The error messages include helpful context for debugging. --- `342-373`: **LGTM! Clean utility methods.** The helper methods are straightforward and well-documented. The `validateApiKey` method appropriately checks for both presence and non-empty content. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -1,86 +1,187 @@
// ABOUTME: Type definitions for the Freewriting Cleanup plugin
coderabbitai[bot] (Migrated from github.com) commented 2025-10-24 13:27:32 +02:00

🛠️ Refactor suggestion | 🟠 Major

Loosen stop_sequence to match API responses.

Typing stop_sequence strictly as null may break when the API returns a string. Prefer string | null.

-    /** Stop sequence that triggered end (if any) */
-    stop_sequence: null;
+    /** Stop sequence that triggered end (if any) */
+    stop_sequence: string | null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    /** Reason generation stopped */
    stop_reason: string;
    /** Stop sequence that triggered end (if any) */
    stop_sequence: string | null;
    /** Response type */
    type: 'message';
    /** Token usage statistics */
🤖 Prompt for AI Agents
In types.ts around lines 93 to 99, the stop_sequence property is typed as
strictly null which will break when the API returns a string; change its type to
string | null (and update the JSDoc comment to reflect "Stop sequence that
triggered end (if any) — string | null"). Also search for any code assuming
stop_sequence is always null and update checks/usages to handle both string and
null safely.

✅ Addressed in commits ee892b3 to 58abaf7

_🛠️ Refactor suggestion_ | _🟠 Major_ **Loosen stop_sequence to match API responses.** Typing stop_sequence strictly as null may break when the API returns a string. Prefer string | null. ```diff - /** Stop sequence that triggered end (if any) */ - stop_sequence: null; + /** Stop sequence that triggered end (if any) */ + stop_sequence: string | null; ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion /** Reason generation stopped */ stop_reason: string; /** Stop sequence that triggered end (if any) */ stop_sequence: string | null; /** Response type */ type: 'message'; /** Token usage statistics */ ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In types.ts around lines 93 to 99, the stop_sequence property is typed as strictly null which will break when the API returns a string; change its type to string | null (and update the JSDoc comment to reflect "Stop sequence that triggered end (if any) — string | null"). Also search for any code assuming stop_sequence is always null and update checks/usages to handle both string and null safely. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits ee892b3 to 58abaf7
coderabbitai[bot] (Migrated from github.com) commented 2025-10-24 13:27:32 +02:00

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Consider making pagination IDs optional.

Some list endpoints omit first_id/last_id. Marking them optional improves resilience to schema variance.

-    /** ID of first model in list */
-    first_id: string;
+    /** ID of first model in list */
+    first_id?: string;
...
-    /** ID of last model in list */
-    last_id: string;
+    /** ID of last model in list */
+    last_id?: string;

🌐 Web query:

Anthropic models list API: Are first_id/last_id always present? Provide current schema.

💡 Result:

Short answer: Yes — the models-list response always includes the first_id and last_id fields, but they may be null when the page's data array is empty. The current published schema shows first_id and last_id as "string | null".

Schema (excerpt):
{
"data": [ { "id": "string", "type": "model", "display_name": "string", "created_at": "string" } ],
"first_id": "string | null",
"has_more": true,
"last_id": "string | null"
}

Sources: Anthropic List Models docs and the community SDK typing. [1][2]


Change pagination IDs to nullable instead of optional.

The Anthropic models list API always includes first_id and last_id in the response, but they may be null when the data array is empty. These should be typed as string | null (non-optional fields that can be null), not optional properties:

-    /** ID of first model in list */
-    first_id: string;
+    /** ID of first model in list */
+    first_id: string | null;
     /** Whether more models are available */
     has_more: boolean;
-    /** ID of last model in list */
-    last_id: string;
+    /** ID of last model in list */
+    last_id: string | null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export interface ModelsListResponse {
    /** Array of model information */
    data: ModelInfo[];
    /** ID of first model in list */
    first_id: string | null;
    /** Whether more models are available */
    has_more: boolean;
    /** ID of last model in list */
    last_id: string | null;
}
🤖 Prompt for AI Agents
In types.ts around lines 154 to 163, the pagination ID fields are currently
typed as required non-nullable strings; change first_id and last_id to be
non-optional but nullable (string | null) so the type reflects that the API
always includes these keys yet may set them to null when data is empty; update
the interface by replacing the types of first_id and last_id from string to
string | null.

✅ Addressed in commits ee892b3 to 58abaf7

_⚠️ Potential issue_ | _🔴 Critical_ <details> <summary>🧩 Analysis chain</summary> **Consider making pagination IDs optional.** Some list endpoints omit first_id/last_id. Marking them optional improves resilience to schema variance. ```diff - /** ID of first model in list */ - first_id: string; + /** ID of first model in list */ + first_id?: string; ... - /** ID of last model in list */ - last_id: string; + /** ID of last model in list */ + last_id?: string; ``` --- 🌐 Web query: ```web Anthropic models list API: Are first_id/last_id always present? Provide current schema. ``` 💡 Result: Short answer: Yes — the models-list response always includes the first_id and last_id fields, but they may be null when the page's data array is empty. The current published schema shows first_id and last_id as "string | null". Schema (excerpt): { "data": [ { "id": "string", "type": "model", "display_name": "string", "created_at": "string" } ], "first_id": "string | null", "has_more": true, "last_id": "string | null" } Sources: Anthropic List Models docs and the community SDK typing. [1][2] --- </details> **Change pagination IDs to nullable instead of optional.** The Anthropic models list API always includes `first_id` and `last_id` in the response, but they may be `null` when the data array is empty. These should be typed as `string | null` (non-optional fields that can be null), not optional properties: ```diff - /** ID of first model in list */ - first_id: string; + /** ID of first model in list */ + first_id: string | null; /** Whether more models are available */ has_more: boolean; - /** ID of last model in list */ - last_id: string; + /** ID of last model in list */ + last_id: string | null; ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion export interface ModelsListResponse { /** Array of model information */ data: ModelInfo[]; /** ID of first model in list */ first_id: string | null; /** Whether more models are available */ has_more: boolean; /** ID of last model in list */ last_id: string | null; } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In types.ts around lines 154 to 163, the pagination ID fields are currently typed as required non-nullable strings; change first_id and last_id to be non-optional but nullable (string | null) so the type reflects that the API always includes these keys yet may set them to null when data is empty; update the interface by replacing the types of first_id and last_id from string to string | null. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits ee892b3 to 58abaf7
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 15:30:00 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
commands/cleanupCommand.ts (1)

116-122: Remove unused formatSelectedTextInfo method or integrate its output into user feedback.

The formatSelectedTextInfo method is called within validateSelection (line 165) and populates the info field, but this field is never accessed in the execute method—only validation.isValid and validation.error are used (lines 52-54). Either display the info summary to the user via a Notice or remove the unused method and info field from the return type.

🧹 Nitpick comments (4)
commands/cleanupCommand.ts (1)

45-48: Duplicate validation check.

The empty selection validation at lines 45-48 duplicates the check performed by validateSelection at line 51. This creates redundant logic and potential maintenance burden.

Apply this diff to remove the duplicate check:

-        if (!selectedText || selectedText.trim().length === 0) {
-            new Notice('Please select some text to clean up');
-            return;
-        }
-
         // Validate text selection before proceeding
         const validation = this.validateSelection(selectedText);
api/anthropicClient.ts (1)

69-71: Improve error message clarity.

The error message "Custom commentary prompt is required when using custom style" could be more actionable for users.

Apply this diff to clarify the error:

-            } else if (commentaryStyle === 'custom') {
-                throw new Error('Custom commentary prompt is required when using custom style');
+            } else if (commentaryStyle === 'custom') {
+                throw new Error('Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.');
services/modelService.ts (2)

51-58: Simplify toModelInfo by using object spread.

The explicit field assignment in toModelInfo can be more concise using object spread with overrides.

Apply this diff:

     private toModelInfo(opt: ModelOption): ModelInfo {
         return {
-            id: opt.id,
-            display_name: opt.displayName,
+            ...opt,
+            display_name: opt.displayName,
             created_at: '',
             type: 'model'
         };
     }

82-83: Consider consolidating the fallback caching pattern.

The pattern of converting fallback models to ModelInfo and updating cache appears in 4 locations (lines 82, 96, 115, 128). This duplication could be extracted into a helper method.

Add a private helper method:

/**
 * Caches fallback models as ModelInfo for consistency
 * 
 * @returns Array of fallback model options
 */
private cacheFallbackModels(): ModelOption[] {
    const fallback = this.getFallbackModels();
    this.updateCache(fallback.map(f => this.toModelInfo(f)));
    return fallback;
}

Then replace the 4 occurrences with:

-            const fallback = this.getFallbackModels();
-            // Cache fallback models as ModelInfo for consistency
-            this.updateCache(fallback.map(f => this.toModelInfo(f)));
-            return fallback;
+            return this.cacheFallbackModels();

Also applies to: 96-97, 115-116, 128-129

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0f3d6ec7a3 and 58abaf7e91.

📒 Files selected for processing (6)
  • api/anthropicClient.ts (9 hunks)
  • commands/cleanupCommand.ts (6 hunks)
  • main.ts (4 hunks)
  • services/modelService.ts (8 hunks)
  • settings.ts (16 hunks)
  • types.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • settings.ts
🧰 Additional context used
📓 Path-based instructions (7)
{main.ts,src/main.ts}

📄 CodeRabbit inference engine (AGENTS.md)

{main.ts,src/main.ts}: Plugin entry point is main.ts, compiled to main.js and loaded by Obsidian
Keep main.ts minimal, focusing on lifecycle (onload, onunload, addCommand) and delegate feature logic
Persist settings using this.loadData() / this.saveData()
Keep startup light; avoid long-running tasks during onload and defer heavy work

Files:

  • main.ts
{src/commands/**/*.ts,{main.ts,src/main.ts}}

📄 CodeRabbit inference engine (AGENTS.md)

{src/commands/**/*.ts,{main.ts,src/main.ts}}: Add user-facing commands via this.addCommand(...)
Use stable command IDs and avoid renaming once released

Files:

  • main.ts
{main.ts,src/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

{main.ts,src/**/*.ts}: Register and clean up DOM/app/interval listeners using this.register* helpers so the plugin unloads safely
Write idempotent load/unload paths so reload/unload doesn’t leak listeners or intervals

Files:

  • main.ts
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • main.ts
  • commands/cleanupCommand.ts
  • types.ts
  • services/modelService.ts
  • api/anthropicClient.ts
main.ts

📄 CodeRabbit inference engine (CLAUDE.md)

main.ts: Use main.ts as the single entry point for the plugin (compiled to main.js)
Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Files:

  • main.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
types.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize TypeScript interfaces and types in types.ts

Files:

  • types.ts
🧠 Learnings (3)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to settings.ts : Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence

Applied to files:

  • main.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • main.ts
  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • main.ts
  • commands/cleanupCommand.ts
🧬 Code graph analysis (3)
main.ts (4)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • FreewritingCleanupData (31-34)
services/cleanupService.ts (1)
  • CleanupService (15-253)
commands/cleanupCommand.ts (1)
  • CleanupCommand (15-168)
settings.ts (1)
  • DEFAULT_SETTINGS (15-22)
commands/cleanupCommand.ts (2)
services/cleanupService.ts (1)
  • CleanupService (15-253)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • ANTHROPIC_LIMITS (231-238)
services/modelService.ts (2)
api/anthropicClient.ts (1)
  • AnthropicClient (14-376)
types.ts (2)
  • ModelCache (170-175)
  • ModelInfo (138-147)
🔇 Additional comments (11)
commands/cleanupCommand.ts (1)

96-97: LGTM!

The finally block properly ensures the loading notice is hidden regardless of success or error, preventing UI leaks.

api/anthropicClient.ts (2)

189-208: LGTM!

The retry logic with exponential backoff is correctly implemented and provides good resilience against transient API failures.


222-244: LGTM!

The structured response parsing with marker-based extraction is robust and includes proper validation for empty content.

services/modelService.ts (1)

184-190: LGTM!

The throttled error notice implementation effectively prevents notification fatigue while still informing users of persistent issues.

types.ts (3)

95-96: LGTM - Previous review comment addressed.

The stop_sequence field is now correctly typed as string | null, addressing the previous review feedback about API response compatibility.


157-158: LGTM - Previous review comment addressed.

The pagination fields first_id and last_id are now correctly typed as string | null, matching the Anthropic API schema where these fields are always present but may be null when data is empty.

Also applies to: 161-162


4-238: Comprehensive type definitions with excellent documentation.

The entire types file provides a well-structured, well-documented type system for the plugin. All interfaces have clear JSDoc comments, and the types accurately reflect the API contracts.

main.ts (4)

31-50: LGTM - Well-structured plugin initialization.

The onload method properly sequences initialization:

  1. Loads settings and data once
  2. Initializes services with loaded settings
  3. Restores model cache from loaded data (avoiding redundant loadData call)
  4. Registers commands
  5. Adds settings tab

This approach efficiently reuses data and follows Obsidian plugin best practices.

Based on learnings


73-81: Clean settings and cache separation.

The destructuring pattern const { modelCache, ...persisted } = data ?? {} elegantly separates the model cache from settings, maintaining clean type boundaries between FreewritingCleanupSettings and FreewritingCleanupData.


89-101: LGTM - Proper settings persistence with service updates.

The saveSettings method correctly:

  1. Combines settings with current model cache
  2. Persists to storage
  3. Updates the cleanup service with the new API key

This ensures services stay synchronized with settings changes.


114-114: Stable command ID follows best practices.

The command ID 'freewriting-cleanup-cleanup-text' is properly prefixed with the plugin ID to avoid collisions and maintain stability post-release.

As per coding guidelines

**Actionable comments posted: 0** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (1)</summary><blockquote> > > <details> > <summary>commands/cleanupCommand.ts (1)</summary><blockquote> > > `116-122`: **Remove unused `formatSelectedTextInfo` method or integrate its output into user feedback.** > > The `formatSelectedTextInfo` method is called within `validateSelection` (line 165) and populates the `info` field, but this field is never accessed in the `execute` method—only `validation.isValid` and `validation.error` are used (lines 52-54). Either display the info summary to the user via a Notice or remove the unused method and info field from the return type. > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (4)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `45-48`: **Duplicate validation check.** The empty selection validation at lines 45-48 duplicates the check performed by `validateSelection` at line 51. This creates redundant logic and potential maintenance burden. Apply this diff to remove the duplicate check: ```diff - if (!selectedText || selectedText.trim().length === 0) { - new Notice('Please select some text to clean up'); - return; - } - // Validate text selection before proceeding const validation = this.validateSelection(selectedText); ``` </blockquote></details> <details> <summary>api/anthropicClient.ts (1)</summary><blockquote> `69-71`: **Improve error message clarity.** The error message "Custom commentary prompt is required when using custom style" could be more actionable for users. Apply this diff to clarify the error: ```diff - } else if (commentaryStyle === 'custom') { - throw new Error('Custom commentary prompt is required when using custom style'); + } else if (commentaryStyle === 'custom') { + throw new Error('Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.'); ``` </blockquote></details> <details> <summary>services/modelService.ts (2)</summary><blockquote> `51-58`: **Simplify toModelInfo by using object spread.** The explicit field assignment in `toModelInfo` can be more concise using object spread with overrides. Apply this diff: ```diff private toModelInfo(opt: ModelOption): ModelInfo { return { - id: opt.id, - display_name: opt.displayName, + ...opt, + display_name: opt.displayName, created_at: '', type: 'model' }; } ``` --- `82-83`: **Consider consolidating the fallback caching pattern.** The pattern of converting fallback models to ModelInfo and updating cache appears in 4 locations (lines 82, 96, 115, 128). This duplication could be extracted into a helper method. Add a private helper method: ```typescript /** * Caches fallback models as ModelInfo for consistency * * @returns Array of fallback model options */ private cacheFallbackModels(): ModelOption[] { const fallback = this.getFallbackModels(); this.updateCache(fallback.map(f => this.toModelInfo(f))); return fallback; } ``` Then replace the 4 occurrences with: ```diff - const fallback = this.getFallbackModels(); - // Cache fallback models as ModelInfo for consistency - this.updateCache(fallback.map(f => this.toModelInfo(f))); - return fallback; + return this.cacheFallbackModels(); ``` Also applies to: 96-97, 115-116, 128-129 </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 0f3d6ec7a32d815a6391a09ae183886d6a39d901 and 58abaf7e9136177bc472e286456e0a41bf1f4909. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `api/anthropicClient.ts` (9 hunks) * `commands/cleanupCommand.ts` (6 hunks) * `main.ts` (4 hunks) * `services/modelService.ts` (8 hunks) * `settings.ts` (16 hunks) * `types.ts` (3 hunks) </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * settings.ts </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (7)</summary> <details> <summary>{main.ts,src/main.ts}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{main.ts,src/main.ts}`: Plugin entry point is main.ts, compiled to main.js and loaded by Obsidian > Keep main.ts minimal, focusing on lifecycle (onload, onunload, addCommand) and delegate feature logic > Persist settings using this.loadData() / this.saveData() > Keep startup light; avoid long-running tasks during onload and defer heavy work Files: - `main.ts` </details> <details> <summary>{src/commands/**/*.ts,{main.ts,src/main.ts}}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{src/commands/**/*.ts,{main.ts,src/main.ts}}`: Add user-facing commands via this.addCommand(...) > Use stable command IDs and avoid renaming once released Files: - `main.ts` </details> <details> <summary>{main.ts,src/**/*.ts}</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > `{main.ts,src/**/*.ts}`: Register and clean up DOM/app/interval listeners using this.register* helpers so the plugin unloads safely > Write idempotent load/unload paths so reload/unload doesn’t leak listeners or intervals Files: - `main.ts` </details> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `main.ts` - `commands/cleanupCommand.ts` - `types.ts` - `services/modelService.ts` - `api/anthropicClient.ts` </details> <details> <summary>main.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > `main.ts`: Use main.ts as the single entry point for the plugin (compiled to main.js) > Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() Files: - `main.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> <details> <summary>types.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Centralize TypeScript interfaces and types in types.ts Files: - `types.ts` </details> </details><details> <summary>🧠 Learnings (3)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to settings.ts : Implement settings UI and defaults in settings.ts using FreewritingCleanupSettings with loadData/saveData persistence ``` **Applied to files:** - `main.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `main.ts` - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `main.ts` - `commands/cleanupCommand.ts` </details> </details><details> <summary>🧬 Code graph analysis (3)</summary> <details> <summary>main.ts (4)</summary><blockquote> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `FreewritingCleanupData` (31-34) </details> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (15-253) </details> <details> <summary>commands/cleanupCommand.ts (1)</summary> * `CleanupCommand` (15-168) </details> <details> <summary>settings.ts (1)</summary> * `DEFAULT_SETTINGS` (15-22) </details> </blockquote></details> <details> <summary>commands/cleanupCommand.ts (2)</summary><blockquote> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (15-253) </details> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `ANTHROPIC_LIMITS` (231-238) </details> </blockquote></details> <details> <summary>services/modelService.ts (2)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (14-376) </details> <details> <summary>types.ts (2)</summary> * `ModelCache` (170-175) * `ModelInfo` (138-147) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (11)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `96-97`: **LGTM!** The `finally` block properly ensures the loading notice is hidden regardless of success or error, preventing UI leaks. </blockquote></details> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> `189-208`: **LGTM!** The retry logic with exponential backoff is correctly implemented and provides good resilience against transient API failures. --- `222-244`: **LGTM!** The structured response parsing with marker-based extraction is robust and includes proper validation for empty content. </blockquote></details> <details> <summary>services/modelService.ts (1)</summary><blockquote> `184-190`: **LGTM!** The throttled error notice implementation effectively prevents notification fatigue while still informing users of persistent issues. </blockquote></details> <details> <summary>types.ts (3)</summary><blockquote> `95-96`: **LGTM - Previous review comment addressed.** The `stop_sequence` field is now correctly typed as `string | null`, addressing the previous review feedback about API response compatibility. --- `157-158`: **LGTM - Previous review comment addressed.** The pagination fields `first_id` and `last_id` are now correctly typed as `string | null`, matching the Anthropic API schema where these fields are always present but may be null when data is empty. Also applies to: 161-162 --- `4-238`: **Comprehensive type definitions with excellent documentation.** The entire types file provides a well-structured, well-documented type system for the plugin. All interfaces have clear JSDoc comments, and the types accurately reflect the API contracts. </blockquote></details> <details> <summary>main.ts (4)</summary><blockquote> `31-50`: **LGTM - Well-structured plugin initialization.** The `onload` method properly sequences initialization: 1. Loads settings and data once 2. Initializes services with loaded settings 3. Restores model cache from loaded data (avoiding redundant loadData call) 4. Registers commands 5. Adds settings tab This approach efficiently reuses data and follows Obsidian plugin best practices. Based on learnings --- `73-81`: **Clean settings and cache separation.** The destructuring pattern `const { modelCache, ...persisted } = data ?? {}` elegantly separates the model cache from settings, maintaining clean type boundaries between `FreewritingCleanupSettings` and `FreewritingCleanupData`. --- `89-101`: **LGTM - Proper settings persistence with service updates.** The `saveSettings` method correctly: 1. Combines settings with current model cache 2. Persists to storage 3. Updates the cleanup service with the new API key This ensures services stay synchronized with settings changes. --- `114-114`: **Stable command ID follows best practices.** The command ID `'freewriting-cleanup-cleanup-text'` is properly prefixed with the plugin ID to avoid collisions and maintain stability post-release. As per coding guidelines </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 15:47:54 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 0

🧹 Nitpick comments (1)
commands/cleanupCommand.ts (1)

74-90: Consider using custom error types for more robust error handling.

The string matching on error messages (lines 77, 79, 81) is fragile and could break if error messages change. Consider defining custom error classes or using error codes for more reliable error type detection.

Example approach:

// In a new errors.ts file
export class ApiKeyError extends Error {
    constructor(message: string) {
        super(message);
        this.name = 'ApiKeyError';
    }
}

export class TextTooLongError extends Error {
    constructor(message: string) {
        super(message);
        this.name = 'TextTooLongError';
    }
}

// In error handling
if (error instanceof ApiKeyError) {
    new Notice('API key error. Please check your settings.');
} else if (error instanceof TextTooLongError) {
    new Notice('Text is too long for processing.');
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58abaf7e91 and ecb57d794c.

📒 Files selected for processing (3)
  • api/anthropicClient.ts (9 hunks)
  • commands/cleanupCommand.ts (4 hunks)
  • services/modelService.ts (8 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • api/anthropicClient.ts
  • commands/cleanupCommand.ts
  • services/modelService.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
🧠 Learnings (2)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • commands/cleanupCommand.ts
🧬 Code graph analysis (2)
commands/cleanupCommand.ts (2)
services/cleanupService.ts (1)
  • CleanupService (15-253)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • ANTHROPIC_LIMITS (231-238)
services/modelService.ts (2)
api/anthropicClient.ts (1)
  • AnthropicClient (14-376)
types.ts (2)
  • ModelCache (170-175)
  • ModelInfo (138-147)
🔇 Additional comments (12)
commands/cleanupCommand.ts (5)

6-6: LGTM! Consistent use of shared constants.

The ANTHROPIC_LIMITS import centralizes limit values and is properly used in validation error messages.


8-14: Excellent documentation coverage.

The JSDoc comments are comprehensive, well-structured, and provide clear context for class purpose, method behaviors, parameters, and return values.

Also applies to: 18-22, 29-39, 102-110


40-40: Good use of naming convention for unused parameters.

The underscore prefix clearly indicates the parameter is unused while maintaining the required callback signature for Obsidian's editorCallback.


53-53: Proper resource cleanup with finally block.

The persistent loading notice with cleanup in the finally block ensures the UI is always restored, preventing orphaned notices in error scenarios.

Also applies to: 91-93


111-141: Well-structured validation with excellent user feedback.

The validation logic properly checks empty text and API limits, and provides clear error messages with formatted counts using toLocaleString(). The streamlined return type (removed info field) keeps the interface focused.

api/anthropicClient.ts (3)

7-28: Excellent documentation and structure!

The comprehensive JSDoc comments significantly improve code readability. The class documentation clearly explains purpose, responsibilities, and key features (retry logic, error handling, structured parsing).


64-74: Solid validation for custom commentary prompts.

The validation logic correctly ensures that when commentaryStyle is 'custom', a customCommentaryPrompt must be provided. The error message is clear and actionable for developers integrating this API.


189-208: Well-implemented retry logic with exponential backoff.

The retry mechanism correctly implements exponential backoff (1s, 2s, 4s delays) and provides clear error messages. This makes the API client resilient to transient failures.

services/modelService.ts (4)

8-40: Excellent documentation and UX improvement with error throttling.

The comprehensive JSDoc comments clearly explain the caching strategy, TTL behavior, and fallback mechanisms. The addition of error notice throttling (lines 30-31) is a thoughtful UX enhancement that prevents notification fatigue when the API is persistently unavailable.


51-58: Helper method maintains consistent cache structure.

The toModelInfo method correctly converts fallback models to ModelInfo format for caching. Using empty strings for metadata fields like created_at is acceptable since these are fallback models without real API metadata, and formatModels only uses the id and display_name fields for UI display.


72-119: Well-structured caching and fallback logic.

Both methods handle the cache lifecycle correctly:

  • getAvailableModels leverages cache to minimize API calls
  • refreshModels bypasses cache for explicit refreshes
  • Both gracefully handle missing API keys without error notices (an expected state)
  • API failures trigger throttled notices and fallback to hardcoded models

The implementation ensures the UI always has model options available, even during offline use or before API key configuration.


175-245: Clean helper methods reduce duplication and improve maintainability.

The private helper methods are well-designed:

  • cacheFallbackModels() consolidates the common fallback pattern (used in 4 places)
  • showThrottledErrorNotice() implements proper notification throttling
  • formatModels() ensures alphabetically sorted results for consistent UX

The implementation follows DRY principles and maintains good separation of concerns.

**Actionable comments posted: 0** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `74-90`: **Consider using custom error types for more robust error handling.** The string matching on error messages (lines 77, 79, 81) is fragile and could break if error messages change. Consider defining custom error classes or using error codes for more reliable error type detection. Example approach: ```typescript // In a new errors.ts file export class ApiKeyError extends Error { constructor(message: string) { super(message); this.name = 'ApiKeyError'; } } export class TextTooLongError extends Error { constructor(message: string) { super(message); this.name = 'TextTooLongError'; } } // In error handling if (error instanceof ApiKeyError) { new Notice('API key error. Please check your settings.'); } else if (error instanceof TextTooLongError) { new Notice('Text is too long for processing.'); } ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 58abaf7e9136177bc472e286456e0a41bf1f4909 and ecb57d794ce9e74c70d4ae66839d48ca95a07b3d. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `api/anthropicClient.ts` (9 hunks) * `commands/cleanupCommand.ts` (4 hunks) * `services/modelService.ts` (8 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (2)</summary> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `api/anthropicClient.ts` - `commands/cleanupCommand.ts` - `services/modelService.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> </details><details> <summary>🧠 Learnings (2)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> </details><details> <summary>🧬 Code graph analysis (2)</summary> <details> <summary>commands/cleanupCommand.ts (2)</summary><blockquote> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (15-253) </details> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `ANTHROPIC_LIMITS` (231-238) </details> </blockquote></details> <details> <summary>services/modelService.ts (2)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (14-376) </details> <details> <summary>types.ts (2)</summary> * `ModelCache` (170-175) * `ModelInfo` (138-147) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (12)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (5)</summary><blockquote> `6-6`: **LGTM! Consistent use of shared constants.** The ANTHROPIC_LIMITS import centralizes limit values and is properly used in validation error messages. --- `8-14`: **Excellent documentation coverage.** The JSDoc comments are comprehensive, well-structured, and provide clear context for class purpose, method behaviors, parameters, and return values. Also applies to: 18-22, 29-39, 102-110 --- `40-40`: **Good use of naming convention for unused parameters.** The underscore prefix clearly indicates the parameter is unused while maintaining the required callback signature for Obsidian's editorCallback. --- `53-53`: **Proper resource cleanup with finally block.** The persistent loading notice with cleanup in the finally block ensures the UI is always restored, preventing orphaned notices in error scenarios. Also applies to: 91-93 --- `111-141`: **Well-structured validation with excellent user feedback.** The validation logic properly checks empty text and API limits, and provides clear error messages with formatted counts using `toLocaleString()`. The streamlined return type (removed info field) keeps the interface focused. </blockquote></details> <details> <summary>api/anthropicClient.ts (3)</summary><blockquote> `7-28`: **Excellent documentation and structure!** The comprehensive JSDoc comments significantly improve code readability. The class documentation clearly explains purpose, responsibilities, and key features (retry logic, error handling, structured parsing). --- `64-74`: **Solid validation for custom commentary prompts.** The validation logic correctly ensures that when `commentaryStyle` is 'custom', a `customCommentaryPrompt` must be provided. The error message is clear and actionable for developers integrating this API. --- `189-208`: **Well-implemented retry logic with exponential backoff.** The retry mechanism correctly implements exponential backoff (1s, 2s, 4s delays) and provides clear error messages. This makes the API client resilient to transient failures. </blockquote></details> <details> <summary>services/modelService.ts (4)</summary><blockquote> `8-40`: **Excellent documentation and UX improvement with error throttling.** The comprehensive JSDoc comments clearly explain the caching strategy, TTL behavior, and fallback mechanisms. The addition of error notice throttling (lines 30-31) is a thoughtful UX enhancement that prevents notification fatigue when the API is persistently unavailable. --- `51-58`: **Helper method maintains consistent cache structure.** The `toModelInfo` method correctly converts fallback models to `ModelInfo` format for caching. Using empty strings for metadata fields like `created_at` is acceptable since these are fallback models without real API metadata, and `formatModels` only uses the `id` and `display_name` fields for UI display. --- `72-119`: **Well-structured caching and fallback logic.** Both methods handle the cache lifecycle correctly: - `getAvailableModels` leverages cache to minimize API calls - `refreshModels` bypasses cache for explicit refreshes - Both gracefully handle missing API keys without error notices (an expected state) - API failures trigger throttled notices and fallback to hardcoded models The implementation ensures the UI always has model options available, even during offline use or before API key configuration. --- `175-245`: **Clean helper methods reduce duplication and improve maintainability.** The private helper methods are well-designed: - `cacheFallbackModels()` consolidates the common fallback pattern (used in 4 places) - `showThrottledErrorNotice()` implements proper notification throttling - `formatModels()` ensures alphabetically sorted results for consistent UX The implementation follows DRY principles and maintains good separation of concerns. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 15:57:28 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
services/cleanupService.ts (1)

93-97: Potential duplicate error notices shown to users.

The error handling here shows a Notice (line 95) and then rethrows the error. The calling code in commands/cleanupCommand.ts (lines 75-87) also catches these errors and shows notices. This could result in duplicate error messages being displayed to users.

Consider one of these approaches:

  1. Remove the Notice here and let the command layer handle all user feedback
  2. Don't rethrow after showing the Notice
  3. Add a flag to indicate the error has been displayed
         } catch (error) {
-            const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
-            new Notice(`Text cleanup failed: ${errorMessage}`);
             throw error;
         }
🧹 Nitpick comments (2)
commands/cleanupCommand.ts (1)

75-87: Consider more specific error messages for better UX.

The error handling correctly uses typed errors with instanceof checks. However, the user-facing messages for TextTooLongError (line 80) and ServiceUnavailableError (line 82) are somewhat generic. The validateSelection method already provides detailed character and token counts, which could help users understand the issue better.

Consider extracting the detailed message from the error itself:

 } else if (error instanceof TextTooLongError) {
-    new Notice('Text is too long for processing.');
+    new Notice(error.message);
 } else if (error instanceof ServiceUnavailableError) {
-    new Notice('Service temporarily unavailable. Please try again.');
+    new Notice(error.message);

This would show users the actual character/token counts and limits from the error message.

api/anthropicClient.ts (1)

198-217: Consider selective retry based on error type.

The retry logic currently retries all errors indiscriminately. However, some errors (like authentication failures with 401 status, or client errors with 4xx status codes) are not transient and shouldn't be retried. This can lead to unnecessary delays and API quota consumption.

Consider checking the error type before retrying:

         for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) {
             try {
                 const response = await this.makeRequest(request);
                 return response;
             } catch (error) {
                 lastError = error instanceof Error ? error : new Error('Unknown error');
+
+                // Don't retry client errors (ApiKeyError, ConfigurationError, ApiError with 4xx status)
+                if (error instanceof ApiKeyError || error instanceof ConfigurationError) {
+                    throw error;
+                }
+                if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500) {
+                    throw error;
+                }
 
                 if (attempt < this.MAX_RETRIES) {

This ensures only transient failures (network errors, 5xx server errors) are retried.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ecb57d794c and e29539c8eb.

📒 Files selected for processing (4)
  • api/anthropicClient.ts (8 hunks)
  • commands/cleanupCommand.ts (4 hunks)
  • errors.ts (1 hunks)
  • services/cleanupService.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • commands/cleanupCommand.ts
  • api/anthropicClient.ts
  • errors.ts
  • services/cleanupService.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
services/cleanupService.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Isolate Anthropic API integration and connection testing in CleanupService

Files:

  • services/cleanupService.ts
🧠 Learnings (3)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.ts
🧬 Code graph analysis (3)
commands/cleanupCommand.ts (3)
services/cleanupService.ts (1)
  • CleanupService (16-254)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • ANTHROPIC_LIMITS (231-238)
errors.ts (3)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ServiceUnavailableError (38-38)
api/anthropicClient.ts (2)
errors.ts (7)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ConfigurationError (52-52)
  • ServiceUnavailableError (38-38)
  • InvalidResponseError (45-45)
  • ApiError (66-74)
  • NetworkError (59-59)
types.ts (3)
  • ANTHROPIC_LIMITS (231-238)
  • ModelsListResponse (154-163)
  • AnthropicResponse (79-106)
services/cleanupService.ts (3)
api/anthropicClient.ts (1)
  • AnthropicClient (23-385)
types.ts (3)
  • FreewritingCleanupSettings (10-23)
  • CleanupResult (113-131)
  • ANTHROPIC_LIMITS (231-238)
errors.ts (2)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
🔇 Additional comments (10)
errors.ts (1)

1-74: LGTM! Well-structured error hierarchy.

The custom error types provide type-safe error categorization across the plugin. The use of Object.setPrototypeOf in the base class ensures proper prototype chain maintenance for instanceof checks in transpiled code. The ApiError class appropriately captures additional context (status code and response body) for detailed error reporting.

commands/cleanupCommand.ts (2)

1-26: LGTM! Clean imports and dependency injection.

The imports are well-organized, bringing in typed errors for robust error handling and constants for validation. The constructor-based service injection follows good dependency injection practices.


110-140: LGTM! Clear validation logic with user-friendly formatting.

The validation correctly checks for empty text and both character and token limits. The use of toLocaleString() provides good UX by formatting large numbers with thousands separators. The return type with an optional error field is appropriate for this use case.

services/cleanupService.ts (3)

16-35: LGTM! Clean service initialization.

The getter appropriately exposes the underlying client for use by ModelService, and the constructor properly initializes the AnthropicClient with the provided API key.


109-154: LGTM! Clean service methods.

The testConnection method appropriately wraps the client's test functionality with error handling, and formatCleanupResult produces well-formatted markdown output with clear section separators.


166-253: LGTM! Well-organized utility methods.

The configuration and utility methods are clean and focused. The static utilities provide clear separation of concerns, and the token estimation (1 token ≈ 4 characters) is a reasonable approximation for user feedback purposes.

api/anthropicClient.ts (4)

57-124: LGTM! Robust text cleanup implementation.

The method properly validates inputs, constructs a well-structured prompt with explicit output markers, and uses typed errors for different failure scenarios. The commentary handling correctly requires a custom prompt when the custom style is selected.


136-184: LGTM! Clean connection test implementation.

The test connection method appropriately validates the API key format before making a minimal test request. The inclusion of timing and token usage details provides valuable diagnostic information.


231-328: LGTM! Solid parsing and request handling.

The marker-based parsing provides reliable extraction of cleaned text and commentary. The HTTP request methods appropriately map different failure scenarios to typed errors (ApiError for non-2xx responses, NetworkError for network failures).


340-384: LGTM! Clean utility and configuration methods.

The response extraction properly validates content, and the configuration methods provide straightforward API key management. The sleep utility is correctly implemented for retry delays.

**Actionable comments posted: 0** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (1)</summary><blockquote> > > <details> > <summary>services/cleanupService.ts (1)</summary><blockquote> > > `93-97`: **Potential duplicate error notices shown to users.** > > The error handling here shows a Notice (line 95) and then rethrows the error. The calling code in `commands/cleanupCommand.ts` (lines 75-87) also catches these errors and shows notices. This could result in duplicate error messages being displayed to users. > > > > Consider one of these approaches: > 1. Remove the Notice here and let the command layer handle all user feedback > 2. Don't rethrow after showing the Notice > 3. Add a flag to indicate the error has been displayed > > ```diff > } catch (error) { > - const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; > - new Notice(`Text cleanup failed: ${errorMessage}`); > throw error; > } > ``` > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `75-87`: **Consider more specific error messages for better UX.** The error handling correctly uses typed errors with `instanceof` checks. However, the user-facing messages for `TextTooLongError` (line 80) and `ServiceUnavailableError` (line 82) are somewhat generic. The `validateSelection` method already provides detailed character and token counts, which could help users understand the issue better. Consider extracting the detailed message from the error itself: ```diff } else if (error instanceof TextTooLongError) { - new Notice('Text is too long for processing.'); + new Notice(error.message); } else if (error instanceof ServiceUnavailableError) { - new Notice('Service temporarily unavailable. Please try again.'); + new Notice(error.message); ``` This would show users the actual character/token counts and limits from the error message. </blockquote></details> <details> <summary>api/anthropicClient.ts (1)</summary><blockquote> `198-217`: **Consider selective retry based on error type.** The retry logic currently retries all errors indiscriminately. However, some errors (like authentication failures with 401 status, or client errors with 4xx status codes) are not transient and shouldn't be retried. This can lead to unnecessary delays and API quota consumption. Consider checking the error type before retrying: ```diff for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) { try { const response = await this.makeRequest(request); return response; } catch (error) { lastError = error instanceof Error ? error : new Error('Unknown error'); + + // Don't retry client errors (ApiKeyError, ConfigurationError, ApiError with 4xx status) + if (error instanceof ApiKeyError || error instanceof ConfigurationError) { + throw error; + } + if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500) { + throw error; + } if (attempt < this.MAX_RETRIES) { ``` This ensures only transient failures (network errors, 5xx server errors) are retried. </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between ecb57d794ce9e74c70d4ae66839d48ca95a07b3d and e29539c8ebfe739661c607403cbb81ab3a3f91ee. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `api/anthropicClient.ts` (8 hunks) * `commands/cleanupCommand.ts` (4 hunks) * `errors.ts` (1 hunks) * `services/cleanupService.ts` (5 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (3)</summary> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `commands/cleanupCommand.ts` - `api/anthropicClient.ts` - `errors.ts` - `services/cleanupService.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> <details> <summary>services/cleanupService.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Isolate Anthropic API integration and connection testing in CleanupService Files: - `services/cleanupService.ts` </details> </details><details> <summary>🧠 Learnings (3)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.ts` </details> </details><details> <summary>🧬 Code graph analysis (3)</summary> <details> <summary>commands/cleanupCommand.ts (3)</summary><blockquote> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (16-254) </details> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `ANTHROPIC_LIMITS` (231-238) </details> <details> <summary>errors.ts (3)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ServiceUnavailableError` (38-38) </details> </blockquote></details> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> <details> <summary>errors.ts (7)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ConfigurationError` (52-52) * `ServiceUnavailableError` (38-38) * `InvalidResponseError` (45-45) * `ApiError` (66-74) * `NetworkError` (59-59) </details> <details> <summary>types.ts (3)</summary> * `ANTHROPIC_LIMITS` (231-238) * `ModelsListResponse` (154-163) * `AnthropicResponse` (79-106) </details> </blockquote></details> <details> <summary>services/cleanupService.ts (3)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (23-385) </details> <details> <summary>types.ts (3)</summary> * `FreewritingCleanupSettings` (10-23) * `CleanupResult` (113-131) * `ANTHROPIC_LIMITS` (231-238) </details> <details> <summary>errors.ts (2)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (10)</summary><blockquote> <details> <summary>errors.ts (1)</summary><blockquote> `1-74`: **LGTM! Well-structured error hierarchy.** The custom error types provide type-safe error categorization across the plugin. The use of `Object.setPrototypeOf` in the base class ensures proper prototype chain maintenance for `instanceof` checks in transpiled code. The `ApiError` class appropriately captures additional context (status code and response body) for detailed error reporting. </blockquote></details> <details> <summary>commands/cleanupCommand.ts (2)</summary><blockquote> `1-26`: **LGTM! Clean imports and dependency injection.** The imports are well-organized, bringing in typed errors for robust error handling and constants for validation. The constructor-based service injection follows good dependency injection practices. --- `110-140`: **LGTM! Clear validation logic with user-friendly formatting.** The validation correctly checks for empty text and both character and token limits. The use of `toLocaleString()` provides good UX by formatting large numbers with thousands separators. The return type with an optional `error` field is appropriate for this use case. </blockquote></details> <details> <summary>services/cleanupService.ts (3)</summary><blockquote> `16-35`: **LGTM! Clean service initialization.** The getter appropriately exposes the underlying client for use by `ModelService`, and the constructor properly initializes the `AnthropicClient` with the provided API key. --- `109-154`: **LGTM! Clean service methods.** The `testConnection` method appropriately wraps the client's test functionality with error handling, and `formatCleanupResult` produces well-formatted markdown output with clear section separators. --- `166-253`: **LGTM! Well-organized utility methods.** The configuration and utility methods are clean and focused. The static utilities provide clear separation of concerns, and the token estimation (1 token ≈ 4 characters) is a reasonable approximation for user feedback purposes. </blockquote></details> <details> <summary>api/anthropicClient.ts (4)</summary><blockquote> `57-124`: **LGTM! Robust text cleanup implementation.** The method properly validates inputs, constructs a well-structured prompt with explicit output markers, and uses typed errors for different failure scenarios. The commentary handling correctly requires a custom prompt when the custom style is selected. --- `136-184`: **LGTM! Clean connection test implementation.** The test connection method appropriately validates the API key format before making a minimal test request. The inclusion of timing and token usage details provides valuable diagnostic information. --- `231-328`: **LGTM! Solid parsing and request handling.** The marker-based parsing provides reliable extraction of cleaned text and commentary. The HTTP request methods appropriately map different failure scenarios to typed errors (`ApiError` for non-2xx responses, `NetworkError` for network failures). --- `340-384`: **LGTM! Clean utility and configuration methods.** The response extraction properly validates content, and the configuration methods provide straightforward API key management. The `sleep` utility is correctly implemented for retry delays. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 16:15:57 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
commands/cleanupCommand.ts (1)

63-75: Insert result at selection end, not end-of-line

If selection ends mid-line, inserting at line end places output after unselected trailing text. Insert at the selection end to truly place “below the selection.”

Apply:

-                const selectionEnd = editor.getCursor('to');
-                // Insert the formatted result below the selected text
-                const insertPosition = {
-                    line: selectionEnd.line,
-                    ch: editor.getLine(selectionEnd.line).length
-                };
-
-                // Move to end of current line and insert new content
-                editor.setCursor(insertPosition);
-                editor.replaceRange(formattedResult, insertPosition);
+                const insertPosition = editor.getCursor('to');
+                editor.replaceRange(formattedResult, insertPosition);
🧹 Nitpick comments (7)
commands/cleanupCommand.ts (1)

76-85: Handle more specific API errors (401/403, 429, invalid/ network)

Map known error types/status for clearer user notices and resilience.

Apply:

-import { ApiKeyError, TextTooLongError, ServiceUnavailableError } from '../errors';
+import { ApiKeyError, TextTooLongError, ServiceUnavailableError, ApiError, InvalidResponseError, NetworkError } from '../errors';
@@
-            } catch (error) {
+            } catch (error) {
                 // 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 && (error.status === 401 || error.status === 403)) {
+                    new Notice('API key was rejected by the server. Please verify your key.');
+                } else if (error instanceof ApiError && error.status === 429) {
+                    new Notice('Rate limited by API. Please wait and try again.');
                 } 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}`);
services/cleanupService.ts (3)

89-92: Keep services UI-agnostic; move success Notice to command

Emitting Notice here mixes UI into the service layer. Return timing (or let the command compute it) and surface the success toast in the command.

Apply:

-            const duration = Date.now() - startTime;
-            new Notice(`Text cleanup completed in ${(duration / 1000).toFixed(1)}s`);
+            // Command layer can compute/show timing notice if desired.

As per coding guidelines (service isolation).


169-200: Validate custom commentary prompt when style is 'custom'

Prevent downstream configuration errors earlier.

Apply:

     validateSettings(settings: FreewritingCleanupSettings): {
         isValid: boolean;
         errors: string[];
     } {
         const errors: string[] = [];
@@
         if (!settings.cleanupPrompt || settings.cleanupPrompt.trim().length === 0) {
             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
         };

228-252: Token estimate is coarse; consider headroom

Optional: subtract a small safety margin (e.g., 5–10%) or surface the estimate + limit in the validation error to reduce near-limit failures.

api/anthropicClient.ts (3)

200-229: Retry 429 Too Many Requests; keep other 4xx non-retryable

Treating 429 as retryable improves resilience under transient rate limits.

Apply:

-                if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500) {
+                if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500 && error.status !== 429) {
                     throw error;
                 }

Optionally read Retry-After when available in follow-up.

Also applies to: 210-218


327-333: Map 401/403 to ApiKeyError and 429 to ServiceUnavailableError

Clearer semantics upstream; better user notices.

Apply:

-            if (response.status < 200 || response.status >= 300) {
-                const errorBody = response.text || 'Unknown error';
-                throw new ApiError(`API request failed (${response.status}): ${errorBody}`, response.status, errorBody);
-            }
+            if (response.status < 200 || response.status >= 300) {
+                const errorBody = response.text || 'Unknown error';
+                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);
+            }

351-359: Concatenate all text blocks in response

Anthropic can return multiple text blocks; only reading index 0 may truncate output.

Apply:

-        const text = response.content[0].text;
-        if (!text || text.trim().length === 0) {
+        const text = response.content.map(c => c.text ?? '').join('').trim();
+        if (!text) {
             throw new InvalidResponseError('Empty response from API');
         }
 
-        return text.trim();
+        return text;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e29539c8eb and 306e6819a3.

📒 Files selected for processing (3)
  • api/anthropicClient.ts (9 hunks)
  • commands/cleanupCommand.ts (4 hunks)
  • services/cleanupService.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • services/cleanupService.ts
  • commands/cleanupCommand.ts
  • api/anthropicClient.ts
services/cleanupService.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Isolate Anthropic API integration and connection testing in CleanupService

Files:

  • services/cleanupService.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
🧠 Learnings (3)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • commands/cleanupCommand.ts
🧬 Code graph analysis (3)
services/cleanupService.ts (3)
api/anthropicClient.ts (1)
  • AnthropicClient (23-396)
types.ts (3)
  • FreewritingCleanupSettings (10-23)
  • CleanupResult (113-131)
  • ANTHROPIC_LIMITS (231-238)
errors.ts (2)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
commands/cleanupCommand.ts (3)
services/cleanupService.ts (1)
  • CleanupService (16-253)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • ANTHROPIC_LIMITS (231-238)
errors.ts (3)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ServiceUnavailableError (38-38)
api/anthropicClient.ts (2)
errors.ts (7)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ConfigurationError (52-52)
  • ApiError (66-74)
  • ServiceUnavailableError (38-38)
  • InvalidResponseError (45-45)
  • NetworkError (59-59)
types.ts (3)
  • ANTHROPIC_LIMITS (231-238)
  • ModelsListResponse (154-163)
  • AnthropicResponse (79-106)
🔇 Additional comments (6)
commands/cleanupCommand.ts (3)

54-55: Loading notice lifecycle: good

Persistent notice + finally hide prevents leaks. LGTM.


101-139: Validation UX looks solid

Clear messages with localized counts and both char/token checks. LGTM.


41-41: Command signature wiring is correct

The execute method receives the correct parameters via proper service injection. The editorCallback invokes executeCleanupCommand(editor, view), which then delegates to this.cleanupCommand.execute(editor, view, this.settings) at main.ts:135. The settings parameter is correctly supplied through the plugin's instance context and passed as the third argument to execute().

services/cleanupService.ts (1)

50-63: Good: explicit ApiKeyError/TextTooLongError with precise counts

Clear signals and domain errors. LGTM.

api/anthropicClient.ts (2)

126-184: testConnection: concise and helpful

Good validation, timing details, and error mapping. LGTM.


266-303: fetchModels: headers and error handling look right

Straightforward GET with version header and ApiError mapping. LGTM.

**Actionable comments posted: 0** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (1)</summary><blockquote> > > <details> > <summary>commands/cleanupCommand.ts (1)</summary><blockquote> > > `63-75`: **Insert result at selection end, not end-of-line** > > If selection ends mid-line, inserting at line end places output after unselected trailing text. Insert at the selection end to truly place “below the selection.” > > Apply: > > ```diff > - const selectionEnd = editor.getCursor('to'); > - // Insert the formatted result below the selected text > - const insertPosition = { > - line: selectionEnd.line, > - ch: editor.getLine(selectionEnd.line).length > - }; > - > - // Move to end of current line and insert new content > - editor.setCursor(insertPosition); > - editor.replaceRange(formattedResult, insertPosition); > + const insertPosition = editor.getCursor('to'); > + editor.replaceRange(formattedResult, insertPosition); > ``` > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (7)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `76-85`: **Handle more specific API errors (401/403, 429, invalid/ network)** Map known error types/status for clearer user notices and resilience. Apply: ```diff -import { ApiKeyError, TextTooLongError, ServiceUnavailableError } from '../errors'; +import { ApiKeyError, TextTooLongError, ServiceUnavailableError, ApiError, InvalidResponseError, NetworkError } from '../errors'; @@ - } catch (error) { + } catch (error) { // 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 && (error.status === 401 || error.status === 403)) { + new Notice('API key was rejected by the server. Please verify your key.'); + } else if (error instanceof ApiError && error.status === 429) { + new Notice('Rate limited by API. Please wait and try again.'); } 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}`); ``` </blockquote></details> <details> <summary>services/cleanupService.ts (3)</summary><blockquote> `89-92`: **Keep services UI-agnostic; move success Notice to command** Emitting Notice here mixes UI into the service layer. Return timing (or let the command compute it) and surface the success toast in the command. Apply: ```diff - const duration = Date.now() - startTime; - new Notice(`Text cleanup completed in ${(duration / 1000).toFixed(1)}s`); + // Command layer can compute/show timing notice if desired. ``` As per coding guidelines (service isolation). --- `169-200`: **Validate custom commentary prompt when style is 'custom'** Prevent downstream configuration errors earlier. Apply: ```diff validateSettings(settings: FreewritingCleanupSettings): { isValid: boolean; errors: string[]; } { const errors: string[] = []; @@ if (!settings.cleanupPrompt || settings.cleanupPrompt.trim().length === 0) { 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 }; ``` --- `228-252`: **Token estimate is coarse; consider headroom** Optional: subtract a small safety margin (e.g., 5–10%) or surface the estimate + limit in the validation error to reduce near-limit failures. </blockquote></details> <details> <summary>api/anthropicClient.ts (3)</summary><blockquote> `200-229`: **Retry 429 Too Many Requests; keep other 4xx non-retryable** Treating 429 as retryable improves resilience under transient rate limits. Apply: ```diff - if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500) { + if (error instanceof ApiError && error.status && error.status >= 400 && error.status < 500 && error.status !== 429) { throw error; } ``` Optionally read Retry-After when available in follow-up. Also applies to: 210-218 --- `327-333`: **Map 401/403 to ApiKeyError and 429 to ServiceUnavailableError** Clearer semantics upstream; better user notices. Apply: ```diff - if (response.status < 200 || response.status >= 300) { - const errorBody = response.text || 'Unknown error'; - throw new ApiError(`API request failed (${response.status}): ${errorBody}`, response.status, errorBody); - } + if (response.status < 200 || response.status >= 300) { + const errorBody = response.text || 'Unknown error'; + 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); + } ``` --- `351-359`: **Concatenate all text blocks in response** Anthropic can return multiple text blocks; only reading index 0 may truncate output. Apply: ```diff - const text = response.content[0].text; - if (!text || text.trim().length === 0) { + const text = response.content.map(c => c.text ?? '').join('').trim(); + if (!text) { throw new InvalidResponseError('Empty response from API'); } - return text.trim(); + return text; ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e29539c8ebfe739661c607403cbb81ab3a3f91ee and 306e6819a3dbdeff7a4b7697fd9cb5c0ff1e74ad. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `api/anthropicClient.ts` (9 hunks) * `commands/cleanupCommand.ts` (4 hunks) * `services/cleanupService.ts` (5 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (3)</summary> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `services/cleanupService.ts` - `commands/cleanupCommand.ts` - `api/anthropicClient.ts` </details> <details> <summary>services/cleanupService.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Isolate Anthropic API integration and connection testing in CleanupService Files: - `services/cleanupService.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> </details><details> <summary>🧠 Learnings (3)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> </details><details> <summary>🧬 Code graph analysis (3)</summary> <details> <summary>services/cleanupService.ts (3)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (23-396) </details> <details> <summary>types.ts (3)</summary> * `FreewritingCleanupSettings` (10-23) * `CleanupResult` (113-131) * `ANTHROPIC_LIMITS` (231-238) </details> <details> <summary>errors.ts (2)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) </details> </blockquote></details> <details> <summary>commands/cleanupCommand.ts (3)</summary><blockquote> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (16-253) </details> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `ANTHROPIC_LIMITS` (231-238) </details> <details> <summary>errors.ts (3)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ServiceUnavailableError` (38-38) </details> </blockquote></details> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> <details> <summary>errors.ts (7)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ConfigurationError` (52-52) * `ApiError` (66-74) * `ServiceUnavailableError` (38-38) * `InvalidResponseError` (45-45) * `NetworkError` (59-59) </details> <details> <summary>types.ts (3)</summary> * `ANTHROPIC_LIMITS` (231-238) * `ModelsListResponse` (154-163) * `AnthropicResponse` (79-106) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (6)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (3)</summary><blockquote> `54-55`: **Loading notice lifecycle: good** Persistent notice + finally hide prevents leaks. LGTM. --- `101-139`: **Validation UX looks solid** Clear messages with localized counts and both char/token checks. LGTM. --- `41-41`: **Command signature wiring is correct** The execute method receives the correct parameters via proper service injection. The editorCallback invokes `executeCleanupCommand(editor, view)`, which then delegates to `this.cleanupCommand.execute(editor, view, this.settings)` at main.ts:135. The settings parameter is correctly supplied through the plugin's instance context and passed as the third argument to execute(). </blockquote></details> <details> <summary>services/cleanupService.ts (1)</summary><blockquote> `50-63`: **Good: explicit ApiKeyError/TextTooLongError with precise counts** Clear signals and domain errors. LGTM. </blockquote></details> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> `126-184`: **testConnection: concise and helpful** Good validation, timing details, and error mapping. LGTM. --- `266-303`: **fetchModels: headers and error handling look right** Straightforward GET with version header and ApiError mapping. LGTM. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-24 16:35:00 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 1

🧹 Nitpick comments (1)
commands/cleanupCommand.ts (1)

41-108: Well-structured error handling with domain-specific errors.

The refactored error handling properly differentiates between error types using instanceof checks, providing appropriate user feedback for each scenario. The finally block correctly ensures the loading notice is hidden regardless of success or failure.

Consider consolidating the ApiError checks for slightly better readability:

-                } else if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
-                    new Notice('API key was rejected by the server. Please verify your key.');
-                } else if (error instanceof ApiError && error.status === 429) {
-                    new Notice('Rate limited by API. Please wait and try again.');
+                } 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(`API error (${error.status}): ${error.message}`);
+                    }

This also adds a catch-all for other ApiError status codes that might occur.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 306e6819a3 and ab5e134a12.

📒 Files selected for processing (4)
  • api/anthropicClient.ts (9 hunks)
  • commands/cleanupCommand.ts (4 hunks)
  • services/cleanupService.ts (7 hunks)
  • types.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer async/await over promise chains and handle errors gracefully

Use ESLint to lint all TypeScript source files

Files:

  • api/anthropicClient.ts
  • commands/cleanupCommand.ts
  • services/cleanupService.ts
  • types.ts
commands/cleanupCommand.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Implement command execution and editor interaction in CleanupCommand with service injection

Files:

  • commands/cleanupCommand.ts
services/cleanupService.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Isolate Anthropic API integration and connection testing in CleanupService

Files:

  • services/cleanupService.ts
types.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize TypeScript interfaces and types in types.ts

Files:

  • types.ts
🧠 Learnings (3)
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand()

Applied to files:

  • commands/cleanupCommand.ts
📚 Learning: 2025-10-24T09:14:48.135Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-24T09:14:48.135Z
Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.ts
🧬 Code graph analysis (3)
api/anthropicClient.ts (2)
errors.ts (7)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ConfigurationError (52-52)
  • ApiError (66-74)
  • ServiceUnavailableError (38-38)
  • InvalidResponseError (45-45)
  • NetworkError (59-59)
types.ts (3)
  • ANTHROPIC_LIMITS (233-240)
  • ModelsListResponse (156-165)
  • AnthropicResponse (79-106)
commands/cleanupCommand.ts (2)
types.ts (2)
  • FreewritingCleanupSettings (10-23)
  • ANTHROPIC_LIMITS (233-240)
errors.ts (6)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
  • ApiError (66-74)
  • ServiceUnavailableError (38-38)
  • InvalidResponseError (45-45)
  • NetworkError (59-59)
services/cleanupService.ts (3)
api/anthropicClient.ts (1)
  • AnthropicClient (23-403)
types.ts (3)
  • FreewritingCleanupSettings (10-23)
  • CleanupResult (113-133)
  • ANTHROPIC_LIMITS (233-240)
errors.ts (2)
  • ApiKeyError (24-24)
  • TextTooLongError (31-31)
🔇 Additional comments (17)
commands/cleanupCommand.ts (2)

1-26: LGTM! Clean dependency injection and comprehensive documentation.

The imports of domain-specific errors and ANTHROPIC_LIMITS align well with the broader error handling refactor. The constructor properly receives the CleanupService as a dependency, enabling testability and loose coupling.


121-151: LGTM! Clear validation logic with user-friendly error messages.

The validation properly checks for empty text and uses the CleanupService's static method to verify limits. The use of toLocaleString() for number formatting provides better readability for users across different locales.

types.ts (1)

4-177: LGTM! Comprehensive type definitions with excellent documentation.

All interfaces are well-documented with clear JSDoc comments explaining the purpose of each field. The nullable types for stop_sequence, first_id, and last_id correctly reflect the API's actual behavior.

services/cleanupService.ts (5)

9-35: LGTM! Clean service initialization with proper encapsulation.

The public getter for anthropicClient provides controlled access for dependent services like ModelService, while maintaining encapsulation of the private field.


39-97: LGTM! Well-structured cleanup orchestration with clear validation.

The method properly validates inputs before making the API call and delegates error handling to the command layer, avoiding duplicate user notices. The duration calculation and result construction are straightforward and correct.


99-153: LGTM! Clear utility methods with appropriate error handling.

Both testConnection and formatCleanupResult follow simple, predictable patterns. The connection test provides useful diagnostic information, and the formatting method creates clean markdown output.


157-206: LGTM! Comprehensive settings validation.

The validation correctly checks all required fields and includes the important check for custom commentary prompts when the custom style is selected. This aligns with the error handling in AnthropicClient.


210-261: LGTM! Sensible utility methods with documented approximations.

The token estimation uses a reasonable heuristic with a safety margin, clearly documented as an approximation. The isWithinLimits method provides comprehensive information for validation feedback.

api/anthropicClient.ts (9)

16-37: LGTM! Clean client initialization with sensible retry configuration.

The retry configuration (3 attempts with 1-second base delay) provides good resilience without excessive waiting. The constructor keeps initialization simple and focused.


41-124: LGTM! Robust text cleanup with comprehensive validation.

The method properly validates inputs before making the API call and handles the commentary configuration correctly, throwing a clear error when custom style is selected without a custom prompt.


126-184: LGTM! Effective connection test with diagnostic information.

The minimal test request efficiently validates the API key and connection, providing useful timing and token metrics for troubleshooting.


188-228: LGTM! Well-designed retry logic with appropriate backoff.

The retry strategy correctly distinguishes between transient failures (network errors, 5xx, 429) and permanent failures (API key errors, configuration errors, 4xx status codes). The exponential backoff provides reasonable spacing between attempts.


230-264: LGTM! Reliable marker-based response parsing.

The regex patterns correctly handle multi-line content and the validation ensures that required sections are present. The optional commentary extraction gracefully handles cases where Claude doesn't provide it.


266-302: LGTM! Straightforward model fetching with proper error handling.

The method correctly validates the API key, makes the GET request with appropriate headers, and handles errors consistently with the rest of the client.


304-345: LGTM! Comprehensive HTTP error handling with domain-specific errors.

The method correctly maps HTTP status codes to appropriate domain errors, providing clear error semantics for retry logic and user feedback. The distinction between authentication failures (401/403), rate limiting (429), and other API errors is well-defined.


347-369: LGTM! Safe content extraction with proper validation.

The method safely handles multiple content blocks and uses nullish coalescing to guard against missing text fields. The validation ensures meaningful content is present before proceeding.


371-402: LGTM! Simple utility methods with clear purposes.

The sleep utility supports the retry logic, and the API key methods provide runtime configuration flexibility without requiring client recreation.

**Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (1)</summary><blockquote> `41-108`: **Well-structured error handling with domain-specific errors.** The refactored error handling properly differentiates between error types using instanceof checks, providing appropriate user feedback for each scenario. The finally block correctly ensures the loading notice is hidden regardless of success or failure. Consider consolidating the ApiError checks for slightly better readability: ```diff - } else if (error instanceof ApiError && (error.status === 401 || error.status === 403)) { - new Notice('API key was rejected by the server. Please verify your key.'); - } else if (error instanceof ApiError && error.status === 429) { - new Notice('Rate limited by API. Please wait and try again.'); + } 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(`API error (${error.status}): ${error.message}`); + } ``` This also adds a catch-all for other ApiError status codes that might occur. </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 306e6819a3dbdeff7a4b7697fd9cb5c0ff1e74ad and ab5e134a1248b1e3bf260212872ec2af0533273f. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `api/anthropicClient.ts` (9 hunks) * `commands/cleanupCommand.ts` (4 hunks) * `services/cleanupService.ts` (7 hunks) * `types.ts` (3 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (4)</summary> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (AGENTS.md)** > Prefer async/await over promise chains and handle errors gracefully > > Use ESLint to lint all TypeScript source files Files: - `api/anthropicClient.ts` - `commands/cleanupCommand.ts` - `services/cleanupService.ts` - `types.ts` </details> <details> <summary>commands/cleanupCommand.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Implement command execution and editor interaction in CleanupCommand with service injection Files: - `commands/cleanupCommand.ts` </details> <details> <summary>services/cleanupService.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Isolate Anthropic API integration and connection testing in CleanupService Files: - `services/cleanupService.ts` </details> <details> <summary>types.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Centralize TypeScript interfaces and types in types.ts Files: - `types.ts` </details> </details><details> <summary>🧠 Learnings (3)</summary> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to commands/cleanupCommand.ts : Implement command execution and editor interaction in CleanupCommand with service injection ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to main.ts : Define FreewritingCleanupPlugin class extending Obsidian’s Plugin and register commands via addCommand() ``` **Applied to files:** - `commands/cleanupCommand.ts` </details> <details> <summary>📚 Learning: 2025-10-24T09:14:48.135Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-10-24T09:14:48.135Z Learning: Applies to services/cleanupService.ts : Isolate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.ts` </details> </details><details> <summary>🧬 Code graph analysis (3)</summary> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> <details> <summary>errors.ts (7)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ConfigurationError` (52-52) * `ApiError` (66-74) * `ServiceUnavailableError` (38-38) * `InvalidResponseError` (45-45) * `NetworkError` (59-59) </details> <details> <summary>types.ts (3)</summary> * `ANTHROPIC_LIMITS` (233-240) * `ModelsListResponse` (156-165) * `AnthropicResponse` (79-106) </details> </blockquote></details> <details> <summary>commands/cleanupCommand.ts (2)</summary><blockquote> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (10-23) * `ANTHROPIC_LIMITS` (233-240) </details> <details> <summary>errors.ts (6)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) * `ApiError` (66-74) * `ServiceUnavailableError` (38-38) * `InvalidResponseError` (45-45) * `NetworkError` (59-59) </details> </blockquote></details> <details> <summary>services/cleanupService.ts (3)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (23-403) </details> <details> <summary>types.ts (3)</summary> * `FreewritingCleanupSettings` (10-23) * `CleanupResult` (113-133) * `ANTHROPIC_LIMITS` (233-240) </details> <details> <summary>errors.ts (2)</summary> * `ApiKeyError` (24-24) * `TextTooLongError` (31-31) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (17)</summary><blockquote> <details> <summary>commands/cleanupCommand.ts (2)</summary><blockquote> `1-26`: **LGTM! Clean dependency injection and comprehensive documentation.** The imports of domain-specific errors and ANTHROPIC_LIMITS align well with the broader error handling refactor. The constructor properly receives the CleanupService as a dependency, enabling testability and loose coupling. --- `121-151`: **LGTM! Clear validation logic with user-friendly error messages.** The validation properly checks for empty text and uses the CleanupService's static method to verify limits. The use of `toLocaleString()` for number formatting provides better readability for users across different locales. </blockquote></details> <details> <summary>types.ts (1)</summary><blockquote> `4-177`: **LGTM! Comprehensive type definitions with excellent documentation.** All interfaces are well-documented with clear JSDoc comments explaining the purpose of each field. The nullable types for `stop_sequence`, `first_id`, and `last_id` correctly reflect the API's actual behavior. </blockquote></details> <details> <summary>services/cleanupService.ts (5)</summary><blockquote> `9-35`: **LGTM! Clean service initialization with proper encapsulation.** The public getter for `anthropicClient` provides controlled access for dependent services like ModelService, while maintaining encapsulation of the private field. --- `39-97`: **LGTM! Well-structured cleanup orchestration with clear validation.** The method properly validates inputs before making the API call and delegates error handling to the command layer, avoiding duplicate user notices. The duration calculation and result construction are straightforward and correct. --- `99-153`: **LGTM! Clear utility methods with appropriate error handling.** Both `testConnection` and `formatCleanupResult` follow simple, predictable patterns. The connection test provides useful diagnostic information, and the formatting method creates clean markdown output. --- `157-206`: **LGTM! Comprehensive settings validation.** The validation correctly checks all required fields and includes the important check for custom commentary prompts when the custom style is selected. This aligns with the error handling in AnthropicClient. --- `210-261`: **LGTM! Sensible utility methods with documented approximations.** The token estimation uses a reasonable heuristic with a safety margin, clearly documented as an approximation. The `isWithinLimits` method provides comprehensive information for validation feedback. </blockquote></details> <details> <summary>api/anthropicClient.ts (9)</summary><blockquote> `16-37`: **LGTM! Clean client initialization with sensible retry configuration.** The retry configuration (3 attempts with 1-second base delay) provides good resilience without excessive waiting. The constructor keeps initialization simple and focused. --- `41-124`: **LGTM! Robust text cleanup with comprehensive validation.** The method properly validates inputs before making the API call and handles the commentary configuration correctly, throwing a clear error when custom style is selected without a custom prompt. --- `126-184`: **LGTM! Effective connection test with diagnostic information.** The minimal test request efficiently validates the API key and connection, providing useful timing and token metrics for troubleshooting. --- `188-228`: **LGTM! Well-designed retry logic with appropriate backoff.** The retry strategy correctly distinguishes between transient failures (network errors, 5xx, 429) and permanent failures (API key errors, configuration errors, 4xx status codes). The exponential backoff provides reasonable spacing between attempts. --- `230-264`: **LGTM! Reliable marker-based response parsing.** The regex patterns correctly handle multi-line content and the validation ensures that required sections are present. The optional commentary extraction gracefully handles cases where Claude doesn't provide it. --- `266-302`: **LGTM! Straightforward model fetching with proper error handling.** The method correctly validates the API key, makes the GET request with appropriate headers, and handles errors consistently with the rest of the client. --- `304-345`: **LGTM! Comprehensive HTTP error handling with domain-specific errors.** The method correctly maps HTTP status codes to appropriate domain errors, providing clear error semantics for retry logic and user feedback. The distinction between authentication failures (401/403), rate limiting (429), and other API errors is well-defined. --- `347-369`: **LGTM! Safe content extraction with proper validation.** The method safely handles multiple content blocks and uses nullish coalescing to guard against missing text fields. The validation ensures meaningful content is present before proceeding. --- `371-402`: **LGTM! Simple utility methods with clear purposes.** The sleep utility supports the retry logic, and the API key methods provide runtime configuration flexibility without requiring client recreation. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -99,9 +204,19 @@ export const COMMENTARY_STYLES = [
'custom'
coderabbitai[bot] (Migrated from github.com) commented 2025-10-24 16:35:00 +02:00

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the API limits match Anthropic's current documentation.

The defined limits should be confirmed against Anthropic's latest API documentation to ensure they're accurate and up-to-date.


🌐 Web query:

What are the current Anthropic Claude API limits for maximum input tokens, maximum input characters, and default maximum output tokens?

💡 Result:

  • Maximum input tokens (context window): 200,000 tokens. [1][2]
  • Maximum input characters: Anthropic does not publish a strict character limit — they express context window in tokens (200k tokens ≈ “about 500 pages of text” per support doc). If you need a rough conversion, many users use ~4 characters/token → ~800,000 characters (approximate only). [3][1]
  • Default maximum output tokens: model-dependent. For current Claude family docs: Claude Opus 4 — 32,000 tokens; Claude Sonnet 4 — 64,000 tokens (other models have different defaults). (Some models support larger outputs with beta headers/flags.) [2][4]

Sources:
[1] Anthropic — Rate limits / context & token docs.
[2] Anthropic — Models overview (shows context window and max output by model).
[3] Anthropic Support — “maximum prompt length” (200k+ tokens ≈ 500 pages).
[4] Anthropic — Models overview (notes about beta headers to increase max output).


Update API limits constants to reflect current Anthropic documentation.

The MAX_TOKENS value (200,000) is correct, but two values need correction:

  • MAX_CHARACTERS (680,000): Anthropic does not publish a strict character limit—they express the context window in tokens (200k tokens ≈ ~800,000 characters approximate). Remove or replace this value with a comment noting the character-to-token approximation.
  • DEFAULT_MAX_OUTPUT_TOKENS (4,000): Current Claude models support much higher defaults (Claude Opus 4 — 32,000 tokens; Claude Sonnet 4 — 64,000 tokens). Update this to reflect a current model's default output tokens, or make it model-specific if used for validation.
🤖 Prompt for AI Agents
In types.ts around lines 227 to 240, update the Anthropic limits: remove the
strict MAX_CHARACTERS value (680,000) and replace it with a comment that
character counts are approximate and depend on tokenization (e.g., "≈ 4
characters per token, varies by language"), and change DEFAULT_MAX_OUTPUT_TOKENS
from 4000 to a more current default (e.g., 32000 for Claude Opus 4) or refactor
into a model-specific map (e.g., DEFAULT_OUTPUT_TOKENS_BY_MODEL) if the code
validates per-model — adjust any validation that consumes these constants
accordingly.

✅ Addressed in commits c5ebfce to 4efa8a1

_⚠️ Potential issue_ | _🔴 Critical_ <details> <summary>🧩 Analysis chain</summary> **Verify the API limits match Anthropic's current documentation.** The defined limits should be confirmed against Anthropic's latest API documentation to ensure they're accurate and up-to-date. --- 🌐 Web query: ```web What are the current Anthropic Claude API limits for maximum input tokens, maximum input characters, and default maximum output tokens? ``` 💡 Result: - Maximum input tokens (context window): 200,000 tokens. [1][2] - Maximum input characters: Anthropic does not publish a strict character limit — they express context window in tokens (200k tokens ≈ “about 500 pages of text” per support doc). If you need a rough conversion, many users use ~4 characters/token → ~800,000 characters (approximate only). [3][1] - Default maximum output tokens: model-dependent. For current Claude family docs: Claude Opus 4 — 32,000 tokens; Claude Sonnet 4 — 64,000 tokens (other models have different defaults). (Some models support larger outputs with beta headers/flags.) [2][4] Sources: [1] Anthropic — Rate limits / context & token docs. [2] Anthropic — Models overview (shows context window and max output by model). [3] Anthropic Support — “maximum prompt length” (200k+ tokens ≈ 500 pages). [4] Anthropic — Models overview (notes about beta headers to increase max output). --- </details> **Update API limits constants to reflect current Anthropic documentation.** The MAX_TOKENS value (200,000) is correct, but two values need correction: - MAX_CHARACTERS (680,000): Anthropic does not publish a strict character limit—they express the context window in tokens (200k tokens ≈ ~800,000 characters approximate). Remove or replace this value with a comment noting the character-to-token approximation. - DEFAULT_MAX_OUTPUT_TOKENS (4,000): Current Claude models support much higher defaults (Claude Opus 4 — 32,000 tokens; Claude Sonnet 4 — 64,000 tokens). Update this to reflect a current model's default output tokens, or make it model-specific if used for validation. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In types.ts around lines 227 to 240, update the Anthropic limits: remove the strict MAX_CHARACTERS value (680,000) and replace it with a comment that character counts are approximate and depend on tokenization (e.g., "≈ 4 characters per token, varies by language"), and change DEFAULT_MAX_OUTPUT_TOKENS from 4000 to a more current default (e.g., 32000 for Claude Opus 4) or refactor into a model-specific map (e.g., DEFAULT_OUTPUT_TOKENS_BY_MODEL) if the code validates per-model — adjust any validation that consumes these constants accordingly. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits c5ebfce to 4efa8a1
Sign in to join this conversation.