feat: add dynamic model fetching from Anthropic API #2

Merged
AlexKucera merged 10 commits from dynamic-models into master 2025-10-24 11:14:13 +02:00
AlexKucera commented 2025-10-23 10:26:19 +02:00 (Migrated from github.com)

Replace hardcoded model list with dynamic API-based model fetching
that queries the Anthropic models endpoint. Implements 24-hour caching
with automatic fallback to hardcoded models if API is unavailable.

Changes:

  • Add ModelService to fetch and cache available models from API
  • Implement 24-hour TTL cache persisted in plugin data
  • Update AnthropicClient with fetchModels() method
  • Modify settings UI to load models asynchronously with loading states
  • Auto-refresh models when API key is entered or changed
  • Display model names using display_name field from API
  • Preserve user's selected model across updates and restarts
  • Show notice when falling back to hardcoded model list
  • Change model type from strict enum to string for dynamic support

Technical details:

  • New ModelInfo and ModelsListResponse interfaces for API response
  • ModelCache interface with timestamp for TTL validation
  • FreewritingCleanupData extends settings to include cache
  • Settings dropdown disabled during model fetch/refresh
  • Fallback to ANTHROPIC_MODELS constant on API failure

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

Summary by CodeRabbit

  • New Features

    • Dynamic model discovery from the API with a user-facing model dropdown and remembered model cache.
    • 24-hour in-memory caching of model listings with persistence across plugin saves.
  • Improvements

    • Settings UI auto-loads and refreshes model options when API key is entered or changed.
    • Better error handling with automatic fallback to built-in model list and surfaced usage/token info for requests.
Replace hardcoded model list with dynamic API-based model fetching that queries the Anthropic models endpoint. Implements 24-hour caching with automatic fallback to hardcoded models if API is unavailable. Changes: - Add ModelService to fetch and cache available models from API - Implement 24-hour TTL cache persisted in plugin data - Update AnthropicClient with fetchModels() method - Modify settings UI to load models asynchronously with loading states - Auto-refresh models when API key is entered or changed - Display model names using display_name field from API - Preserve user's selected model across updates and restarts - Show notice when falling back to hardcoded model list - Change model type from strict enum to string for dynamic support Technical details: - New ModelInfo and ModelsListResponse interfaces for API response - ModelCache interface with timestamp for TTL validation - FreewritingCleanupData extends settings to include cache - Settings dropdown disabled during model fetch/refresh - Fallback to ANTHROPIC_MODELS constant on API failure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Dynamic model discovery from the API with a user-facing model dropdown and remembered model cache. * 24-hour in-memory caching of model listings with persistence across plugin saves. * **Improvements** * Settings UI auto-loads and refreshes model options when API key is entered or changed. * Better error handling with automatic fallback to built-in model list and surfaced usage/token info for requests. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
AlexKucera commented 2025-10-23 10:29:27 +02:00 (Migrated from github.com)

@coderabbitai review

@coderabbitai review
AlexKucera commented 2025-10-23 15:01:49 +02:00 (Migrated from github.com)

@coderabbit review

@coderabbit review
coderabbitai[bot] commented 2025-10-23 15:02:12 +02:00 (Migrated from github.com)
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>✅ Actions performed</summary> Review triggered. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
coderabbitai[bot] commented 2025-10-23 15:02:15 +02:00 (Migrated from github.com)

Walkthrough

Dynamic model management added: AnthropicClient now supports a dedicated models endpoint and returns richer responses; a new ModelService fetches and caches model metadata (24h TTL) with fallbacks; plugin and settings updated to load, persist, and populate models as dynamic string IDs.

Changes

Cohort / File(s) Summary
Anthropic API Client
api/anthropicClient.ts
Added fetchModels(): Promise<ModelsListResponse>, new private messagesUrl and modelsUrl fields, switched requests to messagesUrl, changed makeRequestWithRetry to return AnthropicResponse, updated cleanupText() and testConnection() to accept model: string, and imported ModelsListResponse.
Service Layer Refactor
services/cleanupService.ts
Renamed private anthropicClient → client; added public getter get anthropicClient() returning the internal client; updated internal references and usage token propagation.
Model Management Service
services/modelService.ts
New ModelService and ModelOption export: fetches models via AnthropicClient, implements 24‑hour in-memory ModelCache, getAvailableModels(), refreshModels(), cache load/get/clear, formatting, and fallback to hardcoded models.
Plugin Initialization
main.ts
Added ModelService and FreewritingCleanupData imports; added public modelService: ModelService; instantiate and load cache on onload(); persist modelCache in saveSettings().
Settings UI
settings.ts
Made settings UI async: background model loading, dynamic modelDropdown populated from availableModels; added loadModels(), populateModelDropdown(), refreshModels(); API key changes trigger refresh; replaced custom ConfirmModal with Obsidian Modal subclass.
Type Definitions
types.ts
Switched FreewritingCleanupSettings.model from AnthropicModel to string; added FreewritingCleanupData, ModelInfo, ModelsListResponse, ModelCache interfaces; ANTHROPIC_MODELS now readonly string[]; removed AnthropicModel type alias.
Docs/Notes
CLAUDE.md
Updated documentation to reflect model now a dynamic string ID and related type changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor User
    participant Settings
    participant ModelService
    participant AnthropicClient
    participant API

    User->>Settings: Open settings
    Settings->>ModelService: loadModels()
    alt cache valid
        ModelService-->>Settings: return cached ModelOption[]
    else cache stale/empty
        ModelService->>AnthropicClient: fetchModels()
        AnthropicClient->>API: GET /models (modelsUrl)
        alt success
            API-->>AnthropicClient: ModelsListResponse
            AnthropicClient-->>ModelService: ModelsListResponse
            ModelService->>ModelService: updateCache(fetchedAt)
            ModelService-->>Settings: formatted ModelOption[]
        else failure
            API-->>AnthropicClient: error
            AnthropicClient-->>ModelService: throw/propagate
            ModelService->>ModelService: use fallback models
            ModelService-->>Settings: fallback ModelOption[]
        end
    end
    Settings->>Settings: populateModelDropdown()
    Settings-->>User: UI shows models

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • AlexKucera/freewriting-cleanup#1 — Modifies Anthropic client and types related to request/response shapes and model handling; likely touches overlapping code paths.

Poem

🐰
I hopped through endpoints, soft and spry,
Cached the models 'neath moonlit sky,
Dropdowns bloom where static lay,
Fallbacks guard the cloudy way.
A humble rabbit cheers the new reply.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "feat: add dynamic model fetching from Anthropic API" accurately reflects the primary change in this pull request. The changeset's core objective is to replace the hardcoded Anthropic model list with dynamic fetching from the Anthropic models endpoint, which is exactly what the title conveys. The title is concise, specific, and free from vague terminology or file lists. While the PR includes supporting changes such as ModelService implementation, UI updates, caching mechanisms, and fallback behavior, all of these serve the central feature of adding dynamic model fetching capability. The title clearly communicates the main change without being misleading or overly generic.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dynamic-models

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b23ed6615 and f8427e72a0.

📒 Files selected for processing (7)
  • CLAUDE.md (1 hunks)
  • api/anthropicClient.ts (5 hunks)
  • main.ts (2 hunks)
  • services/cleanupService.ts (6 hunks)
  • services/modelService.ts (1 hunks)
  • settings.ts (7 hunks)
  • types.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
services/cleanupService.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Encapsulate Anthropic API integration and connection testing in CleanupService

Files:

  • services/cleanupService.ts
**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Lint all TypeScript files with ESLint

Prefer async/await over promise chains and handle errors gracefully

Files:

  • services/cleanupService.ts
  • services/modelService.ts
  • main.ts
  • api/anthropicClient.ts
  • settings.ts
  • types.ts
main.ts

📄 CodeRabbit inference engine (CLAUDE.md)

main.ts: Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point
Register commands via addCommand() with stable IDs
Persist settings using loadData()/saveData() and update services when settings change

Files:

  • main.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
settings.ts

📄 CodeRabbit inference engine (CLAUDE.md)

settings.ts: Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab
Define DEFAULT_SETTINGS for FreewritingCleanupSettings

Files:

  • settings.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
types.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts

Files:

  • types.ts
🧠 Learnings (8)
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to settings.ts : Define DEFAULT_SETTINGS for FreewritingCleanupSettings

Applied to files:

  • CLAUDE.md
  • main.ts
  • types.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to services/cleanupService.ts : Encapsulate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to main.ts : Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point

Applied to files:

  • main.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to settings.ts : Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab

Applied to files:

  • main.ts
  • settings.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 {main.ts,src/main.ts} : Persist settings using this.loadData() / this.saveData()

Applied to files:

  • main.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to main.ts : Persist settings using loadData()/saveData() and update services when settings change

Applied to files:

  • 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-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to types.ts : Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts

Applied to files:

  • types.ts
🧬 Code graph analysis (5)
services/cleanupService.ts (1)
api/anthropicClient.ts (1)
  • AnthropicClient (7-265)
services/modelService.ts (3)
api/anthropicClient.ts (1)
  • AnthropicClient (7-265)
types.ts (3)
  • ModelCache (78-81)
  • ModelInfo (64-69)
  • ANTHROPIC_MODELS (84-91)
services/cleanupService.ts (1)
  • anthropicClient (12-14)
main.ts (3)
types.ts (2)
  • FreewritingCleanupSettings (4-11)
  • FreewritingCleanupData (13-15)
services/cleanupService.ts (1)
  • CleanupService (8-167)
services/modelService.ts (1)
  • ModelService (13-182)
api/anthropicClient.ts (1)
types.ts (4)
  • CommentaryStyle (102-102)
  • AnthropicRequest (25-33)
  • AnthropicResponse (35-50)
  • ModelsListResponse (71-76)
settings.ts (1)
services/modelService.ts (1)
  • ModelOption (8-11)
🔇 Additional comments (36)
types.ts (6)

6-6: LGTM!

The change from a strict type to string enables dynamic model IDs fetched from the Anthropic API, aligning with the PR objectives.


13-15: LGTM!

The FreewritingCleanupData interface cleanly extends settings to include cache persistence.


64-69: LGTM!

The ModelInfo interface correctly models the Anthropic API response. The display_name field is properly defined as required, addressing the previous review concern.


71-76: LGTM!

The ModelsListResponse interface correctly models the Anthropic API pagination structure.


78-81: LGTM!

The ModelCache interface provides a clean structure for TTL-based caching with the fetchedAt timestamp.


83-91: LGTM!

The readonly modifier on ANTHROPIC_MODELS prevents accidental mutations while maintaining the fallback list for when the API is unavailable.

CLAUDE.md (1)

78-78: LGTM!

Documentation correctly reflects the change from AnthropicModel to dynamic string-based model IDs.

services/cleanupService.ts (2)

9-14: LGTM!

The refactor to expose anthropicClient via a public getter while keeping the internal field private is a clean encapsulation pattern that enables ModelService access.


56-57: LGTM!

Token usage is now properly extracted from the API response's usage field, providing accurate metrics.

settings.ts (7)

20-21: LGTM!

The addition of modelDropdown and availableModels fields enables dynamic model management in the settings UI.


28-44: LGTM!

The display() method correctly remains void (not async) and loads models asynchronously in the background without blocking the UI. This addresses the previous review concern.


61-69: LGTM!

The API key change handler appropriately triggers model refresh when a key is entered and reverts to fallback options when cleared.


220-227: LGTM!

The loadModels() method cleanly delegates to ModelService and handles errors appropriately.


229-246: LGTM!

The populateModelDropdown() method handles empty states correctly by disabling the dropdown and showing a loading message.


248-285: LGTM!

The refreshModels() method correctly persists a valid model selection when the current model disappears (lines 270-276), addressing the previous review concern. Settings are saved after any model changes.


344-387: LGTM!

The ConfirmModal implementation correctly extends Obsidian's Modal class with proper onOpen/onClose lifecycle hooks, ensuring consistent styling and accessibility.

main.ts (4)

5-5: LGTM!

The imports and field additions cleanly integrate ModelService into the plugin architecture.

Also applies to: 8-8, 14-14


18-29: LGTM!

The optimization to reuse loaded data avoids calling loadData() twice and cleanly integrates model cache loading.


44-48: LGTM!

The loadSettings() method now returns the loaded data, enabling cache initialization without redundant loads.


50-62: LGTM!

The saveSettings() method correctly persists the model cache alongside settings, with proper null-safety using the optional chaining and || undefined fallback.

services/modelService.ts (9)

8-11: LGTM!

The ModelOption interface provides a clean abstraction for UI components.


13-20: LGTM!

The constructor and cache initialization are clean and straightforward.


29-66: LGTM!

The getAvailableModels() method correctly implements early fallback when the API key is missing (lines 35-46) and caches the fallback to honor TTL, addressing the previous review concern. The fallback is silently cached when no key is present, and a Notice is only shown on actual API failures (line 55).


72-103: LGTM!

The refreshModels() method correctly implements the same early fallback and caching pattern as getAvailableModels().


108-132: LGTM!

The cache management methods (loadCache, getCache, clearCache, getFallbackOptions) provide a clean public API for external components.


139-147: LGTM!

The isCacheValid() method correctly implements 24-hour TTL validation.


152-157: LGTM!

The updateCache() method cleanly stores models with a timestamp for TTL validation.


164-171: LGTM!

The formatModels() method correctly maps API responses to UI-friendly options and sorts alphabetically for consistent UX.


176-181: LGTM!

The getFallbackModels() method cleanly converts the hardcoded model list to ModelOption format.

api/anthropicClient.ts (7)

9-10: LGTM!

Separating endpoints for messages and models improves code clarity and supports the new model fetching capability.


22-27: LGTM!

The change from a strict type to string for the model parameter and the addition of usage metrics in the return type align with dynamic model support and token tracking requirements.


78-84: LGTM!

The method now correctly extracts usage metrics from the response and includes them in the return value.


87-87: LGTM!

The testConnection() method correctly accepts a string model parameter, consistent with dynamic model support.


139-145: LGTM!

The makeRequestWithRetry() method now returns the full AnthropicResponse object, enabling access to usage metrics and other response metadata.


184-210: LGTM!

The fetchModels() method is well-implemented with proper error handling and validation. The API key check, status code validation, and error message construction are all correct.


215-215: LGTM!

The makeRequest() method correctly uses messagesUrl for sending messages, consistent with the endpoint separation.


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 --> <!-- walkthrough_start --> ## Walkthrough Dynamic model management added: AnthropicClient now supports a dedicated models endpoint and returns richer responses; a new ModelService fetches and caches model metadata (24h TTL) with fallbacks; plugin and settings updated to load, persist, and populate models as dynamic string IDs. ## Changes | Cohort / File(s) | Summary | |---|---| | **Anthropic API Client** <br> `api/anthropicClient.ts` | Added `fetchModels(): Promise<ModelsListResponse>`, new private `messagesUrl` and `modelsUrl` fields, switched requests to `messagesUrl`, changed `makeRequestWithRetry` to return `AnthropicResponse`, updated `cleanupText()` and `testConnection()` to accept `model: string`, and imported `ModelsListResponse`. | | **Service Layer Refactor** <br> `services/cleanupService.ts` | Renamed private `anthropicClient` → `client`; added public getter `get anthropicClient()` returning the internal client; updated internal references and usage token propagation. | | **Model Management Service** <br> `services/modelService.ts` | New `ModelService` and `ModelOption` export: fetches models via `AnthropicClient`, implements 24‑hour in-memory `ModelCache`, `getAvailableModels()`, `refreshModels()`, cache load/get/clear, formatting, and fallback to hardcoded models. | | **Plugin Initialization** <br> `main.ts` | Added `ModelService` and `FreewritingCleanupData` imports; added public `modelService: ModelService`; instantiate and load cache on `onload()`; persist `modelCache` in `saveSettings()`. | | **Settings UI** <br> `settings.ts` | Made settings UI async: background model loading, dynamic `modelDropdown` populated from `availableModels`; added `loadModels()`, `populateModelDropdown()`, `refreshModels()`; API key changes trigger refresh; replaced custom ConfirmModal with Obsidian `Modal` subclass. | | **Type Definitions** <br> `types.ts` | Switched `FreewritingCleanupSettings.model` from `AnthropicModel` to `string`; added `FreewritingCleanupData`, `ModelInfo`, `ModelsListResponse`, `ModelCache` interfaces; `ANTHROPIC_MODELS` now `readonly string[]`; removed `AnthropicModel` type alias. | | **Docs/Notes** <br> `CLAUDE.md` | Updated documentation to reflect `model` now a dynamic string ID and related type changes. | ## Sequence Diagram(s) ```mermaid sequenceDiagram autonumber actor User participant Settings participant ModelService participant AnthropicClient participant API User->>Settings: Open settings Settings->>ModelService: loadModels() alt cache valid ModelService-->>Settings: return cached ModelOption[] else cache stale/empty ModelService->>AnthropicClient: fetchModels() AnthropicClient->>API: GET /models (modelsUrl) alt success API-->>AnthropicClient: ModelsListResponse AnthropicClient-->>ModelService: ModelsListResponse ModelService->>ModelService: updateCache(fetchedAt) ModelService-->>Settings: formatted ModelOption[] else failure API-->>AnthropicClient: error AnthropicClient-->>ModelService: throw/propagate ModelService->>ModelService: use fallback models ModelService-->>Settings: fallback ModelOption[] end end Settings->>Settings: populateModelDropdown() Settings-->>User: UI shows models ``` ## Estimated code review effort 🎯 3 (Moderate) | ⏱️ ~25 minutes ## Possibly related PRs - AlexKucera/freewriting-cleanup#1 — Modifies Anthropic client and types related to request/response shapes and model handling; likely touches overlapping code paths. ## Poem > 🐰 > I hopped through endpoints, soft and spry, > Cached the models 'neath moonlit sky, > Dropdowns bloom where static lay, > Fallbacks guard the cloudy way. > A humble rabbit cheers the new reply. <!-- walkthrough_end --> <!-- pre_merge_checks_walkthrough_start --> ## Pre-merge checks and finishing touches <details> <summary>❌ Failed checks (1 warning)</summary> | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- | | 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 (2 passed)</summary> | Check name | Status | Explanation | | :---------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. | | Title Check | ✅ Passed | The PR title "feat: add dynamic model fetching from Anthropic API" accurately reflects the primary change in this pull request. The changeset's core objective is to replace the hardcoded Anthropic model list with dynamic fetching from the Anthropic models endpoint, which is exactly what the title conveys. The title is concise, specific, and free from vague terminology or file lists. While the PR includes supporting changes such as ModelService implementation, UI updates, caching mechanisms, and fallback behavior, all of these serve the central feature of adding dynamic model fetching capability. The title clearly communicates the main change without being misleading or overly generic. | </details> <!-- pre_merge_checks_walkthrough_end --> <!-- finishing_touch_checkbox_start --> <details> <summary>✨ Finishing touches</summary> - [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate docstrings <details> <summary>🧪 Generate unit tests (beta)</summary> - [ ] <!-- {"checkboxId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Create PR with unit tests - [ ] <!-- {"checkboxId": "07f1e7d6-8a8e-4e23-9900-8731c2c87f58", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Post copyable unit tests in a comment - [ ] <!-- {"checkboxId": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Commit unit tests in branch `dynamic-models` </details> </details> <!-- finishing_touch_checkbox_end --> --- <details> <summary>📜 Recent 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 7b23ed6615a2847422d240abff35f054e3813a40 and f8427e72a0ab1fd5edfa8f0964559167036ac74f. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `CLAUDE.md` (1 hunks) * `api/anthropicClient.ts` (5 hunks) * `main.ts` (2 hunks) * `services/cleanupService.ts` (6 hunks) * `services/modelService.ts` (1 hunks) * `settings.ts` (7 hunks) * `types.ts` (2 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>📓 Path-based instructions (9)</summary> <details> <summary>services/cleanupService.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Encapsulate Anthropic API integration and connection testing in CleanupService Files: - `services/cleanupService.ts` </details> <details> <summary>**/*.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Lint all TypeScript files with ESLint > > Prefer async/await over promise chains and handle errors gracefully Files: - `services/cleanupService.ts` - `services/modelService.ts` - `main.ts` - `api/anthropicClient.ts` - `settings.ts` - `types.ts` </details> <details> <summary>main.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > `main.ts`: Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point > Register commands via addCommand() with stable IDs > Persist settings using loadData()/saveData() and update services when settings change Files: - `main.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>settings.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > `settings.ts`: Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab > Define DEFAULT_SETTINGS for FreewritingCleanupSettings Files: - `settings.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>types.ts</summary> **📄 CodeRabbit inference engine (CLAUDE.md)** > Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts Files: - `types.ts` </details> </details><details> <summary>🧠 Learnings (8)</summary> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to settings.ts : Define DEFAULT_SETTINGS for FreewritingCleanupSettings ``` **Applied to files:** - `CLAUDE.md` - `main.ts` - `types.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to services/cleanupService.ts : Encapsulate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to main.ts : Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point ``` **Applied to files:** - `main.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to settings.ts : Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab ``` **Applied to files:** - `main.ts` - `settings.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 {main.ts,src/main.ts} : Persist settings using this.loadData() / this.saveData() ``` **Applied to files:** - `main.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to main.ts : Persist settings using loadData()/saveData() and update services when settings change ``` **Applied to files:** - `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-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to types.ts : Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts ``` **Applied to files:** - `types.ts` </details> </details><details> <summary>🧬 Code graph analysis (5)</summary> <details> <summary>services/cleanupService.ts (1)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (7-265) </details> </blockquote></details> <details> <summary>services/modelService.ts (3)</summary><blockquote> <details> <summary>api/anthropicClient.ts (1)</summary> * `AnthropicClient` (7-265) </details> <details> <summary>types.ts (3)</summary> * `ModelCache` (78-81) * `ModelInfo` (64-69) * `ANTHROPIC_MODELS` (84-91) </details> <details> <summary>services/cleanupService.ts (1)</summary> * `anthropicClient` (12-14) </details> </blockquote></details> <details> <summary>main.ts (3)</summary><blockquote> <details> <summary>types.ts (2)</summary> * `FreewritingCleanupSettings` (4-11) * `FreewritingCleanupData` (13-15) </details> <details> <summary>services/cleanupService.ts (1)</summary> * `CleanupService` (8-167) </details> <details> <summary>services/modelService.ts (1)</summary> * `ModelService` (13-182) </details> </blockquote></details> <details> <summary>api/anthropicClient.ts (1)</summary><blockquote> <details> <summary>types.ts (4)</summary> * `CommentaryStyle` (102-102) * `AnthropicRequest` (25-33) * `AnthropicResponse` (35-50) * `ModelsListResponse` (71-76) </details> </blockquote></details> <details> <summary>settings.ts (1)</summary><blockquote> <details> <summary>services/modelService.ts (1)</summary> * `ModelOption` (8-11) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (36)</summary><blockquote> <details> <summary>types.ts (6)</summary><blockquote> `6-6`: **LGTM!** The change from a strict type to `string` enables dynamic model IDs fetched from the Anthropic API, aligning with the PR objectives. --- `13-15`: **LGTM!** The `FreewritingCleanupData` interface cleanly extends settings to include cache persistence. --- `64-69`: **LGTM!** The `ModelInfo` interface correctly models the Anthropic API response. The `display_name` field is properly defined as required, addressing the previous review concern. --- `71-76`: **LGTM!** The `ModelsListResponse` interface correctly models the Anthropic API pagination structure. --- `78-81`: **LGTM!** The `ModelCache` interface provides a clean structure for TTL-based caching with the `fetchedAt` timestamp. --- `83-91`: **LGTM!** The `readonly` modifier on `ANTHROPIC_MODELS` prevents accidental mutations while maintaining the fallback list for when the API is unavailable. </blockquote></details> <details> <summary>CLAUDE.md (1)</summary><blockquote> `78-78`: **LGTM!** Documentation correctly reflects the change from `AnthropicModel` to dynamic string-based model IDs. </blockquote></details> <details> <summary>services/cleanupService.ts (2)</summary><blockquote> `9-14`: **LGTM!** The refactor to expose `anthropicClient` via a public getter while keeping the internal field private is a clean encapsulation pattern that enables ModelService access. --- `56-57`: **LGTM!** Token usage is now properly extracted from the API response's `usage` field, providing accurate metrics. </blockquote></details> <details> <summary>settings.ts (7)</summary><blockquote> `20-21`: **LGTM!** The addition of `modelDropdown` and `availableModels` fields enables dynamic model management in the settings UI. --- `28-44`: **LGTM!** The `display()` method correctly remains `void` (not `async`) and loads models asynchronously in the background without blocking the UI. This addresses the previous review concern. --- `61-69`: **LGTM!** The API key change handler appropriately triggers model refresh when a key is entered and reverts to fallback options when cleared. --- `220-227`: **LGTM!** The `loadModels()` method cleanly delegates to ModelService and handles errors appropriately. --- `229-246`: **LGTM!** The `populateModelDropdown()` method handles empty states correctly by disabling the dropdown and showing a loading message. --- `248-285`: **LGTM!** The `refreshModels()` method correctly persists a valid model selection when the current model disappears (lines 270-276), addressing the previous review concern. Settings are saved after any model changes. --- `344-387`: **LGTM!** The `ConfirmModal` implementation correctly extends Obsidian's `Modal` class with proper `onOpen`/`onClose` lifecycle hooks, ensuring consistent styling and accessibility. </blockquote></details> <details> <summary>main.ts (4)</summary><blockquote> `5-5`: **LGTM!** The imports and field additions cleanly integrate ModelService into the plugin architecture. Also applies to: 8-8, 14-14 --- `18-29`: **LGTM!** The optimization to reuse loaded data avoids calling `loadData()` twice and cleanly integrates model cache loading. --- `44-48`: **LGTM!** The `loadSettings()` method now returns the loaded data, enabling cache initialization without redundant loads. --- `50-62`: **LGTM!** The `saveSettings()` method correctly persists the model cache alongside settings, with proper null-safety using the optional chaining and `|| undefined` fallback. </blockquote></details> <details> <summary>services/modelService.ts (9)</summary><blockquote> `8-11`: **LGTM!** The `ModelOption` interface provides a clean abstraction for UI components. --- `13-20`: **LGTM!** The constructor and cache initialization are clean and straightforward. --- `29-66`: **LGTM!** The `getAvailableModels()` method correctly implements early fallback when the API key is missing (lines 35-46) and caches the fallback to honor TTL, addressing the previous review concern. The fallback is silently cached when no key is present, and a Notice is only shown on actual API failures (line 55). --- `72-103`: **LGTM!** The `refreshModels()` method correctly implements the same early fallback and caching pattern as `getAvailableModels()`. --- `108-132`: **LGTM!** The cache management methods (`loadCache`, `getCache`, `clearCache`, `getFallbackOptions`) provide a clean public API for external components. --- `139-147`: **LGTM!** The `isCacheValid()` method correctly implements 24-hour TTL validation. --- `152-157`: **LGTM!** The `updateCache()` method cleanly stores models with a timestamp for TTL validation. --- `164-171`: **LGTM!** The `formatModels()` method correctly maps API responses to UI-friendly options and sorts alphabetically for consistent UX. --- `176-181`: **LGTM!** The `getFallbackModels()` method cleanly converts the hardcoded model list to `ModelOption` format. </blockquote></details> <details> <summary>api/anthropicClient.ts (7)</summary><blockquote> `9-10`: **LGTM!** Separating endpoints for messages and models improves code clarity and supports the new model fetching capability. --- `22-27`: **LGTM!** The change from a strict type to `string` for the model parameter and the addition of usage metrics in the return type align with dynamic model support and token tracking requirements. --- `78-84`: **LGTM!** The method now correctly extracts usage metrics from the response and includes them in the return value. --- `87-87`: **LGTM!** The `testConnection()` method correctly accepts a string model parameter, consistent with dynamic model support. --- `139-145`: **LGTM!** The `makeRequestWithRetry()` method now returns the full `AnthropicResponse` object, enabling access to usage metrics and other response metadata. --- `184-210`: **LGTM!** The `fetchModels()` method is well-implemented with proper error handling and validation. The API key check, status code validation, and error message construction are all correct. --- `215-215`: **LGTM!** The `makeRequest()` method correctly uses `messagesUrl` for sending messages, consistent with the endpoint separation. </blockquote></details> </blockquote></details> </details> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=AlexKucera/freewriting-cleanup&utm_content=2)! 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+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKPR1AGxJcAZiWpcaLT0tLIYaMzwDJDMiiQekH64DAgYRIkULJAAghi4sJncUTlWAJKQABS2kGYATACUkJAG2Xiw+BRc2V4AHgDS2AzKkIAoBJAAyvjYFENcoeGRDGCxSh7IgEmEMM6knDFoiDR8Y+O41NiIXPjcZKOQAMIU/jS0XLUADLUArGAAjG9gtQAzNA3gAODi1ABsHB+AE4AFpuBDIFKYUiQR7cDxoIbIfIkSCwZy0JhKei5fKFYoreKQDxIXCQADu6lgkHmEWKSRS8DSGSy+JyeQKV2pcTWkDItG4+F5jMw9CCtGQaEgtQALGB2tMYNAADKMHGwAnXCiIBl0FBYLHYIi89nUVUs/I4AjMahctAeDwCHEAa0gBEDxsJxNJlvpBxQPmDBOyZRQyGw4Qk2mxAi8GkgfRI8lRaWkHAMUGywWQAFlxeNKBIogSg9y2QrDSkCWhU/B014YuLEABuFDMLEkNh5Cviu5Gglyyg+HEE51s8RsA4RbiJDq6g2p+m0D34LDNgBijxITIo6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xEah/jFNt4goDad2Esa5heIMAEMOTOnDGUJ2c2eaKIDkJRAsSlUBwmHFTBEAzKhwSIAlFOp6I+AEefxAcGpm0oEAWUEMNUGFI7JHYpvbSGsVIr2BBgTYMHm7ReKDhhwRWPXNjHKCVdXM0A9INc0EhIBmAlMBJBTzxhpMOg7UVVMyONC+IkK0My5Ip2Xh7TU8+qJUPuR/Z6RWRUwtYu/BUCdh1AIfGmfWE8CXILOP8G+MmGqSQQySGhV6eiEXC856YHSJALeDA7pBNwa0SgD/DwqyQNAU0waQoncizNCkB4EySXKClVTRpNU2QmkBrlRTHgKSaTDzMeCMScJFUkSU1LtDPo2pvjEyXTJ6lOS+pDUgaUFNckjSRJXEhgBjkFg/9SAzclibNLClaSIsDUliUtLilVzRpc8jHEwCXn0zIAbwDQG8DeAABScgfjOoTvhsAYFKIAwXDnZpsAj3DZAUBwazNiIyAUEGfIvmXzi5PcsudIArndTRpAATSmCGgo6yYYTGnCIT8JY4hchdHlHnmI4VBSkGwpkDBloLD5ecqgKQCAVbyRJdckSQ3LqnAK+5LUjwIPLYAdSSJgqMKQ1Mxyq4S4ZkhRHX1sBeSup8U0abCFBBQhaAkIAQICFhDyUVAG4n4AwE+B7i/5PgNcWgEBC0BAQe4msT4CnGghQQgIGsZCBkUqKfgJAUEJ8AYC0B1QoIYRXuDeACAVxJAAQG8AYAlzOF+wXALYHGkeTRpCivwAItUCwgNFNYhgGeNqB/BQQNYz4G8DAqQgSAV4nsT8DMWyKfgiSgRbQDeC0AaxPwXReqHVC0AZxPgURQwAvEFLRAOIJxXgsRyLzlApAEJHFS9AnAXI5EyHKwtYUFiIAT0kCWwBxIgTXJlfP8dGKAA== --> <!-- internal state end -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-10-23 15:09:46 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 4

🧹 Nitpick comments (10)
settings.ts (2)

52-56: Handle API key clearing; avoid unnecessary refresh.

Only refresh on non-empty keys, but also consider resetting to fallback models when the key is cleared to avoid repeated failed fetch attempts.

-                    // Trigger model refresh when API key is entered
-                    if (value.trim().length > 0) {
-                        await this.refreshModels();
-                    }
+                    // Refresh when key is entered; revert to fallback when cleared
+                    const hasKey = value.trim().length > 0;
+                    if (hasKey) {
+                        await this.refreshModels();
+                    } else if (this.modelDropdown) {
+                        // Show fallback immediately
+                        this.availableModels = this.plugin.modelService['getFallbackModels']?.()
+                          ?? this.availableModels;
+                        this.populateModelDropdown(this.modelDropdown);
+                    }

Note: If getFallbackModels is private, expose a public helper or call getAvailableModels() which will fall back without a key.


323-372: Prefer Obsidian Modal over custom DOM modal.

Using obsidian.Modal gives consistent styling, keyboard handling, and accessibility.

I can provide a small Modal subclass if you want to switch.

types.ts (2)

83-92: Remove AnthropicModel if no longer used.

Keeping AnthropicModel alongside string model can confuse downstream typing.

If unused, delete AnthropicModel and narrow ANTHROPIC_MODELS to readonly string[] for fallback only.


114-118: Static token/character limits risk drift.

Consider deriving per-model limits from the models API (if available) or centralize in ModelService.

I can draft a follow-up to surface context window per model and validate before requests.

services/cleanupService.ts (1)

39-48: Propagate token usage when available.

If AnthropicClient.cleanupText returns usage, plumb it into CleanupResult.tokensUsed.

-            const { cleanedText, commentary } = await this.client.cleanupText(
+            const { cleanedText, commentary, usage } = await this.client.cleanupText(
               text,
               settings.model,
               settings.cleanupPrompt,
               settings.enableCommentary,
               settings.commentaryStyle,
               settings.customCommentaryPrompt
             );
...
-                tokensUsed: {
-                    input: 0, // We don't have access to this from the response
-                    output: 0  // We don't have access to this from the response
-                }
+                tokensUsed: {
+                    input: usage?.input_tokens ?? 0,
+                    output: usage?.output_tokens ?? 0
+                }
main.ts (1)

25-30: Avoid double loadData() during onload.

You call loadData() in loadSettings() and again to fetch modelCache. Reuse the raw data or extend loadSettings to return it.

-        // Load model cache
-        const data = await this.loadData() as FreewritingCleanupData | null;
+        // Load model cache (reuse already loaded settings data if available)
+        const data = (await this.loadData()) as FreewritingCleanupData | null;
         if (data?.modelCache) {
             this.modelService.loadCache(data.modelCache);
         }

Or have loadSettings return the loaded data to avoid the second I/O.

services/modelService.ts (3)

51-61: Same for refresh: respect missing key and cache fallback.

     async refreshModels(): Promise<ModelOption[]> {
         try {
+            if (!this.anthropicClient.validateApiKey?.()) {
+                const fallback = this.getFallbackModels();
+                this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+                return fallback;
+            }
             const response = await this.anthropicClient.fetchModels();
             this.updateCache(response.data);
             return this.formatModels(response.data);
         } catch (error) {
             console.error('Failed to refresh models from API:', error);
             new Notice('Fetching current models failed. Using hardcoded fallback list.');
-            return this.getFallbackModels();
+            const fallback = this.getFallbackModels();
+            this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+            return fallback;
         }
     }

113-118: Stabilize option order for UX.

Sort by displayName to avoid jitter when cache/API ordering differs.

-    private formatModels(models: ModelInfo[]): ModelOption[] {
-        return models.map(model => ({
-            id: model.id,
-            displayName: model.display_name || model.id
-        }));
-    }
+    private formatModels(models: ModelInfo[]): ModelOption[] {
+        return models
+            .map(m => ({ id: m.id, displayName: m.display_name || m.id }))
+            .sort((a, b) => a.displayName.localeCompare(b.displayName));
+    }

121-129: Consider exposing fallback via a public helper.

Settings UI currently can’t call getFallbackModels directly. A small public getFallbackOptions() avoids poking at private methods.

api/anthropicClient.ts (1)

178-204: Well-implemented with consistent patterns.

The fetchModels() method follows the same patterns as makeRequest():

  • Proper API key validation
  • Correct HTTP method and headers
  • Consistent status code checking
  • Similar error handling approach

The type assertion on line 197 (as ModelsListResponse) matches the pattern used in makeRequest() at line 224. While runtime validation would add safety, the consistency with existing code is appropriate.

If you'd like to add runtime validation for the models response structure, consider using a validation library like Zod:

import { z } from 'zod';

const ModelsListResponseSchema = z.object({
    data: z.array(z.object({
        id: z.string(),
        display_name: z.string(),
        // ... other fields
    }))
});

// In fetchModels():
const parsed = ModelsListResponseSchema.parse(response.json);
return parsed;

This would catch unexpected API response structures early, though it adds a dependency.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b119923300 and 7b23ed6615.

📒 Files selected for processing (6)
  • api/anthropicClient.ts (4 hunks)
  • main.ts (2 hunks)
  • services/cleanupService.ts (5 hunks)
  • services/modelService.ts (1 hunks)
  • settings.ts (5 hunks)
  • types.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (6)
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to main.ts : Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point

Applied to files:

  • main.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to settings.ts : Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab

Applied to files:

  • main.ts
  • settings.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to settings.ts : Define DEFAULT_SETTINGS for FreewritingCleanupSettings

Applied to files:

  • main.ts
  • types.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to types.ts : Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts

Applied to files:

  • types.ts
📚 Learning: 2025-09-26T12:22:54.480Z
Learnt from: CR
PR: AlexKucera/freewriting-cleanup#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T12:22:54.480Z
Learning: Applies to services/cleanupService.ts : Encapsulate Anthropic API integration and connection testing in CleanupService

Applied to files:

  • services/cleanupService.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
🔇 Additional comments (6)
types.ts (2)

6-6: Model as string: LGTM.

This unblocks dynamic models and aligns with runtime API responses.


13-15: Persisting modelCache in settings data: good.

Keeps cache across restarts. Ensure save/load paths handle undefined safely (they do).

services/cleanupService.ts (1)

112-114: updateApiKey passthrough: LGTM.

Keeps ModelService’s client in sync via shared instance.

main.ts (1)

48-55: Persisting modelCache with settings: LGTM.

The composition with getCache() maintains TTL state across restarts.

api/anthropicClient.ts (2)

9-10: LGTM! Clean separation of concerns.

Splitting the base URL into dedicated endpoints for messages and models improves code clarity and follows the single responsibility principle.


22-22: Runtime validation exists at UI layer; API-level validation recommended for robustness.

The type change from AnthropicModel to string is intentional and necessary for dynamic model fetching. Validation does occur—the ModelService maintains a list of valid models, and the settings UI dropdown (settings.ts:227-229) restricts choices to available options, with a model existence check (line 252) before persisting selections.

However, validation is UI-layer only. The cleanupText() and testConnection() methods in anthropicClient.ts accept any string without validation. Consider adding a runtime check (e.g., validating against available models) to handle edge cases like manually edited settings or stale cache scenarios. Currently, invalid models will fail at the API level with error handling, which is acceptable but could be more graceful.

**Actionable comments posted: 4** <details> <summary>🧹 Nitpick comments (10)</summary><blockquote> <details> <summary>settings.ts (2)</summary><blockquote> `52-56`: **Handle API key clearing; avoid unnecessary refresh.** Only refresh on non-empty keys, but also consider resetting to fallback models when the key is cleared to avoid repeated failed fetch attempts. ```diff - // Trigger model refresh when API key is entered - if (value.trim().length > 0) { - await this.refreshModels(); - } + // Refresh when key is entered; revert to fallback when cleared + const hasKey = value.trim().length > 0; + if (hasKey) { + await this.refreshModels(); + } else if (this.modelDropdown) { + // Show fallback immediately + this.availableModels = this.plugin.modelService['getFallbackModels']?.() + ?? this.availableModels; + this.populateModelDropdown(this.modelDropdown); + } ``` Note: If getFallbackModels is private, expose a public helper or call getAvailableModels() which will fall back without a key. --- `323-372`: **Prefer Obsidian Modal over custom DOM modal.** Using obsidian.Modal gives consistent styling, keyboard handling, and accessibility. I can provide a small Modal subclass if you want to switch. </blockquote></details> <details> <summary>types.ts (2)</summary><blockquote> `83-92`: **Remove AnthropicModel if no longer used.** Keeping AnthropicModel alongside string model can confuse downstream typing. If unused, delete AnthropicModel and narrow ANTHROPIC_MODELS to readonly string[] for fallback only. --- `114-118`: **Static token/character limits risk drift.** Consider deriving per-model limits from the models API (if available) or centralize in ModelService. I can draft a follow-up to surface context window per model and validate before requests. </blockquote></details> <details> <summary>services/cleanupService.ts (1)</summary><blockquote> `39-48`: **Propagate token usage when available.** If AnthropicClient.cleanupText returns usage, plumb it into CleanupResult.tokensUsed. ```diff - const { cleanedText, commentary } = await this.client.cleanupText( + const { cleanedText, commentary, usage } = await this.client.cleanupText( text, settings.model, settings.cleanupPrompt, settings.enableCommentary, settings.commentaryStyle, settings.customCommentaryPrompt ); ... - tokensUsed: { - input: 0, // We don't have access to this from the response - output: 0 // We don't have access to this from the response - } + tokensUsed: { + input: usage?.input_tokens ?? 0, + output: usage?.output_tokens ?? 0 + } ``` </blockquote></details> <details> <summary>main.ts (1)</summary><blockquote> `25-30`: **Avoid double loadData() during onload.** You call loadData() in loadSettings() and again to fetch modelCache. Reuse the raw data or extend loadSettings to return it. ```diff - // Load model cache - const data = await this.loadData() as FreewritingCleanupData | null; + // Load model cache (reuse already loaded settings data if available) + const data = (await this.loadData()) as FreewritingCleanupData | null; if (data?.modelCache) { this.modelService.loadCache(data.modelCache); } ``` Or have loadSettings return the loaded data to avoid the second I/O. </blockquote></details> <details> <summary>services/modelService.ts (3)</summary><blockquote> `51-61`: **Same for refresh: respect missing key and cache fallback.** ```diff async refreshModels(): Promise<ModelOption[]> { try { + if (!this.anthropicClient.validateApiKey?.()) { + const fallback = this.getFallbackModels(); + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; + } const response = await this.anthropicClient.fetchModels(); this.updateCache(response.data); return this.formatModels(response.data); } catch (error) { console.error('Failed to refresh models from API:', error); new Notice('Fetching current models failed. Using hardcoded fallback list.'); - return this.getFallbackModels(); + const fallback = this.getFallbackModels(); + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; } } ``` --- `113-118`: **Stabilize option order for UX.** Sort by displayName to avoid jitter when cache/API ordering differs. ```diff - private formatModels(models: ModelInfo[]): ModelOption[] { - return models.map(model => ({ - id: model.id, - displayName: model.display_name || model.id - })); - } + private formatModels(models: ModelInfo[]): ModelOption[] { + return models + .map(m => ({ id: m.id, displayName: m.display_name || m.id })) + .sort((a, b) => a.displayName.localeCompare(b.displayName)); + } ``` --- `121-129`: **Consider exposing fallback via a public helper.** Settings UI currently can’t call getFallbackModels directly. A small public getFallbackOptions() avoids poking at private methods. </blockquote></details> <details> <summary>api/anthropicClient.ts (1)</summary><blockquote> `178-204`: **Well-implemented with consistent patterns.** The `fetchModels()` method follows the same patterns as `makeRequest()`: - Proper API key validation - Correct HTTP method and headers - Consistent status code checking - Similar error handling approach The type assertion on line 197 (`as ModelsListResponse`) matches the pattern used in `makeRequest()` at line 224. While runtime validation would add safety, the consistency with existing code is appropriate. If you'd like to add runtime validation for the models response structure, consider using a validation library like Zod: ```typescript import { z } from 'zod'; const ModelsListResponseSchema = z.object({ data: z.array(z.object({ id: z.string(), display_name: z.string(), // ... other fields })) }); // In fetchModels(): const parsed = ModelsListResponseSchema.parse(response.json); return parsed; ``` This would catch unexpected API response structures early, though it adds a dependency. </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 b11992330008ea126ae029e52a866978a4c48fad and 7b23ed6615a2847422d240abff35f054e3813a40. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `api/anthropicClient.ts` (4 hunks) * `main.ts` (2 hunks) * `services/cleanupService.ts` (5 hunks) * `services/modelService.ts` (1 hunks) * `settings.ts` (5 hunks) * `types.ts` (2 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧠 Learnings (6)</summary> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to main.ts : Main plugin class FreewritingCleanupPlugin extends obsidian Plugin and acts as the entry point ``` **Applied to files:** - `main.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to settings.ts : Provide settings UI in FreewritingCleanupSettingTab extending PluginSettingTab ``` **Applied to files:** - `main.ts` - `settings.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to settings.ts : Define DEFAULT_SETTINGS for FreewritingCleanupSettings ``` **Applied to files:** - `main.ts` - `types.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to types.ts : Centralize TypeScript interfaces (e.g., FreewritingCleanupSettings, API responses, plugin config) in types.ts ``` **Applied to files:** - `types.ts` </details> <details> <summary>📚 Learning: 2025-09-26T12:22:54.480Z</summary> ``` Learnt from: CR PR: AlexKucera/freewriting-cleanup#0 File: CLAUDE.md:0-0 Timestamp: 2025-09-26T12:22:54.480Z Learning: Applies to services/cleanupService.ts : Encapsulate Anthropic API integration and connection testing in CleanupService ``` **Applied to files:** - `services/cleanupService.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> </details> <details> <summary>🔇 Additional comments (6)</summary><blockquote> <details> <summary>types.ts (2)</summary><blockquote> `6-6`: **Model as string: LGTM.** This unblocks dynamic models and aligns with runtime API responses. --- `13-15`: **Persisting modelCache in settings data: good.** Keeps cache across restarts. Ensure save/load paths handle undefined safely (they do). </blockquote></details> <details> <summary>services/cleanupService.ts (1)</summary><blockquote> `112-114`: **updateApiKey passthrough: LGTM.** Keeps ModelService’s client in sync via shared instance. </blockquote></details> <details> <summary>main.ts (1)</summary><blockquote> `48-55`: **Persisting modelCache with settings: LGTM.** The composition with getCache() maintains TTL state across restarts. </blockquote></details> <details> <summary>api/anthropicClient.ts (2)</summary><blockquote> `9-10`: **LGTM! Clean separation of concerns.** Splitting the base URL into dedicated endpoints for messages and models improves code clarity and follows the single responsibility principle. --- `22-22`: **Runtime validation exists at UI layer; API-level validation recommended for robustness.** The type change from `AnthropicModel` to `string` is intentional and necessary for dynamic model fetching. Validation does occur—the ModelService maintains a list of valid models, and the settings UI dropdown (settings.ts:227-229) restricts choices to available options, with a model existence check (line 252) before persisting selections. However, validation is UI-layer only. The `cleanupText()` and `testConnection()` methods in anthropicClient.ts accept any string without validation. Consider adding a runtime check (e.g., validating against available models) to handle edge cases like manually edited settings or stale cache scenarios. Currently, invalid models will fail at the API level with error handling, which is acceptable but could be more graceful. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -0,0 +1,182 @@
// ABOUTME: Service for managing Claude model list from Anthropic API
coderabbitai[bot] (Migrated from github.com) commented 2025-10-23 15:09:45 +02:00

🛠️ Refactor suggestion | 🟠 Major

Early fallback when API key missing; also cache the fallback to reduce repeated Notices.

Skip network calls if no API key, and write fallback into cache with fetchedAt so subsequent calls don’t spam.

-    async getAvailableModels(): Promise<ModelOption[]> {
+    async getAvailableModels(): Promise<ModelOption[]> {
         // Check if we have a valid cache
         if (this.isCacheValid() && this.modelCache) {
             return this.formatModels(this.modelCache.models);
         }
 
-        // Try to fetch from API
+        // Try to fetch from API (bail early without key)
         try {
+            if (!this.anthropicClient.validateApiKey?.()) {
+                const fallback = this.getFallbackModels();
+                // write fallback into cache to honor TTL
+                this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+                return fallback;
+            }
             const response = await this.anthropicClient.fetchModels();
             this.updateCache(response.data);
             return this.formatModels(response.data);
         } catch (error) {
             console.error('Failed to fetch models from API:', error);
             new Notice('Fetching current models failed. Using hardcoded fallback list.');
-            return this.getFallbackModels();
+            const fallback = this.getFallbackModels();
+            this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo)));
+            return fallback;
         }
     }

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

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

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

✅ Addressed in commits eae4852 to f8427e7

_🛠️ Refactor suggestion_ | _🟠 Major_ **Early fallback when API key missing; also cache the fallback to reduce repeated Notices.** Skip network calls if no API key, and write fallback into cache with fetchedAt so subsequent calls don’t spam. ```diff - async getAvailableModels(): Promise<ModelOption[]> { + async getAvailableModels(): Promise<ModelOption[]> { // Check if we have a valid cache if (this.isCacheValid() && this.modelCache) { return this.formatModels(this.modelCache.models); } - // Try to fetch from API + // Try to fetch from API (bail early without key) try { + if (!this.anthropicClient.validateApiKey?.()) { + const fallback = this.getFallbackModels(); + // write fallback into cache to honor TTL + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; + } const response = await this.anthropicClient.fetchModels(); this.updateCache(response.data); return this.formatModels(response.data); } catch (error) { console.error('Failed to fetch models from API:', error); new Notice('Fetching current models failed. Using hardcoded fallback list.'); - return this.getFallbackModels(); + const fallback = this.getFallbackModels(); + this.updateCache(fallback.map(f => ({ id: f.id, display_name: f.displayName, created_at: '', type: 'model' } as ModelInfo))); + return fallback; } } ``` Note: If you prefer not to synthesize ModelInfo for fallback, adjust cache type to accept ModelOption or store a flag. > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In services/modelService.ts around lines 29 to 45, the method currently attempts an API fetch even when the API key may be missing and returns a hardcoded fallback without caching it; modify getAvailableModels to first detect a missing/empty API key and immediately return the fallback while also writing that fallback into the existing cache (include a fetchedAt timestamp) so subsequent calls use the cache and don’t repeatedly show Notices; if your cache expects ModelInfo instead of ModelOption, either synthesize minimal ModelInfo fields for the fallback or relax the cache type to accept ModelOption/union before writing the fallback into cache. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits eae4852 to f8427e7
@@ -16,6 +17,8 @@ export const DEFAULT_SETTINGS: FreewritingCleanupSettings = {
coderabbitai[bot] (Migrated from github.com) commented 2025-10-23 15:09:45 +02:00

⚠️ Potential issue | 🔴 Critical

Do not make display() async; Obsidian expects display(): void.

PluginSettingTab.display is typed as void. Overriding with Promise can break type compatibility and Obsidian won’t await it. Load models asynchronously without changing the signature.

Apply:

-    async display(): Promise<void> {
+    display(): void {
       const { containerEl } = this;
       containerEl.empty();
       containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' });
-      // Load models asynchronously
-      await this.loadModels();
+      // Begin async model load; UI will update when done
+      void this.loadModels().then(async () => {
+        if (this.modelDropdown) {
+          this.populateModelDropdown(this.modelDropdown);
+          const current = this.plugin.settings.model;
+          const exists = this.availableModels.some(m => m.id === current);
+          const fallback = this.availableModels[0]?.id;
+          if (!exists && fallback) {
+            this.modelDropdown.setValue(fallback);
+            this.plugin.settings.model = fallback;
+            await this.plugin.saveSettings();
+          }
+        }
+      });

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

🤖 Prompt for AI Agents
In settings.ts around lines 28 to 36, do not change display() to async; keep the
signature display(): void and remove the Promise return. Call this.loadModels()
without awaiting it (e.g., this.loadModels().then(() => { /* update UI if needed
*/ }).catch(err => { console.error(err); })), or start it in the background and
update the UI when it resolves. Ensure any UI updates that depend on models run
inside the then() callback (or use an internal async helper invoked but not
awaited) and surface load errors via console/logging instead of making the
display method async.

✅ Addressed in commits eae4852 to f8427e7

_⚠️ Potential issue_ | _🔴 Critical_ **Do not make display() async; Obsidian expects display(): void.** PluginSettingTab.display is typed as void. Overriding with Promise<void> can break type compatibility and Obsidian won’t await it. Load models asynchronously without changing the signature. Apply: ```diff - async display(): Promise<void> { + display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' }); - // Load models asynchronously - await this.loadModels(); + // Begin async model load; UI will update when done + void this.loadModels().then(async () => { + if (this.modelDropdown) { + this.populateModelDropdown(this.modelDropdown); + const current = this.plugin.settings.model; + const exists = this.availableModels.some(m => m.id === current); + const fallback = this.availableModels[0]?.id; + if (!exists && fallback) { + this.modelDropdown.setValue(fallback); + this.plugin.settings.model = fallback; + await this.plugin.saveSettings(); + } + } + }); ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In settings.ts around lines 28 to 36, do not change display() to async; keep the signature display(): void and remove the Promise return. Call this.loadModels() without awaiting it (e.g., this.loadModels().then(() => { /* update UI if needed */ }).catch(err => { console.error(err); })), or start it in the background and update the UI when it resolves. Ensure any UI updates that depend on models run inside the then() callback (or use an internal async helper invoked but not awaited) and surface load errors via console/logging instead of making the display method async. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits eae4852 to f8427e7
coderabbitai[bot] (Migrated from github.com) commented 2025-10-23 15:09:45 +02:00

⚠️ Potential issue | 🔴 Critical

Persist a valid selection when the current model disappears.

If the user’s saved model isn’t in the refreshed list, settings.model remains stale and later API calls may fail. Pick the first available option and save.

-                if (modelExists) {
-                    this.modelDropdown.setValue(currentModel);
-                }
+                if (modelExists) {
+                    this.modelDropdown.setValue(currentModel);
+                } else {
+                    const fallback = this.availableModels[0]?.id;
+                    if (fallback) {
+                        this.modelDropdown.setValue(fallback);
+                        this.plugin.settings.model = fallback;
+                        await this.plugin.saveSettings();
+                    }
+                }
🤖 Prompt for AI Agents
In settings.ts around lines 250 to 256, if the saved model is no longer in
availableModels you must replace the stale this.plugin.settings.model with a
valid choice: set this.plugin.settings.model = this.availableModels[0].id (or
the first available model's id), call this.modelDropdown.setValue(...) with that
id, and persist the change by invoking the repository's save method (e.g., await
this.plugin.saveSettings() or the existing saveSettings helper) so the new
selection is stored.

✅ Addressed in commits eae4852 to f8427e7

_⚠️ Potential issue_ | _🔴 Critical_ **Persist a valid selection when the current model disappears.** If the user’s saved model isn’t in the refreshed list, settings.model remains stale and later API calls may fail. Pick the first available option and save. ```diff - if (modelExists) { - this.modelDropdown.setValue(currentModel); - } + if (modelExists) { + this.modelDropdown.setValue(currentModel); + } else { + const fallback = this.availableModels[0]?.id; + if (fallback) { + this.modelDropdown.setValue(fallback); + this.plugin.settings.model = fallback; + await this.plugin.saveSettings(); + } + } ``` <details> <summary>🤖 Prompt for AI Agents</summary> ``` In settings.ts around lines 250 to 256, if the saved model is no longer in availableModels you must replace the stale this.plugin.settings.model with a valid choice: set this.plugin.settings.model = this.availableModels[0].id (or the first available model's id), call this.modelDropdown.setValue(...) with that id, and persist the change by invoking the repository's save method (e.g., await this.plugin.saveSettings() or the existing saveSettings helper) so the new selection is stored. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits eae4852 to f8427e7
coderabbitai[bot] (Migrated from github.com) commented 2025-10-23 15:09:45 +02:00

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify Anthropic models schema matches fields used.

Ensure /v1/models returns display_name, created_at, and type as modeled here.


🌐 Web query:

What fields does Anthropic’s /v1/models endpoint return for each model (id, display_name, created_at, type, and any token limit fields)?

💡 Result:

The /v1/models response returns these fields for each model: id, display_name, created_at, and type. [1][2]

It does not include token-limit / context-window fields in the /v1/models response — token limits are documented separately (e.g., in the Models Overview / model pages). [2][3]

Sources:

  • Get/List Models (Anthropic API docs). [1] [2]
  • Models overview (context-window / model specs). [3]

Fix display_name field to be required in ModelInfo interface.

Anthropic's /v1/models endpoint consistently returns display_name as a present field in model responses, so marking it as optional (display_name?: string) is incorrect. Change to display_name: string to match the API contract.

🤖 Prompt for AI Agents
In types.ts around lines 64 to 76, the ModelInfo interface incorrectly marks
display_name as optional; update the interface so display_name is a required
string (change display_name?: string to display_name: string) ensuring the type
matches the API contract and adjust any places that relied on it being optional
to treat display_name as always present.

✅ Addressed in commits eae4852 to f8427e7

_⚠️ Potential issue_ | _🔴 Critical_ <details> <summary>🧩 Analysis chain</summary> **Verify Anthropic models schema matches fields used.** Ensure /v1/models returns display_name, created_at, and type as modeled here. --- 🌐 Web query: ```web What fields does Anthropic’s /v1/models endpoint return for each model (id, display_name, created_at, type, and any token limit fields)? ``` 💡 Result: The /v1/models response returns these fields for each model: id, display_name, created_at, and type. [1][2] It does not include token-limit / context-window fields in the /v1/models response — token limits are documented separately (e.g., in the Models Overview / model pages). [2][3] Sources: - Get/List Models (Anthropic API docs). [1] [2] - Models overview (context-window / model specs). [3] --- </details> **Fix display_name field to be required in ModelInfo interface.** Anthropic's /v1/models endpoint consistently returns display_name as a present field in model responses, so marking it as optional (`display_name?: string`) is incorrect. Change to `display_name: string` to match the API contract. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In types.ts around lines 64 to 76, the ModelInfo interface incorrectly marks display_name as optional; update the interface so display_name is a required string (change display_name?: string to display_name: string) ensuring the type matches the API contract and adjust any places that relied on it being optional to treat display_name as always present. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits eae4852 to f8427e7
AlexKucera commented 2025-10-24 11:09:01 +02:00 (Migrated from github.com)

@coderabbitai generate docstrings

@coderabbitai generate docstrings
coderabbitai[bot] commented 2025-10-24 11:09:28 +02:00 (Migrated from github.com)
✅ Actions performed

Initiated docstring generation; will generate only if new commits exist.

<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>✅ Actions performed</summary> Initiated docstring generation; will generate only if new commits exist. </details>
coderabbitai[bot] commented 2025-10-24 11:09:31 +02:00 (Migrated from github.com)

Caution

Docstrings generation - FAILED

No docstrings were generated.

> [!CAUTION] > Docstrings generation - FAILED > > No docstrings were generated. <!--DOCSTRING_INTERNAL_START_STATE>N4Igxg9gtlCWAuBJAJiAXCAZgDgCwCYB2AU0PwEMAGcgIwEZNkBWY5Tc7TSgTgDZcmTbnV6FKAZl7kwhXJhAAaEACdiAN1jEA7gH0AzvHLwArnvQhiy5RGUgAvkA <!--DOCSTRING_INTERNAL_END_STATE>
Sign in to join this conversation.