Introduces a comprehensive model management system for Anthropic Claude models with the following key improvements:
Features
Dynamically fetch available Claude models from Anthropic API
Implement 24-hour caching mechanism for model list
Provide fallback to hardcoded model list if API request fails
Enhance settings UI with dynamic model dropdown
Improvements
Prevents race conditions in timed prompts generation
Simplifies cursor placement after prompt insertion
Removes unnecessary error notifications
Improves overall plugin robustness and flexibility
Changes
Created new ModelService for managing model list
Updated AnthropicClient to support model list fetching
Improved error handling and user experience in settings
Updated repository links and licensing information
Additional Notes
Enables more dynamic and up-to-date model selection for AI-powered writing prompts.
Summary by CodeRabbit
New Features
Dynamic Claude model management with caching, refresh, API-key testing, and a model dropdown; prompt-generation caching; Timed Prompts and Note Prompts commands with start/stop/status and improved plugin lifecycle.
Bug Fixes
Better prompt insertion (cursor/newline handling), prevented concurrent timed runs, ensured proper stop/cleanup and clearer user notices.
## Overview
Introduces a comprehensive model management system for Anthropic Claude models with the following key improvements:
### Features
- Dynamically fetch available Claude models from Anthropic API
- Implement 24-hour caching mechanism for model list
- Provide fallback to hardcoded model list if API request fails
- Enhance settings UI with dynamic model dropdown
### Improvements
- Prevents race conditions in timed prompts generation
- Simplifies cursor placement after prompt insertion
- Removes unnecessary error notifications
- Improves overall plugin robustness and flexibility
### Changes
- Created new ModelService for managing model list
- Updated AnthropicClient to support model list fetching
- Improved error handling and user experience in settings
- Updated repository links and licensing information
## Additional Notes
Enables more dynamic and up-to-date model selection for AI-powered writing prompts.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
* **New Features**
* Dynamic Claude model management with caching, refresh, API-key testing, and a model dropdown; prompt-generation caching; Timed Prompts and Note Prompts commands with start/stop/status and improved plugin lifecycle.
* **Bug Fixes**
* Better prompt insertion (cursor/newline handling), prevented concurrent timed runs, ensured proper stop/cleanup and clearer user notices.
* **Chores / Documentation**
* Updated repository links, author, license (GPL‑3.0), changelog dates/content, release workflow action version, and linting configuration.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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>
Updated CI release action and repository references; changed license/author metadata; added model discovery, caching, and UI dropdown; refactored Anthropic client for messages/models endpoints and key testing; added ModelService and PromptGenerator caching; introduced timed and note prompt commands and plugin lifecycle/settings updates.
Bumped softprops/action-gh-release v1 → v2; normalized repo owner/name capitalization in links; updated changelog dates/entries; changed license MIT → GPL‑3.0‑only and updated author; adjusted package devDependencies and metadata.
Type Definitions types.ts
Introduced ModelId, ModelInfo, ModelsListResponse, ModelCache, AnthropicMessage, AnthropicRequest, AnthropicResponse, GeneratedPrompt, FreewritingPromptsData; changed FreewritingPromptsSettings.model to ModelId; added ANTHROPIC_MODELS and related type.
Anthropic API Client api/anthropicClient.ts
Reworked client to use model/messages endpoints and versioning; model parameter types → string; added fetchModels(), testApiKey(), API key management (updateApiKey, validateApiKey), and helpers for requests, parsing, pagination, dedupe, and error handling.
Model Service (new) services/modelService.ts
New ModelService + ModelOption: 24‑hour cache, refresh/load/clear, in‑flight dedupe, API-backed fetch with hardcoded fallback, formatting for UI, Notice gating, and cache persistence hooks.
Prompt Generator services/promptGenerator.ts
Replaced AnthropicModel with string; added generateTimedPrompts/generateNotePrompts, 10‑minute prompt cache, updateApiKey, clearCache, cache keying, anthropicClient getter, and stricter settings validation (Claude model required).
Plugin Core main.ts
Added modelService: ModelService; load/persist modelCache with settings; initialize ModelService; stop/cleanup timed prompts on unload; register commands (timed, note, stop); API-key changes clear model cache; removed old loadSettings.
Settings UI settings.ts
Added async model loading and dynamic model dropdown, API-key debounce and test flow, model refresh/clear-cache actions, UI state for loading/refreshing/disabled, hide() lifecycle method, and user Notices for model availability and tests.
TimedPromptsCommand: new class for interval sequencing, lifecycle (start/stop/isRunning/getStatus/getRemainingPrompts), concurrency guards. NotePromptsCommand: insert numbered, timestamped prompts into active note with insertion/formatting helpers and editor/view checks.
main.ts & settings.ts — lifecycle (load/save modelCache), debounced API-key handling, UI state transitions, and command registration.
Lint/config changes — ensure eslint.config.mjs aligns with CI/tooling and tsconfig.
Poem
🐇 I hopped through types and chased a model name,
Cached sleepy lists so dropdowns play the game,
Timers drum their prompts while notes land neat and bright,
Keys get tested, caches cleared, the UI hums at night,
I twitch my nose — the plugin hops to light!
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 pull request title "Adds dynamic Claude model fetching and management" is specific, clear, and directly aligned with the primary objective of the changeset. The title accurately reflects the core feature being introduced: a model management system that dynamically fetches available Claude models from the Anthropic API with caching support. While the PR includes other supporting changes (command refactoring, service architecture updates, license updates, and ESLint configuration changes), these are secondary to the main feature of model management. A teammate reviewing the commit history would clearly understand that this PR introduces dynamic model management capabilities, which is the primary focus of the changes.
✨ 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 9b8ff3181a and 4cb2308bd6.
The comprehensive JSDoc comment clearly articulates the command's purpose, key responsibilities, and implementation details. This makes the code highly maintainable and easy to understand for future developers.
61-104: Concurrency handling is now correct!
The race condition flagged in the previous review has been properly addressed:
inProgress is set to truebefore calling stop() and before any async work (line 69)
The finally block (lines 99-103) ensures the flag is always reset, preventing stuck state
The guard at lines 62-66 reliably prevents concurrent executions during prompt generation
The logic flow is clean and handles all edge cases (empty prompts, single prompt, errors) correctly.
106-124: Clean separation of concerns.
The documentation and implementation clearly establish that stop() handles only interval and queue cleanup, while execute() owns the inProgress lifecycle. This design prevents the race condition that existed in earlier versions and makes the concurrency model easy to reason about.
173-198: Notification duration logic is correct and smooth.
The boundary discontinuity from the previous review has been resolved:
The >= operator (line 185) matches the comment ">=1s" (line 180)
Creates a smooth transition at the 1-second boundary
The 300ms minimum clamp prevents flickering or invisible notices
Notifications end 500ms before the next one for clean transitions
The duration calculations are correct across all delay ranges and provide a polished user experience.
api/anthropicClient.ts (5)
4-49: LGTM! Clean API client setup with centralized configuration.
The imports, class structure, and constants are well-organized. Centralizing API_BASE and API_VERSION prevents drift, and the prompt modifiers are clearly documented for their specific use cases (timed vs. note prompts).
71-111: LGTM! Well-structured prompt generation with appropriate optimizations.
The method correctly applies type-specific modifiers and uses smaller max_tokens for timed prompts to reduce latency and cost. Error handling is appropriate, and the delegation to helper methods keeps the code clean.
125-243: Excellent pagination implementation with comprehensive safety guards.
All previous concerns have been thoroughly addressed:
✅ Full pagination support with after_id parameter (line 156)
✅ Loop safety with maxIterations check (lines 145-149)
✅ Deduplication using seenIds Set (lines 191-194)
✅ Cursor advancement validation (lines 207-212)
✅ Consistent pagination metadata after sorting (lines 225-228)
The implementation is robust, well-documented, and handles edge cases appropriately. The use of limit=1000 minimizes API round trips, and the sorted output ensures stable UX.
257-345: LGTM! Helper methods are well-implemented with proper error handling.
The helper methods are focused and handle their responsibilities correctly:
createUserMessage adapts to example presence
makeRequest uses centralized configuration and proper headers
parsePromptsFromResponse correctly handles multiple content blocks (lines 320-325) and strips various list formats
382-538: LGTM! Robust API key testing with comprehensive error handling.
The testApiKey method correctly validates the API key with a minimal request and checks that the response follows instructions precisely (lines 414-425). The normalization logic appropriately handles common variations like punctuation and capitalization while remaining strict enough to detect API issues.
The parseTestError method provides excellent error categorization and user-friendly messages for different failure scenarios, which will significantly improve the troubleshooting experience.
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.
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
Updated CI release action and repository references; changed license/author metadata; added model discovery, caching, and UI dropdown; refactored Anthropic client for messages/models endpoints and key testing; added ModelService and PromptGenerator caching; introduced timed and note prompt commands and plugin lifecycle/settings updates.
## Changes
| Cohort / File(s) | Summary |
|---|---|
| **Release & Repo Metadata** <br> `\.github/workflows/release.yml`, `CHANGELOG.md`, `README.md`, `package.json` | Bumped `softprops/action-gh-release` v1 → v2; normalized repo owner/name capitalization in links; updated changelog dates/entries; changed license MIT → GPL‑3.0‑only and updated author; adjusted package devDependencies and metadata. |
| **Type Definitions** <br> `types.ts` | Introduced `ModelId`, `ModelInfo`, `ModelsListResponse`, `ModelCache`, `AnthropicMessage`, `AnthropicRequest`, `AnthropicResponse`, `GeneratedPrompt`, `FreewritingPromptsData`; changed `FreewritingPromptsSettings.model` to `ModelId`; added `ANTHROPIC_MODELS` and related type. |
| **Anthropic API Client** <br> `api/anthropicClient.ts` | Reworked client to use model/messages endpoints and versioning; model parameter types → `string`; added `fetchModels()`, `testApiKey()`, API key management (`updateApiKey`, `validateApiKey`), and helpers for requests, parsing, pagination, dedupe, and error handling. |
| **Model Service (new)** <br> `services/modelService.ts` | New `ModelService` + `ModelOption`: 24‑hour cache, refresh/load/clear, in‑flight dedupe, API-backed fetch with hardcoded fallback, formatting for UI, Notice gating, and cache persistence hooks. |
| **Prompt Generator** <br> `services/promptGenerator.ts` | Replaced `AnthropicModel` with `string`; added `generateTimedPrompts`/`generateNotePrompts`, 10‑minute prompt cache, `updateApiKey`, `clearCache`, cache keying, `anthropicClient` getter, and stricter settings validation (Claude model required). |
| **Plugin Core** <br> `main.ts` | Added `modelService: ModelService`; load/persist `modelCache` with settings; initialize ModelService; stop/cleanup timed prompts on unload; register commands (timed, note, stop); API-key changes clear model cache; removed old `loadSettings`. |
| **Settings UI** <br> `settings.ts` | Added async model loading and dynamic model dropdown, API-key debounce and test flow, model refresh/clear-cache actions, UI state for loading/refreshing/disabled, `hide()` lifecycle method, and user Notices for model availability and tests. |
| **Commands** <br> `commands/timedPrompts.ts`, `commands/notePrompts.ts` | `TimedPromptsCommand`: new class for interval sequencing, lifecycle (start/stop/isRunning/getStatus/getRemainingPrompts), concurrency guards. `NotePromptsCommand`: insert numbered, timestamped prompts into active note with insertion/formatting helpers and editor/view checks. |
| **Linting / Tooling** <br> `.eslintrc`, `eslint.config.mjs`, `.eslintignore` | Removed legacy `.eslintrc`; added `eslint.config.mjs` TypeScript-aware config with explicit ignores and rules; `.eslintignore` entries adjusted. |
| **Other** <br> `package.json` (devDeps/metadata) | TypeScript upgraded; ESLint/devDependency reshuffle and new packages added; keywords formatting updated; metadata edits (author/license). |
## Sequence Diagram(s)
```mermaid
sequenceDiagram
participant User
participant SettingsUI as Settings UI
participant ModelService
participant AnthropicClient as Anthropic Client
participant Plugin as Plugin Core
participant PromptGen as Prompt Generator
Note right of ModelService #eef2ff: Cache TTL 24h / fallback
User->>SettingsUI: Open settings
activate SettingsUI
SettingsUI->>ModelService: getAvailableModels()
activate ModelService
alt cache valid
ModelService-->>SettingsUI: ModelOption[] (cached)
else
ModelService->>AnthropicClient: fetchModels()
activate AnthropicClient
AnthropicClient-->>ModelService: ModelsListResponse
deactivate AnthropicClient
ModelService->>ModelService: updateCache()
ModelService-->>SettingsUI: ModelOption[] (fresh)
end
deactivate ModelService
SettingsUI->>SettingsUI: populate dropdown
deactivate SettingsUI
User->>Plugin: Trigger timed prompts
Plugin->>PromptGen: generateTimedPrompts(settings)
activate PromptGen
PromptGen-->>Plugin: prompts[]
deactivate PromptGen
Plugin->>Plugin: Start TimedPromptsCommand (intervals)
Plugin->>User: Notices shown per interval
```
## Estimated code review effort
🎯 4 (Complex) | ⏱️ ~60 minutes
- Pay extra attention to:
- api/anthropicClient.ts — request/response parsing, pagination, deduplication, and error classification.
- services/modelService.ts — cache TTL behavior, in‑flight dedupe, fallback notice gating, and persistence/load integration.
- services/promptGenerator.ts & commands/* — cache key correctness, prompt-count limits, concurrency, and editor insertion edge cases.
- main.ts & settings.ts — lifecycle (load/save modelCache), debounced API-key handling, UI state transitions, and command registration.
- Lint/config changes — ensure eslint.config.mjs aligns with CI/tooling and tsconfig.
## Poem
> 🐇 I hopped through types and chased a model name,
> Cached sleepy lists so dropdowns play the game,
> Timers drum their prompts while notes land neat and bright,
> Keys get tested, caches cleared, the UI hums at night,
> I twitch my nose — the plugin hops to light!
<!-- 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 pull request title "Adds dynamic Claude model fetching and management" is specific, clear, and directly aligned with the primary objective of the changeset. The title accurately reflects the core feature being introduced: a model management system that dynamically fetches available Claude models from the Anthropic API with caching support. While the PR includes other supporting changes (command refactoring, service architecture updates, license updates, and ESLint configuration changes), these are secondary to the main feature of model management. A teammate reviewing the commit history would clearly understand that this PR introduces dynamic model management capabilities, which is the primary focus of the changes. |
</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 9b8ff3181aba03386174722e9d2e87e8171ce1f7 and 4cb2308bd62772f50fc8e7171c2492babbea0870.
</details>
<details>
<summary>📒 Files selected for processing (2)</summary>
* `api/anthropicClient.ts` (8 hunks)
* `commands/timedPrompts.ts` (4 hunks)
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>🧬 Code graph analysis (2)</summary>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
<details>
<summary>types.ts (4)</summary>
* `AnthropicRequest` (57-66)
* `ModelsListResponse` (131-140)
* `ModelInfo` (116-125)
* `AnthropicResponse` (72-99)
</details>
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (1)</summary><blockquote>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (9)</summary><blockquote>
<details>
<summary>commands/timedPrompts.ts (4)</summary><blockquote>
`8-24`: **Excellent documentation!**
The comprehensive JSDoc comment clearly articulates the command's purpose, key responsibilities, and implementation details. This makes the code highly maintainable and easy to understand for future developers.
---
`61-104`: **Concurrency handling is now correct!**
The race condition flagged in the previous review has been properly addressed:
- `inProgress` is set to `true` **before** calling `stop()` and before any async work (line 69)
- The `finally` block (lines 99-103) ensures the flag is always reset, preventing stuck state
- The guard at lines 62-66 reliably prevents concurrent executions during prompt generation
The logic flow is clean and handles all edge cases (empty prompts, single prompt, errors) correctly.
---
`106-124`: **Clean separation of concerns.**
The documentation and implementation clearly establish that `stop()` handles only interval and queue cleanup, while `execute()` owns the `inProgress` lifecycle. This design prevents the race condition that existed in earlier versions and makes the concurrency model easy to reason about.
---
`173-198`: **Notification duration logic is correct and smooth.**
The boundary discontinuity from the previous review has been resolved:
- The `>=` operator (line 185) matches the comment ">=1s" (line 180)
- Creates a smooth transition at the 1-second boundary
- The 300ms minimum clamp prevents flickering or invisible notices
- Notifications end 500ms before the next one for clean transitions
The duration calculations are correct across all delay ranges and provide a polished user experience.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (5)</summary><blockquote>
`4-49`: **LGTM! Clean API client setup with centralized configuration.**
The imports, class structure, and constants are well-organized. Centralizing `API_BASE` and `API_VERSION` prevents drift, and the prompt modifiers are clearly documented for their specific use cases (timed vs. note prompts).
---
`71-111`: **LGTM! Well-structured prompt generation with appropriate optimizations.**
The method correctly applies type-specific modifiers and uses smaller `max_tokens` for timed prompts to reduce latency and cost. Error handling is appropriate, and the delegation to helper methods keeps the code clean.
---
`125-243`: **Excellent pagination implementation with comprehensive safety guards.**
All previous concerns have been thoroughly addressed:
- ✅ Full pagination support with `after_id` parameter (line 156)
- ✅ Loop safety with `maxIterations` check (lines 145-149)
- ✅ Deduplication using `seenIds` Set (lines 191-194)
- ✅ Cursor advancement validation (lines 207-212)
- ✅ Consistent pagination metadata after sorting (lines 225-228)
The implementation is robust, well-documented, and handles edge cases appropriately. The use of `limit=1000` minimizes API round trips, and the sorted output ensures stable UX.
---
`257-345`: **LGTM! Helper methods are well-implemented with proper error handling.**
The helper methods are focused and handle their responsibilities correctly:
- `createUserMessage` adapts to example presence
- `makeRequest` uses centralized configuration and proper headers
- `parsePromptsFromResponse` correctly handles multiple content blocks (lines 320-325) and strips various list formats
---
`382-538`: **LGTM! Robust API key testing with comprehensive error handling.**
The `testApiKey` method correctly validates the API key with a minimal request and checks that the response follows instructions precisely (lines 414-425). The normalization logic appropriately handles common variations like punctuation and capitalization while remaining strict enough to detect API issues.
The `parseTestError` method provides excellent error categorization and user-friendly messages for different failure scenarios, which will significantly improve the troubleshooting experience.
</blockquote></details>
</blockquote></details>
</details>
<!-- tips_start -->
---
Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=AlexKucera/freewriting-prompts&utm_content=1)! 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+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKPR1AGxJcAgrVrItLIYaMzwDJAAwh5o2EqQzIokHpAAZiS4DAgYROgY9MyYaKRsGLiQABS2kGYAjACUkJAGAKqIlL5eAB4A0tgMypCAKAT2+NgUA1xBIWEMYIlKHsiASYSQuM6knAloiDR8IwDK67jYiFz43GTDURQk1HRcAEwADI8ArGC1z2CPAMzQzwAHBxHgA2DhvQEALSarRsABkuLBcLhuGcAPToojqWDYAQaJjMdE+bp9AZUdGpW4kADuFHU8ByYF4LG4uEQ6O42A8HnRtSMABFpAx6Wz4PgsBVUmgxIh6hwDFAAJJlCiKfrSdAJJIpQohErseyyXYkZhpfB8HxlWBq7jhKIxOIkbWLRAaRWQABidxOtzOBiaUAFwVC4TQPPk6UysE1aAk2hiAi8Dti8QWyWQVJYaxjkCtuBtF3tPisSvdgcgSuY3C8pXZWseABYwLAxnwGDLsrk2FlMEgzakLTnnemUh4kJoA7prGqJPAlMg0Glwx4BDKANZrfBa2DOWhMJQFHWQce7FCpYd50uQW4AR2w0nK0vgS3L078AS101DEVHkFotq0PgNJYIyl7tCijJEMgLRlh6VYslIdb+hWVi3FIZTIFQAwKPkDISsgYHiGw9AstW9akOQVDiBKb5QAc8DVuOqTwJqDDjIgQ41jKpqGmgqR7DwarkSgGDtBQNEYHRkA2Ka+BSMg2AYOQAyIIgzjyJQap8Bg+DiCxHaSW6U7KtWs6avJyg8jwHjYNiWBqgIpy4OQal5PQqTdPAajjrgsjulAkS7jk0gKhWH6LpA5A0pAACyOoHJQc44QQ2z6s6BYjsep6ThWLTcLQ9zIPmhZ2gw0SsWUW72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oMR7mRUiQBey/9pwpKGxsnWAHWPcHWpka30Pdg7w2GrGDh2pSY6DOmSRH5REm0dEERtu6ZjfzVGDUKuoAA6ggDJgAKNUB/+FkJlB8AoonFxBqYxueZ/cJKJkh3YvWPGp4I6shDBvU6SB+o7K2JN1ovMzIb6E1CcOLYaZQrSGSGgYOOC7hE6/whcmwWzvseAPJZhHmBGYoQL7BAIowZwg74N2IAQJIKCS1LOAO8BMaf8rftXAFgqAPCm3JgQG8m/gnKcMmGgHYGfCZO7VLLCIc4QBESoASybbyDg2CK7ibJOauEk1J3Cn6B50RbEEqZw8SfYnpgMSc4BxJ5SdalUeZYepTEJCCVamJJH8MkmpJRSZnB7JRiQnq5JOiX6mFJbAMYl2Ut1FjA/apAI6mRJlSRIkkJ7qQ4ncQPUVkmZw1CRjg6GTAImnkoyAMFjPAAAKS7w+qWwI9I2AIrgXG3KfKE42Yfl7p501GMgCAgpaWWmWpliVrDSAtqc4ncK3pGMCmkDkEpBpo4sLNFSwosE/wjs+aXQlsSOmOZCzp8aYWnKAnysmlkJzqZnCxJUEBulRBSSXdBBpMaZnBwit1LIrhpU4L4EqJOwBuI2AJiWYoNJmcM8AdgzwArGggzwHzEkAvwE9FvAGca9GPAHYAPT/R2sakAAZ2MerHDxAgI2DfRSMeTH+Ahsf3HfRTcVjFCx6ipXGOx8SRrA0+tgCUlGJmcBrHPoTcY2DXoTYPDHqKdsY8A3xm8f9HKxrwDzFoxH0b7FvAtQFnEexHMajFpx76VXHGxqQM9GggP0W9HEZmGaen40NTEWk06d0Lmx4ZkAFQyYBmARLGvEX8UaYRMf8XkRvx+gEAA=== -->
<!-- internal state end -->
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
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)
README.md (1)
4-4: Fix license badge: shows MIT but should show GPL-3.0.
The license badge still references MIT with incorrect links, but the project is now licensed under GPL-3.0-only. This misrepresents the actual license to users.
12-12: Consider notifying the user when execution is already in progress.
The race condition guard correctly prevents concurrent invocations, but the early return provides no feedback to the user about why nothing happened.
Apply this diff to notify the user:
// Check if already in progress to prevent race conditions
if (this.inProgress) {
+ new Notice('Timed prompts are already being generated. Please wait.');
return;
}
Also applies to: 19-22
settings.ts (2)
30-37: Consider showing a loading indicator during model loading.
The async model loading before rendering settings is correct, but there's no visual feedback to the user during this potentially slow operation.
You could add a temporary notice or loading state:
asyncdisplay():Promise<void>{const{containerEl}=this;containerEl.empty();containerEl.createEl('h2',{text:'Freewriting Prompts'});// Show loading state
constloadingEl=containerEl.createEl('p',{text:'Loading models...'});awaitthis.loadModels();// Remove loading state
loadingEl.remove();// Continue with settings...
}
227-257: Handle the case where the selected model is no longer available.
The logic preserves the selected model if it still exists after refresh (lines 244-248), but doesn't handle the case where it no longer exists. This could leave the settings in an invalid state with a model ID that's no longer available.
Apply this diff to handle the missing model case:
// Restore selected model if it still exists
const currentModel = this.plugin.settings.model;
const modelExists = this.availableModels.some(m => m.id === currentModel);
if (modelExists) {
this.modelDropdown.setValue(currentModel);
+ } else if (this.availableModels.length > 0) {
+ // Fall back to first available model if current one is gone
+ this.plugin.settings.model = this.availableModels[0].id;
+ this.modelDropdown.setValue(this.availableModels[0].id);
+ new Notice('Your selected model is no longer available. Defaulting to ' + this.availableModels[0].displayName);
}
}
services/modelService.ts (1)
29-45: Consider more specific error messaging.
The fallback mechanism is solid, but the Notice message on line 42 could be more informative about why it failed and what the fallback list represents (e.g., "Could not fetch latest models from API. Using default model list.").
Apply this diff for clearer messaging:
- new Notice('Fetching current models failed. Using hardcoded fallback list.');
+ new Notice('Could not fetch latest models from API. Using default model list.');
main.ts (1)
19-32: Consider optimizing data loading.
The loadData() is called twice: once in loadSettings() (line 20) and again explicitly for the model cache (line 29). While this works correctly, it's slightly inefficient.
Reviewing files that changed from the base of the PR and between 520ac6e826 and 20530142e4.
📒 Files selected for processing (12)
.github/workflows/release.yml (2 hunks)
CHANGELOG.md (4 hunks)
README.md (2 hunks)
api/anthropicClient.ts (5 hunks)
commands/notePrompts.ts (1 hunks)
commands/timedPrompts.ts (4 hunks)
main.ts (3 hunks)
package.json (1 hunks)
services/modelService.ts (1 hunks)
services/promptGenerator.ts (4 hunks)
settings.ts (5 hunks)
types.ts (3 hunks)
🔇 Additional comments (25)
package.json (1)
12-13: Metadata updates align with repository ownership and licensing changes.
Author and license fields are now correctly updated to reflect the actual project maintainer (Alexander Kucera) and GPL-3.0 licensing. These changes are consistent with updates in README, CHANGELOG, and the release workflow.
README.md (1)
229-230: Repository references and license documentation are correctly updated.
The GitHub links (Issues, Discussions), clone URL, and license statement all consistently reflect the new repository ownership (AlexKucera/freewriting-prompts) and GPL-3.0 licensing.
Also applies to: 238-239, 287-287
CHANGELOG.md (1)
90-93: Version links correctly reference the updated repository.
All compare and release links in the footer have been updated to point to AlexKucera/freewriting-prompts, maintaining referential integrity with the repository ownership changes.
.github/workflows/release.yml (1)
111-111: Workflow action and BRAT reference correctly updated.
The GitHub Actions release action has been bumped to v2, and the BRAT plugin repository reference now correctly points to AlexKucera/freewriting-prompts, aligning with the repository ownership changes.
Also applies to: 130-130
commands/notePrompts.ts (2)
78-78: LGTM! Cursor positioning logic is correct.
The cursor is positioned at the end of the inserted content, which provides good UX by leaving the cursor ready for the user to continue typing.
37-40: ****
The service layer properly handles user notifications. When promptGenerator.generateNotePrompts() encounters errors, the catch block (lines 87-94) shows a Notice with the error message to the user, and includes a fallback notice for unknown errors. Users will not experience silent failures.
commands/timedPrompts.ts (3)
27-27: LGTM!
The finally block ensures inProgress is always reset, even when errors occur. The flag is correctly set after stopping any existing sequence.
Also applies to: 52-54
64-64: LGTM!
Resetting inProgress in stop() ensures the flag is cleared when the sequence is stopped, maintaining consistency with the concurrency control pattern.
112-121: LGTM!
The dynamic computation ensures getStatus() returns accurate values based on the current promptQueue state rather than stale field values. The edge case handling for empty queues and the Math.min guard are both correct.
services/promptGenerator.ts (2)
6-6: LGTM!
The model parameter type change from AnthropicModel to string correctly supports dynamic model selection and aligns with the broader PR objectives.
Also applies to: 55-61, 98-113
121-125: LGTM!
The empty cache guard prevents returning invalid cached results and cleans up the cache entry. This is good defensive programming that ensures cache integrity.
settings.ts (3)
53-58: LGTM!
Automatically refreshing models when an API key is entered provides good UX and ensures the model list is up-to-date with the new credentials.
198-225: LGTM!
The model loading and dropdown population logic is well-structured. It correctly handles the empty models case by disabling the dropdown and showing appropriate feedback.
4-4: LGTM!
The new imports and fields support the dynamic model loading functionality correctly.
Also applies to: 7-7, 22-23
types.ts (2)
4-17: LGTM!
The model type change to string correctly enables dynamic model selection, and the FreewritingPromptsData interface provides a clean pattern for persisting additional data alongside settings. The optional modelCache field ensures backward compatibility with existing saved data.
53-70: LGTM!
The new model-related interfaces are well-structured and align with the Anthropic API response format. The ModelCache interface correctly includes a timestamp field for TTL validation.
api/anthropicClient.ts (3)
9-10: LGTM!
The separation of messages and models endpoints is appropriate for the new functionality, and the model parameter type change to string aligns with the dynamic model selection feature across the codebase.
Also applies to: 21-27, 103-103, 163-163
60-86: LGTM!
The fetchModels() implementation follows the same pattern as existing methods with consistent error handling, API key validation, and proper typing. The use of the /v1/models endpoint is correct for fetching available models.
4-5: LGTM!
The import changes correctly support the new fetchModels() functionality and align with the model type changes.
services/modelService.ts (4)
1-20: LGTM!
The ModelService class structure is clean and well-organized. The 24-hour cache TTL is reasonable for model list data, and the ModelOption interface provides a good abstraction for the dropdown UI.
47-61: LGTM!
The refreshModels() method correctly bypasses the cache for forced refreshes, which is appropriate when the API key changes. The error handling is consistent with getAvailableModels().
63-107: LGTM!
The cache management methods provide a clean public API for persistence, and the cache validity logic correctly checks the TTL using timestamp comparison.
109-128: Verify fallback model list coverage.
The fallback mechanism correctly uses the hardcoded ANTHROPIC_MODELS list, but if a user has previously selected a newer model (not in the hardcoded list) and the API fails, their selected model won't appear in the dropdown. This could cause confusion.
Consider checking the hardcoded list to ensure it includes commonly used models. You might also want to add logic to preserve the user's currently selected model even if it's not in the fallback list:
privategetFallbackModels():ModelOption[]{constfallbackModels=ANTHROPIC_MODELS.map(id=>({id,displayName: id}));// If we have a cached model that's not in the fallback list, include it
if(this.modelCache){constcachedIds=newSet(this.modelCache.models.map(m=>m.id));constfallbackIds=newSet(ANTHROPIC_MODELS);this.modelCache.models.forEach(model=>{if(!fallbackIds.has(model.id)){fallbackModels.push({id: model.id,displayName: model.display_name||model.id});}});}returnfallbackModels;}
main.ts (2)
59-71: LGTM!
The saveSettings() implementation correctly persists both settings and model cache together. The optional chaining on line 63 safely handles the case where modelService might not be initialized yet.
5-5: LGTM!
The new imports and field addition correctly support the dynamic model management functionality.
Also applies to: 8-8, 15-15
**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>README.md (1)</summary><blockquote>
>
> `4-4`: **Fix license badge: shows MIT but should show GPL-3.0.**
>
> The license badge still references MIT with incorrect links, but the project is now licensed under GPL-3.0-only. This misrepresents the actual license to users.
>
>
> Use the GPL v3 badge format:
>
> ```diff
> -[](https://opensource.org/licenses/MIT)
> +[](https://www.gnu.org/licenses/gpl-3.0)
> ```
>
>
> Also applies to: 4-4
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>🧹 Nitpick comments (5)</summary><blockquote>
<details>
<summary>commands/timedPrompts.ts (1)</summary><blockquote>
`12-12`: **Consider notifying the user when execution is already in progress.**
The race condition guard correctly prevents concurrent invocations, but the early return provides no feedback to the user about why nothing happened.
Apply this diff to notify the user:
```diff
// Check if already in progress to prevent race conditions
if (this.inProgress) {
+ new Notice('Timed prompts are already being generated. Please wait.');
return;
}
```
Also applies to: 19-22
</blockquote></details>
<details>
<summary>settings.ts (2)</summary><blockquote>
`30-37`: **Consider showing a loading indicator during model loading.**
The async model loading before rendering settings is correct, but there's no visual feedback to the user during this potentially slow operation.
You could add a temporary notice or loading state:
```typescript
async display(): Promise<void> {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Freewriting Prompts' });
// Show loading state
const loadingEl = containerEl.createEl('p', { text: 'Loading models...' });
await this.loadModels();
// Remove loading state
loadingEl.remove();
// Continue with settings...
}
```
---
`227-257`: **Handle the case where the selected model is no longer available.**
The logic preserves the selected model if it still exists after refresh (lines 244-248), but doesn't handle the case where it no longer exists. This could leave the settings in an invalid state with a model ID that's no longer available.
Apply this diff to handle the missing model case:
```diff
// Restore selected model if it still exists
const currentModel = this.plugin.settings.model;
const modelExists = this.availableModels.some(m => m.id === currentModel);
if (modelExists) {
this.modelDropdown.setValue(currentModel);
+ } else if (this.availableModels.length > 0) {
+ // Fall back to first available model if current one is gone
+ this.plugin.settings.model = this.availableModels[0].id;
+ this.modelDropdown.setValue(this.availableModels[0].id);
+ new Notice('Your selected model is no longer available. Defaulting to ' + this.availableModels[0].displayName);
}
}
```
</blockquote></details>
<details>
<summary>services/modelService.ts (1)</summary><blockquote>
`29-45`: **Consider more specific error messaging.**
The fallback mechanism is solid, but the Notice message on line 42 could be more informative about why it failed and what the fallback list represents (e.g., "Could not fetch latest models from API. Using default model list.").
Apply this diff for clearer messaging:
```diff
- new Notice('Fetching current models failed. Using hardcoded fallback list.');
+ new Notice('Could not fetch latest models from API. Using default model list.');
```
</blockquote></details>
<details>
<summary>main.ts (1)</summary><blockquote>
`19-32`: **Consider optimizing data loading.**
The `loadData()` is called twice: once in `loadSettings()` (line 20) and again explicitly for the model cache (line 29). While this works correctly, it's slightly inefficient.
You could optimize by reusing the data:
```typescript
async onload() {
const data = await this.loadData() as FreewritingPromptsData | null;
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
// Initialize services
this.promptGenerator = new PromptGeneratorService(this.settings);
this.modelService = new ModelService(this.promptGenerator.anthropicClient);
this.timedCommand = new TimedPromptsCommand(this.promptGenerator);
this.noteCommand = new NotePromptsCommand(this.promptGenerator);
// Load model cache
if (data?.modelCache) {
this.modelService.loadCache(data.modelCache);
}
// Register commands
this.registerCommands();
// Add settings tab
this.addSettingTab(new FreewritingPromptsSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
```
</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 520ac6e826061dd4c011f2c77ba0e4f004df2b53 and 20530142e4f78b61d5e1c18dbfb9755c64cb81b6.
</details>
<details>
<summary>📒 Files selected for processing (12)</summary>
* `.github/workflows/release.yml` (2 hunks)
* `CHANGELOG.md` (4 hunks)
* `README.md` (2 hunks)
* `api/anthropicClient.ts` (5 hunks)
* `commands/notePrompts.ts` (1 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `main.ts` (3 hunks)
* `package.json` (1 hunks)
* `services/modelService.ts` (1 hunks)
* `services/promptGenerator.ts` (4 hunks)
* `settings.ts` (5 hunks)
* `types.ts` (3 hunks)
</details>
<details>
<summary>🔇 Additional comments (25)</summary><blockquote>
<details>
<summary>package.json (1)</summary><blockquote>
`12-13`: **Metadata updates align with repository ownership and licensing changes.**
Author and license fields are now correctly updated to reflect the actual project maintainer (Alexander Kucera) and GPL-3.0 licensing. These changes are consistent with updates in README, CHANGELOG, and the release workflow.
</blockquote></details>
<details>
<summary>README.md (1)</summary><blockquote>
`229-230`: **Repository references and license documentation are correctly updated.**
The GitHub links (Issues, Discussions), clone URL, and license statement all consistently reflect the new repository ownership (AlexKucera/freewriting-prompts) and GPL-3.0 licensing.
Also applies to: 238-239, 287-287
</blockquote></details>
<details>
<summary>CHANGELOG.md (1)</summary><blockquote>
`90-93`: **Version links correctly reference the updated repository.**
All compare and release links in the footer have been updated to point to `AlexKucera/freewriting-prompts`, maintaining referential integrity with the repository ownership changes.
</blockquote></details>
<details>
<summary>.github/workflows/release.yml (1)</summary><blockquote>
`111-111`: **Workflow action and BRAT reference correctly updated.**
The GitHub Actions release action has been bumped to v2, and the BRAT plugin repository reference now correctly points to `AlexKucera/freewriting-prompts`, aligning with the repository ownership changes.
Also applies to: 130-130
</blockquote></details>
<details>
<summary>commands/notePrompts.ts (2)</summary><blockquote>
`78-78`: **LGTM! Cursor positioning logic is correct.**
The cursor is positioned at the end of the inserted content, which provides good UX by leaving the cursor ready for the user to continue typing.
---
`37-40`: ****
The service layer properly handles user notifications. When `promptGenerator.generateNotePrompts()` encounters errors, the catch block (lines 87-94) shows a Notice with the error message to the user, and includes a fallback notice for unknown errors. Users will not experience silent failures.
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (3)</summary><blockquote>
`27-27`: **LGTM!**
The finally block ensures `inProgress` is always reset, even when errors occur. The flag is correctly set after stopping any existing sequence.
Also applies to: 52-54
---
`64-64`: **LGTM!**
Resetting `inProgress` in `stop()` ensures the flag is cleared when the sequence is stopped, maintaining consistency with the concurrency control pattern.
---
`112-121`: **LGTM!**
The dynamic computation ensures `getStatus()` returns accurate values based on the current `promptQueue` state rather than stale field values. The edge case handling for empty queues and the `Math.min` guard are both correct.
</blockquote></details>
<details>
<summary>services/promptGenerator.ts (2)</summary><blockquote>
`6-6`: **LGTM!**
The model parameter type change from `AnthropicModel` to `string` correctly supports dynamic model selection and aligns with the broader PR objectives.
Also applies to: 55-61, 98-113
---
`121-125`: **LGTM!**
The empty cache guard prevents returning invalid cached results and cleans up the cache entry. This is good defensive programming that ensures cache integrity.
</blockquote></details>
<details>
<summary>settings.ts (3)</summary><blockquote>
`53-58`: **LGTM!**
Automatically refreshing models when an API key is entered provides good UX and ensures the model list is up-to-date with the new credentials.
---
`198-225`: **LGTM!**
The model loading and dropdown population logic is well-structured. It correctly handles the empty models case by disabling the dropdown and showing appropriate feedback.
---
`4-4`: **LGTM!**
The new imports and fields support the dynamic model loading functionality correctly.
Also applies to: 7-7, 22-23
</blockquote></details>
<details>
<summary>types.ts (2)</summary><blockquote>
`4-17`: **LGTM!**
The model type change to `string` correctly enables dynamic model selection, and the `FreewritingPromptsData` interface provides a clean pattern for persisting additional data alongside settings. The optional `modelCache` field ensures backward compatibility with existing saved data.
---
`53-70`: **LGTM!**
The new model-related interfaces are well-structured and align with the Anthropic API response format. The `ModelCache` interface correctly includes a timestamp field for TTL validation.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (3)</summary><blockquote>
`9-10`: **LGTM!**
The separation of messages and models endpoints is appropriate for the new functionality, and the model parameter type change to `string` aligns with the dynamic model selection feature across the codebase.
Also applies to: 21-27, 103-103, 163-163
---
`60-86`: **LGTM!**
The `fetchModels()` implementation follows the same pattern as existing methods with consistent error handling, API key validation, and proper typing. The use of the `/v1/models` endpoint is correct for fetching available models.
---
`4-5`: **LGTM!**
The import changes correctly support the new `fetchModels()` functionality and align with the model type changes.
</blockquote></details>
<details>
<summary>services/modelService.ts (4)</summary><blockquote>
`1-20`: **LGTM!**
The `ModelService` class structure is clean and well-organized. The 24-hour cache TTL is reasonable for model list data, and the `ModelOption` interface provides a good abstraction for the dropdown UI.
---
`47-61`: **LGTM!**
The `refreshModels()` method correctly bypasses the cache for forced refreshes, which is appropriate when the API key changes. The error handling is consistent with `getAvailableModels()`.
---
`63-107`: **LGTM!**
The cache management methods provide a clean public API for persistence, and the cache validity logic correctly checks the TTL using timestamp comparison.
---
`109-128`: **Verify fallback model list coverage.**
The fallback mechanism correctly uses the hardcoded `ANTHROPIC_MODELS` list, but if a user has previously selected a newer model (not in the hardcoded list) and the API fails, their selected model won't appear in the dropdown. This could cause confusion.
Consider checking the hardcoded list to ensure it includes commonly used models. You might also want to add logic to preserve the user's currently selected model even if it's not in the fallback list:
```typescript
private getFallbackModels(): ModelOption[] {
const fallbackModels = ANTHROPIC_MODELS.map(id => ({
id,
displayName: id
}));
// If we have a cached model that's not in the fallback list, include it
if (this.modelCache) {
const cachedIds = new Set(this.modelCache.models.map(m => m.id));
const fallbackIds = new Set(ANTHROPIC_MODELS);
this.modelCache.models.forEach(model => {
if (!fallbackIds.has(model.id)) {
fallbackModels.push({
id: model.id,
displayName: model.display_name || model.id
});
}
});
}
return fallbackModels;
}
```
</blockquote></details>
<details>
<summary>main.ts (2)</summary><blockquote>
`59-71`: **LGTM!**
The `saveSettings()` implementation correctly persists both settings and model cache together. The optional chaining on line 63 safely handles the case where `modelService` might not be initialized yet.
---
`5-5`: **LGTM!**
The new imports and field addition correctly support the dynamic model management functionality.
Also applies to: 8-8, 15-15
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
Optional follow-up: introduce export type ModelId = string; in types.ts and use model: ModelId here to document intent.
Also applies to: 98-104
settings.ts (2)
36-38: Avoid noisy notices when API key is empty.
Currently, opening Settings with no API key can trigger a fetch that fails and shows a Notice. Prefer short‑circuiting in ModelService so getAvailableModels/refreshModels return the fallback list without showing a Notice when validateApiKey() is false.
No change needed here if you apply the ModelService tweak (see my ModelService comment). This keeps Settings quiet until a key exists.
Also applies to: 54-57
243-253: Handle missing selection after refresh by choosing a safe default.
If the previously selected model was removed, set the first available model and persist so subsequent calls don’t use an invalid id.
29-45: Avoid Notice spam when API key is empty; short‑circuit to fallback.
If the key is missing, return the fallback list without attempting the API and without showing a Notice. Keep using cache if valid.
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
+ // If no API key, quietly return fallback
+ if (!this.anthropicClient.validateApiKey()) {
+ return this.getFallbackModels();
+ }
+
+ // Try to fetch from API
try {
const response = await this.anthropicClient.fetchModels();
this.updateCache(response.data);
return this.formatModels(response.data);
} catch (error) {
console.error('Failed to fetch models from API:', error);
- new Notice('Fetching current models failed. Using hardcoded fallback list.');
+ new Notice('Fetching current models failed. Using hardcoded fallback list.');
return this.getFallbackModels();
}
}
51-61: Apply the same short‑circuit for refresh.
Refreshing without a key will always fail; return fallback immediately to keep UX smooth.
async refreshModels(): Promise<ModelOption[]> {
- try {
+ try {
+ if (!this.anthropicClient.validateApiKey()) {
+ return this.getFallbackModels();
+ }
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();
}
}
113-118: Sort models by display name for a better dropdown UX.
Also sort fallback options so the list is predictable.
Reviewing files that changed from the base of the PR and between 520ac6e826 and 20530142e4.
📒 Files selected for processing (12)
.github/workflows/release.yml (2 hunks)
CHANGELOG.md (4 hunks)
README.md (2 hunks)
api/anthropicClient.ts (5 hunks)
commands/notePrompts.ts (1 hunks)
commands/timedPrompts.ts (4 hunks)
main.ts (3 hunks)
package.json (1 hunks)
services/modelService.ts (1 hunks)
services/promptGenerator.ts (4 hunks)
settings.ts (5 hunks)
types.ts (3 hunks)
🔇 Additional comments (15)
package.json (1)
12-13: License change from MIT to GPL-3.0-only noted.
The license has been changed from the permissive MIT license to the copyleft GPL-3.0-only license. This change is consistent with updates in README.md and CHANGELOG.md. Be aware that GPL-3.0 requires derivative works to also be licensed under GPL-3.0, which may impact how others can use and distribute this plugin.
commands/notePrompts.ts (1)
78-78: LGTM - Cursor positioning simplified.
The unconditional cursor positioning is cleaner and works correctly since the contentToInsert logic already handles newline management based on document context.
README.md (1)
229-230: LGTM - Repository and license references updated consistently.
All repository links, development paths, and license references have been updated to reflect the new repository name and GPL-3.0 license, maintaining consistency across the documentation.
Also applies to: 238-239, 287-287
.github/workflows/release.yml (2)
130-130: Repository reference updated correctly.
The BRAT installation reference has been updated to match the new repository path.
111-111: No compatibility issues found with action-gh-release@v2.
The action-gh-release@v2 supports the same inputs as shown in the README, and the workflow configuration uses only standard inputs: tag_name, name, body, and GITHUB_TOKEN. There is no formal v1→v2 migration required and no documented breaking changes. The upgrade is compatible and safe.
commands/timedPrompts.ts (2)
12-12: Excellent concurrency protection added.
The inProgress flag prevents race conditions by ensuring only one timed prompt sequence can execute at a time. The guard check at the start of execute(), combined with proper cleanup in the finally block and stop() method, provides robust protection against overlapping executions.
Also applies to: 19-23, 27-27, 52-54, 64-64
113-120: Improved status calculation.
Computing currentPrompt and totalPrompts directly from the promptQueue state ensures accurate status reporting that reflects the actual queue state, even when prompts are updated or cleared. This is more reliable than maintaining separate field values.
All version comparison links have been updated to reference the new repository path, maintaining consistency with the broader repository rebranding.
main.ts (1)
5-5: Well-structured ModelService integration.
The ModelService has been cleanly integrated into the plugin lifecycle with proper initialization and cache persistence. The model cache is loaded on startup and saved with settings, enabling efficient model management across sessions. The initialization order (promptGenerator → modelService) is correct since ModelService depends on the AnthropicClient from promptGenerator.
Also applies to: 8-8, 15-15, 24-24, 28-32, 59-66
types.ts (2)
6-6: Appropriate type change to support dynamic models.
Changing from AnthropicModel (a const union type) to string enables dynamic model selection from API responses. The inline comment clearly documents the rationale for this change.
15-17: Well-designed types for model management.
The new type definitions support the dynamic model management system effectively:
FreewritingPromptsData extends settings to include optional cache persistence
ModelInfo and ModelsListResponse match the Anthropic API structure
ModelCache includes a timestamp for cache invalidation logic
These additions provide a solid foundation for the 24-hour caching mechanism mentioned in the PR objectives.
Also applies to: 53-71
services/promptGenerator.ts (1)
121-126: Empty-cache guard is a good defensive addition.
Treating empty arrays as misses and cleaning them up avoids stale/invalid entries. LGTM.
If you want, I can add a small unit test to assert this behavior on cache hits/expiry.
services/modelService.ts (1)
66-75: Consider persisting cache only on successful API fetch.
Current design already does this. LGTM.
api/anthropicClient.ts (2)
60-86: No changes required — endpoint and headers are correct and current.
The current endpoint is GET https://api.anthropic.com/v1/models with required headers x-api-key and anthropic-version: 2023-06-01. The code correctly implements both the endpoint (this.modelsUrl) and headers. The anthropic-version: 2023-06-01 is still valid per current Anthropic documentation.
66-73: Incorrect review comment — Obsidian's requestUrl does not support timeout.
Obsidian's requestUrl does not include a timeout option. The RequestUrlParam type exposes url, method, contentType, body, headers, throw, etc., but no timeout or signal property. The suggested code changes adding timeout: 15000 and timeout: 30000 would not be valid and cannot be implemented as written.
Likely an incorrect or invalid review comment.
**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/promptGenerator.ts (1)</summary><blockquote>
>
> `140-163`: **Validate that a model is selected.**
>
> Add a check so users can’t proceed with an empty model value.
>
>
> ```diff
> validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } {
> const errors: string[] = [];
>
> if (!settings.apiKey || settings.apiKey.trim().length === 0) {
> errors.push('API key is required');
> }
> + if (!settings.model || settings.model.trim().length === 0) {
> + errors.push('Claude model is required');
> + }
> ```
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>🧹 Nitpick comments (7)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary><blockquote>
`55-61`: **Tighten types for stronger compile-time guarantees.**
- Narrow the cache-key parameter to 'timed' | 'note' (it’s currently string).
- Optionally alias model to a domain type (e.g., ModelId) to avoid accidental non-Claude strings.
Apply:
```diff
private async generatePrompts(
count: number,
- model: string,
+ model: string,
systemPrompt: string,
examplePrompt: string,
type: 'timed' | 'note'
): Promise<string[]> { ... }
private createCacheKey(
count: number,
- model: string,
+ model: string,
systemPrompt: string,
examplePrompt: string,
- type: string
+ type: 'timed' | 'note'
): string { ... }
```
Optional follow-up: introduce `export type ModelId = string;` in types.ts and use `model: ModelId` here to document intent. <!-- no code change here since types.ts isn’t in this diff -->
Also applies to: 98-104
</blockquote></details>
<details>
<summary>settings.ts (2)</summary><blockquote>
`36-38`: **Avoid noisy notices when API key is empty.**
Currently, opening Settings with no API key can trigger a fetch that fails and shows a Notice. Prefer short‑circuiting in ModelService so getAvailableModels/refreshModels return the fallback list without showing a Notice when `validateApiKey()` is false.
No change needed here if you apply the ModelService tweak (see my ModelService comment). This keeps Settings quiet until a key exists.
Also applies to: 54-57
---
`243-253`: **Handle missing selection after refresh by choosing a safe default.**
If the previously selected model was removed, set the first available model and persist so subsequent calls don’t use an invalid id.
```diff
- const currentModel = this.plugin.settings.model;
- const modelExists = this.availableModels.some(m => m.id === currentModel);
- if (modelExists) {
- this.modelDropdown.setValue(currentModel);
- }
+ const currentModel = this.plugin.settings.model;
+ const modelExists = this.availableModels.some(m => m.id === currentModel);
+ if (modelExists) {
+ this.modelDropdown.setValue(currentModel);
+ } else {
+ const fallbackId = this.availableModels[0]?.id;
+ if (fallbackId) {
+ this.modelDropdown.setValue(fallbackId);
+ this.plugin.settings.model = fallbackId;
+ }
+ }
- // Save updated cache
- await this.plugin.saveSettings();
+ // Persist any selection changes
+ await this.plugin.saveSettings();
```
If you want, I can add an integration test that simulates a models list change and asserts the setting updates.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
`35-47`: **Use smaller max_tokens for timed prompts to reduce latency/cost.**
Timed prompts are short; using 1000 tokens is overkill.
```diff
- const request: AnthropicRequest = {
- model,
- max_tokens: 1000,
- messages: [{ role: 'user', content: userMessage }],
- system: finalSystemPrompt
- };
+ const maxTokens = type === 'timed' ? 256 : 1000;
+ const request: AnthropicRequest = {
+ model,
+ max_tokens: maxTokens,
+ messages: [{ role: 'user', content: userMessage }],
+ system: finalSystemPrompt
+ };
```
</blockquote></details>
<details>
<summary>services/modelService.ts (3)</summary><blockquote>
`29-45`: **Avoid Notice spam when API key is empty; short‑circuit to fallback.**
If the key is missing, return the fallback list without attempting the API and without showing a Notice. Keep using cache if valid.
```diff
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
+ // If no API key, quietly return fallback
+ if (!this.anthropicClient.validateApiKey()) {
+ return this.getFallbackModels();
+ }
+
+ // Try to fetch from API
try {
const response = await this.anthropicClient.fetchModels();
this.updateCache(response.data);
return this.formatModels(response.data);
} catch (error) {
console.error('Failed to fetch models from API:', error);
- new Notice('Fetching current models failed. Using hardcoded fallback list.');
+ new Notice('Fetching current models failed. Using hardcoded fallback list.');
return this.getFallbackModels();
}
}
```
---
`51-61`: **Apply the same short‑circuit for refresh.**
Refreshing without a key will always fail; return fallback immediately to keep UX smooth.
```diff
async refreshModels(): Promise<ModelOption[]> {
- try {
+ try {
+ if (!this.anthropicClient.validateApiKey()) {
+ return this.getFallbackModels();
+ }
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();
}
}
```
---
`113-118`: **Sort models by display name for a better dropdown UX.**
Also sort fallback options so the list is predictable.
```diff
private formatModels(models: ModelInfo[]): ModelOption[] {
- return models.map(model => ({
+ return models.map(model => ({
id: model.id,
displayName: model.display_name || model.id
- }));
+ })).sort((a, b) => a.displayName.localeCompare(b.displayName));
}
private getFallbackModels(): ModelOption[] {
- return ANTHROPIC_MODELS.map(id => ({
+ return ANTHROPIC_MODELS.map(id => ({
id,
displayName: id
- }));
+ })).sort((a, b) => a.displayName.localeCompare(b.displayName));
}
```
Also applies to: 123-128
</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 520ac6e826061dd4c011f2c77ba0e4f004df2b53 and 20530142e4f78b61d5e1c18dbfb9755c64cb81b6.
</details>
<details>
<summary>📒 Files selected for processing (12)</summary>
* `.github/workflows/release.yml` (2 hunks)
* `CHANGELOG.md` (4 hunks)
* `README.md` (2 hunks)
* `api/anthropicClient.ts` (5 hunks)
* `commands/notePrompts.ts` (1 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `main.ts` (3 hunks)
* `package.json` (1 hunks)
* `services/modelService.ts` (1 hunks)
* `services/promptGenerator.ts` (4 hunks)
* `settings.ts` (5 hunks)
* `types.ts` (3 hunks)
</details>
<details>
<summary>🔇 Additional comments (15)</summary><blockquote>
<details>
<summary>package.json (1)</summary><blockquote>
`12-13`: **License change from MIT to GPL-3.0-only noted.**
The license has been changed from the permissive MIT license to the copyleft GPL-3.0-only license. This change is consistent with updates in README.md and CHANGELOG.md. Be aware that GPL-3.0 requires derivative works to also be licensed under GPL-3.0, which may impact how others can use and distribute this plugin.
</blockquote></details>
<details>
<summary>commands/notePrompts.ts (1)</summary><blockquote>
`78-78`: **LGTM - Cursor positioning simplified.**
The unconditional cursor positioning is cleaner and works correctly since the `contentToInsert` logic already handles newline management based on document context.
</blockquote></details>
<details>
<summary>README.md (1)</summary><blockquote>
`229-230`: **LGTM - Repository and license references updated consistently.**
All repository links, development paths, and license references have been updated to reflect the new repository name and GPL-3.0 license, maintaining consistency across the documentation.
Also applies to: 238-239, 287-287
</blockquote></details>
<details>
<summary>.github/workflows/release.yml (2)</summary><blockquote>
`130-130`: **Repository reference updated correctly.**
The BRAT installation reference has been updated to match the new repository path.
---
`111-111`: **No compatibility issues found with action-gh-release@v2.**
The action-gh-release@v2 supports the same inputs as shown in the README, and the workflow configuration uses only standard inputs: `tag_name`, `name`, `body`, and `GITHUB_TOKEN`. There is no formal v1→v2 migration required and no documented breaking changes. The upgrade is compatible and safe.
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (2)</summary><blockquote>
`12-12`: **Excellent concurrency protection added.**
The `inProgress` flag prevents race conditions by ensuring only one timed prompt sequence can execute at a time. The guard check at the start of `execute()`, combined with proper cleanup in the `finally` block and `stop()` method, provides robust protection against overlapping executions.
Also applies to: 19-23, 27-27, 52-54, 64-64
---
`113-120`: **Improved status calculation.**
Computing `currentPrompt` and `totalPrompts` directly from the `promptQueue` state ensures accurate status reporting that reflects the actual queue state, even when prompts are updated or cleared. This is more reliable than maintaining separate field values.
</blockquote></details>
<details>
<summary>CHANGELOG.md (1)</summary><blockquote>
`90-93`: **LGTM - Changelog links updated consistently.**
All version comparison links have been updated to reference the new repository path, maintaining consistency with the broader repository rebranding.
</blockquote></details>
<details>
<summary>main.ts (1)</summary><blockquote>
`5-5`: **Well-structured ModelService integration.**
The ModelService has been cleanly integrated into the plugin lifecycle with proper initialization and cache persistence. The model cache is loaded on startup and saved with settings, enabling efficient model management across sessions. The initialization order (promptGenerator → modelService) is correct since ModelService depends on the AnthropicClient from promptGenerator.
Also applies to: 8-8, 15-15, 24-24, 28-32, 59-66
</blockquote></details>
<details>
<summary>types.ts (2)</summary><blockquote>
`6-6`: **Appropriate type change to support dynamic models.**
Changing from `AnthropicModel` (a const union type) to `string` enables dynamic model selection from API responses. The inline comment clearly documents the rationale for this change.
---
`15-17`: **Well-designed types for model management.**
The new type definitions support the dynamic model management system effectively:
- `FreewritingPromptsData` extends settings to include optional cache persistence
- `ModelInfo` and `ModelsListResponse` match the Anthropic API structure
- `ModelCache` includes a timestamp for cache invalidation logic
These additions provide a solid foundation for the 24-hour caching mechanism mentioned in the PR objectives.
Also applies to: 53-71
</blockquote></details>
<details>
<summary>services/promptGenerator.ts (1)</summary><blockquote>
`121-126`: **Empty-cache guard is a good defensive addition.**
Treating empty arrays as misses and cleaning them up avoids stale/invalid entries. LGTM.
If you want, I can add a small unit test to assert this behavior on cache hits/expiry. <!-- offer kept minimal -->
</blockquote></details>
<details>
<summary>services/modelService.ts (1)</summary><blockquote>
`66-75`: **Consider persisting cache only on successful API fetch.**
Current design already does this. LGTM.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (2)</summary><blockquote>
`60-86`: **No changes required — endpoint and headers are correct and current.**
The current endpoint is GET https://api.anthropic.com/v1/models with required headers x-api-key and anthropic-version: 2023-06-01. The code correctly implements both the endpoint (`this.modelsUrl`) and headers. The anthropic-version: 2023-06-01 is still valid per current Anthropic documentation.
---
`66-73`: **Incorrect review comment — Obsidian's requestUrl does not support timeout.**
Obsidian's requestUrl does not include a timeout option. The RequestUrlParam type exposes url, method, contentType, body, headers, throw, etc., but no timeout or signal property. The suggested code changes adding `timeout: 15000` and `timeout: 30000` would not be valid and cannot be implemented as written.
> Likely an incorrect or invalid review comment.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 0
🧹 Nitpick comments (3)
commands/timedPrompts.ts (1)
19-28: Race condition guard is effective but has a tiny window.
The inProgress flag successfully prevents concurrent executions. However, there's a small race window between the check (line 20) and the flag set (line 28). Consider setting inProgress = true before calling stop() to further minimize this window, though the practical impact is minimal given JavaScript's single-threaded async nature.
Optional refinement:
async execute(settings: FreewritingPromptsSettings): Promise<void> {
// Check if already in progress to prevent race conditions
if (this.inProgress) {
new Notice('Timed prompts are already being generated. Please wait.');
return;
}
+ this.inProgress = true;
+
// Stop any existing timed sequence
this.stop();
- this.inProgress = true;
try {
settings.ts (1)
30-37: Consider non-blocking model loading for better UX.
While loadModels() is called with await, this blocks the entire settings UI from rendering until models are fetched. For a better user experience, consider showing the UI immediately with a "Loading models..." state in the dropdown, then updating it asynchronously when models arrive.
Alternatively, the current approach is acceptable if you prefer to show a complete UI only after models are loaded, though users might experience a brief delay when opening settings.
api/anthropicClient.ts (1)
63-89: Consider adding response validation in fetchModels().
The fetchModels() method correctly implements the API call, but Line 82 performs a type assertion without validating the response structure. If the Anthropic API changes its response format, this could cause runtime errors downstream.
Consider adding basic validation:
return response.json as ModelsListResponse;
+
+ // Validate basic response structure
+ const data = response.json as any;
+ if (!data || !Array.isArray(data.data)) {
+ throw new Error('Invalid models API response structure');
+ }
+ return data as ModelsListResponse;
Alternatively, if you prefer to keep it simple, the current approach is acceptable as the ModelService has fallback logic to handle errors.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 20530142e4 and 6ccfb9e023.
📒 Files selected for processing (8)
README.md (3 hunks)
api/anthropicClient.ts (6 hunks)
commands/timedPrompts.ts (4 hunks)
main.ts (2 hunks)
services/modelService.ts (1 hunks)
services/promptGenerator.ts (5 hunks)
settings.ts (5 hunks)
types.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
The GitHub URLs have been properly updated to reflect the new repository location. The changes are consistent across issues, discussions, and git clone URLs.
Also applies to: 238-239
4-4: License change verified as consistent across project files.
The verification confirms that the GPL v3 license has been properly implemented: the LICENSE file contains GPL v3 text, package.json specifies GPL-3.0-only, and the README badge correctly reflects the new license. All critical project files are in sync. No further changes needed.
commands/timedPrompts.ts (3)
53-55: Excellent use of finally block for cleanup.
The finally block ensures inProgress is always reset regardless of success or failure, preventing the command from becoming permanently locked.
58-66: Good defensive programming in stop() method.
Resetting inProgress in the stop() method ensures the flag is cleared even when the command is stopped externally, complementing the finally block cleanup.
113-122: Improved status calculation with dynamic values.
Deriving currentPrompt and totalPrompts from the actual promptQueue state provides more accurate status information and handles edge cases properly (empty queue, boundary conditions).
settings.ts (5)
4-4: Imports and field additions look good.
The new imports and private fields properly support the dynamic model loading functionality.
Also applies to: 7-7, 22-23
49-58: Good non-blocking model refresh on API key change.
The model refresh is triggered when a valid API key is entered, and it runs asynchronously without blocking user interaction. Error handling is properly delegated to refreshModels().
73-85: Model dropdown handling properly structured.
Storing the dropdown reference enables dynamic updates during model refresh, and the type change to string correctly supports dynamic model IDs.
198-206: Clean error handling in loadModels().
The method properly delegates user-facing error messages to ModelService, avoiding duplication. The empty availableModels array on failure is correctly handled by populateModelDropdown().
208-265: Comprehensive model dropdown management with good UX.
The model loading and refresh logic is well-structured:
Properly handles loading states with disabled dropdown
Clears and repopulates options correctly
Intelligently preserves user's selected model when possible
Provides clear feedback when falling back to a different model
Persists changes appropriately
The implementation provides good user experience during model updates.
api/anthropicClient.ts (4)
4-10: Clean separation of API endpoints.
The import changes and URL split properly support both message generation and model fetching capabilities.
21-27: Model type change enables dynamic model support.
Changing from AnthropicModel to string is necessary for dynamic model fetching, though it trades compile-time type safety for runtime flexibility. The Anthropic API will validate model names at request time.
42-50: Smart optimization for timed prompts.
Using a smaller max_tokens (256) for timed prompts reduces both latency and API costs, which is appropriate given these prompts are designed to be short and immediate. This aligns well with the TIMED_PROMPT_MODIFIER requirements.
103-114: Correct endpoint usage in makeRequest().
The change from baseUrl to messagesUrl correctly aligns with the URL refactoring and ensures message requests go to the proper endpoint.
services/modelService.ts (7)
8-11: Clean interface for model options.
The ModelOption interface is well-designed for dropdown usage with clear, semantic field names.
13-20: Well-structured service initialization.
The class fields are properly typed, and the 24-hour cache TTL is appropriate for model lists that change infrequently. Constructor dependency injection is clean.
29-50: Well-structured model fetching with good fallback logic.
The method implements a sensible priority: cache → API → fallback. The UX is thoughtful—no notification for missing API keys (avoiding nags), but clear feedback when API fetches fail. The cache validity check and fallback handling are both appropriate.
56-71: Force refresh correctly implemented.
The refreshModels() method appropriately bypasses the cache and uses a more specific error message for refresh failures.
73-92: Cache management methods are straightforward and correct.
The cache persistence methods (load, get, clear) provide the necessary interface for the plugin's data persistence layer.
96-117: Cache validation and update logic is correct.
The isCacheValid() method properly checks both cache existence and age, while updateCache() correctly timestamps the cache data.
119-138: Model formatting methods are well-implemented.
Both formatModels() and getFallbackModels() properly transform model data into dropdown-friendly options with alphabetical sorting for better UX. The fallback logic correctly uses model IDs as display names for the hardcoded list.
**Actionable comments posted: 0**
<details>
<summary>🧹 Nitpick comments (3)</summary><blockquote>
<details>
<summary>commands/timedPrompts.ts (1)</summary><blockquote>
`19-28`: **Race condition guard is effective but has a tiny window.**
The `inProgress` flag successfully prevents concurrent executions. However, there's a small race window between the check (line 20) and the flag set (line 28). Consider setting `inProgress = true` before calling `stop()` to further minimize this window, though the practical impact is minimal given JavaScript's single-threaded async nature.
Optional refinement:
```diff
async execute(settings: FreewritingPromptsSettings): Promise<void> {
// Check if already in progress to prevent race conditions
if (this.inProgress) {
new Notice('Timed prompts are already being generated. Please wait.');
return;
}
+ this.inProgress = true;
+
// Stop any existing timed sequence
this.stop();
- this.inProgress = true;
try {
```
</blockquote></details>
<details>
<summary>settings.ts (1)</summary><blockquote>
`30-37`: **Consider non-blocking model loading for better UX.**
While `loadModels()` is called with `await`, this blocks the entire settings UI from rendering until models are fetched. For a better user experience, consider showing the UI immediately with a "Loading models..." state in the dropdown, then updating it asynchronously when models arrive.
Alternatively, the current approach is acceptable if you prefer to show a complete UI only after models are loaded, though users might experience a brief delay when opening settings.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
`63-89`: **Consider adding response validation in fetchModels().**
The `fetchModels()` method correctly implements the API call, but Line 82 performs a type assertion without validating the response structure. If the Anthropic API changes its response format, this could cause runtime errors downstream.
Consider adding basic validation:
```diff
return response.json as ModelsListResponse;
+
+ // Validate basic response structure
+ const data = response.json as any;
+ if (!data || !Array.isArray(data.data)) {
+ throw new Error('Invalid models API response structure');
+ }
+ return data as ModelsListResponse;
```
Alternatively, if you prefer to keep it simple, the current approach is acceptable as the ModelService has fallback logic to handle errors.
</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 20530142e4f78b61d5e1c18dbfb9755c64cb81b6 and 6ccfb9e023d36f5c504e82a297225b67f89ad596.
</details>
<details>
<summary>📒 Files selected for processing (8)</summary>
* `README.md` (3 hunks)
* `api/anthropicClient.ts` (6 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `main.ts` (2 hunks)
* `services/modelService.ts` (1 hunks)
* `services/promptGenerator.ts` (5 hunks)
* `settings.ts` (5 hunks)
* `types.ts` (3 hunks)
</details>
<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (3)</summary>
* services/promptGenerator.ts
* types.ts
* main.ts
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>🧬 Code graph analysis (4)</summary>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
<details>
<summary>types.ts (2)</summary>
* `AnthropicRequest` (27-32)
* `ModelsListResponse` (63-68)
</details>
</blockquote></details>
<details>
<summary>settings.ts (2)</summary><blockquote>
<details>
<summary>services/modelService.ts (1)</summary>
* `ModelOption` (8-11)
</details>
<details>
<summary>main.ts (1)</summary>
* `FreewritingPromptsPlugin` (12-165)
</details>
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (2)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (8-168)
</details>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (7-16)
</details>
</blockquote></details>
<details>
<summary>services/modelService.ts (2)</summary><blockquote>
<details>
<summary>api/anthropicClient.ts (1)</summary>
* `AnthropicClient` (7-297)
</details>
<details>
<summary>types.ts (3)</summary>
* `ModelCache` (70-73)
* `ModelInfo` (56-61)
* `ANTHROPIC_MODELS` (75-82)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (21)</summary><blockquote>
<details>
<summary>README.md (2)</summary><blockquote>
`229-230`: **Repository references updated consistently.**
The GitHub URLs have been properly updated to reflect the new repository location. The changes are consistent across issues, discussions, and git clone URLs.
Also applies to: 238-239
---
`4-4`: **License change verified as consistent across project files.**
The verification confirms that the GPL v3 license has been properly implemented: the LICENSE file contains GPL v3 text, package.json specifies `GPL-3.0-only`, and the README badge correctly reflects the new license. All critical project files are in sync. No further changes needed.
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (3)</summary><blockquote>
`53-55`: **Excellent use of finally block for cleanup.**
The finally block ensures `inProgress` is always reset regardless of success or failure, preventing the command from becoming permanently locked.
---
`58-66`: **Good defensive programming in stop() method.**
Resetting `inProgress` in the `stop()` method ensures the flag is cleared even when the command is stopped externally, complementing the finally block cleanup.
---
`113-122`: **Improved status calculation with dynamic values.**
Deriving `currentPrompt` and `totalPrompts` from the actual `promptQueue` state provides more accurate status information and handles edge cases properly (empty queue, boundary conditions).
</blockquote></details>
<details>
<summary>settings.ts (5)</summary><blockquote>
`4-4`: **Imports and field additions look good.**
The new imports and private fields properly support the dynamic model loading functionality.
Also applies to: 7-7, 22-23
---
`49-58`: **Good non-blocking model refresh on API key change.**
The model refresh is triggered when a valid API key is entered, and it runs asynchronously without blocking user interaction. Error handling is properly delegated to `refreshModels()`.
---
`73-85`: **Model dropdown handling properly structured.**
Storing the dropdown reference enables dynamic updates during model refresh, and the type change to `string` correctly supports dynamic model IDs.
---
`198-206`: **Clean error handling in loadModels().**
The method properly delegates user-facing error messages to ModelService, avoiding duplication. The empty `availableModels` array on failure is correctly handled by `populateModelDropdown()`.
---
`208-265`: **Comprehensive model dropdown management with good UX.**
The model loading and refresh logic is well-structured:
- Properly handles loading states with disabled dropdown
- Clears and repopulates options correctly
- Intelligently preserves user's selected model when possible
- Provides clear feedback when falling back to a different model
- Persists changes appropriately
The implementation provides good user experience during model updates.
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (4)</summary><blockquote>
`4-10`: **Clean separation of API endpoints.**
The import changes and URL split properly support both message generation and model fetching capabilities.
---
`21-27`: **Model type change enables dynamic model support.**
Changing from `AnthropicModel` to `string` is necessary for dynamic model fetching, though it trades compile-time type safety for runtime flexibility. The Anthropic API will validate model names at request time.
---
`42-50`: **Smart optimization for timed prompts.**
Using a smaller `max_tokens` (256) for timed prompts reduces both latency and API costs, which is appropriate given these prompts are designed to be short and immediate. This aligns well with the TIMED_PROMPT_MODIFIER requirements.
---
`103-114`: **Correct endpoint usage in makeRequest().**
The change from `baseUrl` to `messagesUrl` correctly aligns with the URL refactoring and ensures message requests go to the proper endpoint.
</blockquote></details>
<details>
<summary>services/modelService.ts (7)</summary><blockquote>
`8-11`: **Clean interface for model options.**
The `ModelOption` interface is well-designed for dropdown usage with clear, semantic field names.
---
`13-20`: **Well-structured service initialization.**
The class fields are properly typed, and the 24-hour cache TTL is appropriate for model lists that change infrequently. Constructor dependency injection is clean.
---
`29-50`: **Well-structured model fetching with good fallback logic.**
The method implements a sensible priority: cache → API → fallback. The UX is thoughtful—no notification for missing API keys (avoiding nags), but clear feedback when API fetches fail. The cache validity check and fallback handling are both appropriate.
---
`56-71`: **Force refresh correctly implemented.**
The `refreshModels()` method appropriately bypasses the cache and uses a more specific error message for refresh failures.
---
`73-92`: **Cache management methods are straightforward and correct.**
The cache persistence methods (load, get, clear) provide the necessary interface for the plugin's data persistence layer.
---
`96-117`: **Cache validation and update logic is correct.**
The `isCacheValid()` method properly checks both cache existence and age, while `updateCache()` correctly timestamps the cache data.
---
`119-138`: **Model formatting methods are well-implemented.**
Both `formatModels()` and `getFallbackModels()` properly transform model data into dropdown-friendly options with alphabetical sorting for better UX. The fallback logic correctly uses model IDs as display names for the hardcoded list.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/anthropicClient.ts (1)
82-86: Consider validating individual model objects.
The current validation only checks that data.data is an array but doesn't validate the structure of individual model entries. If the API returns malformed model objects, this could cause runtime errors in consuming code.
Consider adding basic validation:
// Validate basic response structure
const data = response.json as any;
if (!data || !Array.isArray(data.data)) {
throw new Error('Invalid models API response structure');
}
+
+ // Validate that each model has required fields
+ if (!data.data.every((model: any) => model && typeof model.id === 'string')) {
+ throw new Error('Invalid model structure in API response');
+ }
return data as ModelsListResponse;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 6ccfb9e023 and 03d2b1c93d.
📒 Files selected for processing (3)
api/anthropicClient.ts (6 hunks)
commands/timedPrompts.ts (4 hunks)
settings.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
The new imports and private fields are appropriate for implementing dynamic model selection functionality.
Also applies to: 22-23
30-30: LGTM!
Making display() async is appropriate since the method now performs asynchronous model loading.
70-85: LGTM!
The model dropdown setup and asynchronous loading pattern appropriately prevents UI blocking while fetching available models.
198-234: LGTM!
The model loading logic appropriately handles asynchronous fetching, gracefully falls back when the current model is unavailable, and includes proper validation before accessing the fallback model.
236-253: LGTM!
The dropdown population logic correctly handles the loading state and gracefully manages empty model lists.
255-293: Verify protection against concurrent refresh calls.
If refreshModels() is invoked multiple times concurrently (for example, if triggered by rapid API key changes before the earlier suggestion is addressed), race conditions may occur—leading to redundant API calls, inconsistent dropdown state, or duplicate notices.
Consider adding a guard to prevent overlapping refreshes:
The import changes appropriately support dynamic model fetching and string-based model identifiers.
9-10: LGTM!
Separating the messages and models endpoints improves code clarity and maintainability.
23-23: LGTM!
The string-based model parameter enables dynamic model selection, and the differentiated max_tokens values appropriately optimize for prompt type—reducing latency and cost for timed prompts.
Also applies to: 42-47
112-112: LGTM!
Using the messagesUrl field improves consistency and maintainability.
172-172: LGTM!
The string-based model parameter aligns with the dynamic model selection feature.
**Actionable comments posted: 2**
<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
`82-86`: **Consider validating individual model objects.**
The current validation only checks that `data.data` is an array but doesn't validate the structure of individual model entries. If the API returns malformed model objects, this could cause runtime errors in consuming code.
Consider adding basic validation:
```diff
// Validate basic response structure
const data = response.json as any;
if (!data || !Array.isArray(data.data)) {
throw new Error('Invalid models API response structure');
}
+
+ // Validate that each model has required fields
+ if (!data.data.every((model: any) => model && typeof model.id === 'string')) {
+ throw new Error('Invalid model structure in API response');
+ }
return data as ModelsListResponse;
```
</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 6ccfb9e023d36f5c504e82a297225b67f89ad596 and 03d2b1c93df48dd4cc12a717d9b549495a93cbbf.
</details>
<details>
<summary>📒 Files selected for processing (3)</summary>
* `api/anthropicClient.ts` (6 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `settings.ts` (5 hunks)
</details>
<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>
* commands/timedPrompts.ts
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>🧬 Code graph analysis (2)</summary>
<details>
<summary>settings.ts (2)</summary><blockquote>
<details>
<summary>services/modelService.ts (1)</summary>
* `ModelOption` (8-11)
</details>
<details>
<summary>main.ts (1)</summary>
* `FreewritingPromptsPlugin` (12-165)
</details>
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
<details>
<summary>types.ts (2)</summary>
* `AnthropicRequest` (27-32)
* `ModelsListResponse` (63-68)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (11)</summary><blockquote>
<details>
<summary>settings.ts (6)</summary><blockquote>
`4-7`: **LGTM!**
The new imports and private fields are appropriate for implementing dynamic model selection functionality.
Also applies to: 22-23
---
`30-30`: **LGTM!**
Making `display()` async is appropriate since the method now performs asynchronous model loading.
---
`70-85`: **LGTM!**
The model dropdown setup and asynchronous loading pattern appropriately prevents UI blocking while fetching available models.
---
`198-234`: **LGTM!**
The model loading logic appropriately handles asynchronous fetching, gracefully falls back when the current model is unavailable, and includes proper validation before accessing the fallback model.
---
`236-253`: **LGTM!**
The dropdown population logic correctly handles the loading state and gracefully manages empty model lists.
---
`255-293`: **Verify protection against concurrent refresh calls.**
If `refreshModels()` is invoked multiple times concurrently (for example, if triggered by rapid API key changes before the earlier suggestion is addressed), race conditions may occur—leading to redundant API calls, inconsistent dropdown state, or duplicate notices.
Consider adding a guard to prevent overlapping refreshes:
```typescript
private isRefreshing = false;
private async refreshModels(): Promise<void> {
if (this.isRefreshing) {
return;
}
this.isRefreshing = true;
try {
// ... existing refresh logic ...
} finally {
this.isRefreshing = false;
}
}
```
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (5)</summary><blockquote>
`4-5`: **LGTM!**
The import changes appropriately support dynamic model fetching and string-based model identifiers.
---
`9-10`: **LGTM!**
Separating the messages and models endpoints improves code clarity and maintainability.
---
`23-23`: **LGTM!**
The string-based model parameter enables dynamic model selection, and the differentiated `max_tokens` values appropriately optimize for prompt type—reducing latency and cost for timed prompts.
Also applies to: 42-47
---
`112-112`: **LGTM!**
Using the `messagesUrl` field improves consistency and maintainability.
---
`172-172`: **LGTM!**
The string-based model parameter aligns with the dynamic model selection feature.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
The ModelsListResponse interface includes has_more, first_id, and last_id fields that indicate pagination support, but fetchModels() only retrieves the first page of results. If Anthropic returns more than one page of models, subsequent pages are silently ignored.
Verify whether pagination is needed:
If pagination is required, consider implementing it or documenting the limitation. Otherwise, if all Claude models fit in a single page, add a comment explaining why pagination isn't needed.
🏁 Script executed:
#!/bin/bash
# Check if the ModelsListResponse type definition includes pagination fields
rg -A 5"interface ModelsListResponse" types.ts
Length of output: 128
I'll verify whether pagination is actually used or documented elsewhere in the codebase.
Additionally, let me search for API documentation references or comments about Anthropic's models endpoint:
---
🏁 Script executed:
```shell
#!/bin/bash
# Check if pagination fields are used anywhere in the codebase
echo "=== Searching for usage of pagination fields ==="
rg -n "(has_more|first_id|last_id)" --type ts --type js -C 2
echo ""
echo "=== Searching for fetchModels calls ==="
rg -n "fetchModels" --type ts --type js -C 2
echo ""
echo "=== Searching for pagination-related comments or TODOs ==="
rg -n "(pagination|TODO|FIXME)" --type ts --type js api/
Length of output: 1321
🏁 Script executed:
#!/bin/bash
# Check for documentation or API-related comments in the anthropicClient fileecho"=== Full anthropicClient.ts file structure ==="
rg -n "^(class|interface|export|async|const|function)" api/anthropicClient.ts
echo""echo"=== Check file for any comments about models endpoint ==="
rg -n "(models|API|pagination|page)" api/anthropicClient.ts -i
Length of output: 2163
🌐 Web query:
Anthropic models API endpoint pagination how many models returned
💡 Result:
By default the List Models endpoint returns 20 models per page. You can set the query param limit to any integer 1–1000 to change this. Pagination uses before_id / after_id with has_more, first_id and last_id in the response. [1]
Implement pagination in fetchModels() or document why it's not needed.
Verification confirms the issue: The ModelsListResponse interface includes pagination fields, but the implementation only retrieves the first page. Anthropic's models API endpoint returns 20 models per page by default, and pagination fields are never used anywhere in the codebase. If Anthropic returns more than 20 models, subsequent pages are silently ignored.
Either:
Implement pagination to fetch all available models (loop using has_more, last_id)
Or verify all Claude models fit within 20 and add a comment explaining why pagination isn't needed
🤖 Prompt for AI Agents
In api/anthropicClient.ts around lines 63–95, fetchModels only returns the first
page of models but ModelsListResponse includes pagination fields; implement
pagination: perform the initial GET then loop while response.data.has_more is
true, using the response.data.last_id (or the API's paging token) as a query
parameter to request the next page, concatenate each page's data array into a
single array, and after all pages are fetched return a ModelsListResponse
containing the combined data and final pagination fields (has_more false and
last_id from the last page). Ensure headers and error handling remain the same
and preserve type annotations; alternatively, if you choose not to paginate, add
a clear comment and a runtime assertion verifying the total models never exceed
one page and document why pagination is unnecessary.
_⚠️ Potential issue_ | _🔴 Critical_
<details>
<summary>🧩 Analysis chain</summary>
**Pagination is not handled for model listing.**
The `ModelsListResponse` interface includes `has_more`, `first_id`, and `last_id` fields that indicate pagination support, but `fetchModels()` only retrieves the first page of results. If Anthropic returns more than one page of models, subsequent pages are silently ignored.
Verify whether pagination is needed:
If pagination is required, consider implementing it or documenting the limitation. Otherwise, if all Claude models fit in a single page, add a comment explaining why pagination isn't needed.
---
🏁 Script executed:
```shell
#!/bin/bash
# Check if the ModelsListResponse type definition includes pagination fields
rg -A 5 "interface ModelsListResponse" types.ts
```
Length of output: 128
---
I'll verify whether pagination is actually used or documented elsewhere in the codebase.
```
Additionally, let me search for API documentation references or comments about Anthropic's models endpoint:
```
```
---
🏁 Script executed:
```shell
#!/bin/bash
# Check if pagination fields are used anywhere in the codebase
echo "=== Searching for usage of pagination fields ==="
rg -n "(has_more|first_id|last_id)" --type ts --type js -C 2
echo ""
echo "=== Searching for fetchModels calls ==="
rg -n "fetchModels" --type ts --type js -C 2
echo ""
echo "=== Searching for pagination-related comments or TODOs ==="
rg -n "(pagination|TODO|FIXME)" --type ts --type js api/
```
Length of output: 1321
---
🏁 Script executed:
```shell
#!/bin/bash
# Check for documentation or API-related comments in the anthropicClient file
echo "=== Full anthropicClient.ts file structure ==="
rg -n "^(class|interface|export|async|const|function)" api/anthropicClient.ts
echo ""
echo "=== Check file for any comments about models endpoint ==="
rg -n "(models|API|pagination|page)" api/anthropicClient.ts -i
```
Length of output: 2163
---
🌐 Web query:
```web
Anthropic models API endpoint pagination how many models returned
```
💡 Result:
By default the List Models endpoint returns 20 models per page. You can set the query param limit to any integer 1–1000 to change this. Pagination uses before_id / after_id with has_more, first_id and last_id in the response. [1]
---
</details>
**Implement pagination in `fetchModels()` or document why it's not needed.**
Verification confirms the issue: The `ModelsListResponse` interface includes pagination fields, but the implementation only retrieves the first page. Anthropic's models API endpoint returns 20 models per page by default, and pagination fields are never used anywhere in the codebase. If Anthropic returns more than 20 models, subsequent pages are silently ignored.
Either:
- Implement pagination to fetch all available models (loop using `has_more`, `last_id`)
- Or verify all Claude models fit within 20 and add a comment explaining why pagination isn't needed
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In api/anthropicClient.ts around lines 63–95, fetchModels only returns the first
page of models but ModelsListResponse includes pagination fields; implement
pagination: perform the initial GET then loop while response.data.has_more is
true, using the response.data.last_id (or the API's paging token) as a query
parameter to request the next page, concatenate each page's data array into a
single array, and after all pages are fetched return a ModelsListResponse
containing the combined data and final pagination fields (has_more false and
last_id from the last page). Ensure headers and error handling remain the same
and preserve type annotations; alternatively, if you choose not to paginate, add
a clear comment and a runtime assertion verifying the total models never exceed
one page and document why pagination is unnecessary.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits e96ef65 to ee7faef
Consider debouncing or using blur event for model refresh.
Refreshing models on every keystroke while the user types their API key will trigger multiple unnecessary API calls (likely to fail with incomplete keys), degrading UX and potentially hitting rate limits.
Consider one of these approaches:
Option 1: Trigger on blur event
.addText(text => text
.setPlaceholder('sk-ant-...')
.setValue(this.plugin.settings.apiKey)
.onChange(async (value) => {
this.plugin.settings.apiKey = value;
await this.plugin.saveSettings();
this.plugin.promptGenerator.updateApiKey(value);
-
- // Trigger model refresh when API key is entered
- if (value.trim().length > 0) {
- await this.refreshModels();
- }
}))
.then(setting => {
// Make it a password field
- setting.controlEl.querySelector('input')?.setAttribute('type', 'password');
+ const inputEl = setting.controlEl.querySelector('input');
+ inputEl?.setAttribute('type', 'password');
+ // Refresh models when user finishes entering API key
+ inputEl?.addEventListener('blur', async () => {
+ if (this.plugin.settings.apiKey.trim().length > 0) {
+ await this.refreshModels();
+ }
+ });
});
Option 2: Debounce the refresh (requires a debounce utility function)
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In settings.ts around lines 51-54, the current code calls refreshModels on every
keystroke which causes unnecessary API calls; change this to either trigger
refreshModels on the input's blur event (call once when the field loses focus if
the trimmed value is non-empty) or implement a debounce around refreshModels
(wrap it with a debounce utility, e.g., 300–500ms, call the debounced function
from the input change handler, and clear the timeout on component unmount).
Ensure the check for value.trim().length > 0 remains before calling the refresh
and that any existing timers are cleaned up to avoid leaks.
_⚠️ Potential issue_ | _🟡 Minor_
**Consider debouncing or using blur event for model refresh.**
Refreshing models on every keystroke while the user types their API key will trigger multiple unnecessary API calls (likely to fail with incomplete keys), degrading UX and potentially hitting rate limits.
Consider one of these approaches:
**Option 1: Trigger on blur event**
```diff
.addText(text => text
.setPlaceholder('sk-ant-...')
.setValue(this.plugin.settings.apiKey)
.onChange(async (value) => {
this.plugin.settings.apiKey = value;
await this.plugin.saveSettings();
this.plugin.promptGenerator.updateApiKey(value);
-
- // Trigger model refresh when API key is entered
- if (value.trim().length > 0) {
- await this.refreshModels();
- }
}))
.then(setting => {
// Make it a password field
- setting.controlEl.querySelector('input')?.setAttribute('type', 'password');
+ const inputEl = setting.controlEl.querySelector('input');
+ inputEl?.setAttribute('type', 'password');
+ // Refresh models when user finishes entering API key
+ inputEl?.addEventListener('blur', async () => {
+ if (this.plugin.settings.apiKey.trim().length > 0) {
+ await this.refreshModels();
+ }
+ });
});
```
**Option 2: Debounce the refresh** (requires a debounce utility function)
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In settings.ts around lines 51-54, the current code calls refreshModels on every
keystroke which causes unnecessary API calls; change this to either trigger
refreshModels on the input's blur event (call once when the field loses focus if
the trimmed value is non-empty) or implement a debounce around refreshModels
(wrap it with a debounce utility, e.g., 300–500ms, call the debounced function
from the input change handler, and clear the timeout on component unmount).
Ensure the check for value.trim().length > 0 remains before calling the refresh
and that any existing timers are cleaned up to avoid leaks.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits e96ef65 to ee7faef
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
commands/notePrompts.ts (2)
95-128: Prevent content merge when inserting mid-line; handle selections explicitly.
Current logic inserts a leading newline based on the entire line’s content and a trailing newline only if not at document end. This can merge inserted prompts with trailing text on the same line and ignores non-collapsed selections.
Add newline after if there is text after the cursor (or selection end).
Collapse selection before inserting to make cursor math deterministic.
Apply:
- private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
- const cursor = editor.getCursor();
- const currentLine = editor.getLine(cursor.line);
- // Determine if we need to add a newline before our content
- const needsNewlineBefore = currentLine.trim().length > 0;
+ private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
+ // Normalize to an insertion point (collapse any selection)
+ const from = editor.getCursor('from');
+ const to = editor.getCursor('to');
+ const hasSelection = from.line !== to.line || from.ch !== to.ch;
+ if (hasSelection) {
+ editor.setSelection(from, from);
+ }
+ const cursor = editor.getCursor(); // refreshed after collapse
+ const currentLine = editor.getLine(cursor.line) ?? '';
+
+ const hasTextBefore = cursor.ch > 0 && currentLine.slice(0, cursor.ch).trim().length > 0;
+ const hasTextAfter = cursor.ch < currentLine.length && currentLine.slice(cursor.ch).trim().length > 0;
// Format the prompts
const formattedPrompts = this.formatPrompts(prompts);
// Prepare the content to insert
- let contentToInsert = '';
-
- if (needsNewlineBefore) {
- contentToInsert += '\n';
- }
-
- contentToInsert += formattedPrompts;
-
- // If we're not at the end of the document, add a trailing newline
- const lastLine = editor.lastLine();
- if (cursor.line < lastLine) {
- contentToInsert += '\n';
- }
-
- // Insert the content at the cursor position
- editor.replaceSelection(contentToInsert);
+ const lastLine = editor.lastLine();
+ let contentToInsert = '';
+ if (hasTextBefore) contentToInsert += '\n';
+ contentToInsert += formattedPrompts;
+ if (hasTextAfter || cursor.line < lastLine) contentToInsert += '\n';
+
+ // Insert the content at the cursor position
+ editor.replaceSelection(contentToInsert);
// Position cursor at the end of the inserted content
const lines = contentToInsert.split('\n');
const newCursorLine = cursor.line + lines.length - 1;
const newCursorCh = lines[lines.length - 1].length;
editor.setCursor(newCursorLine, newCursorCh);
}
149-156: Timestamp won’t include time with toLocaleDateString; use Intl.DateTimeFormat or toLocaleString.
toLocaleDateString typically ignores time fields. Switch to Intl.DateTimeFormat (or toLocaleString) to reliably include time.
158-165: Update ANTHROPIC_MODELS list—missing latest Claude models.
The fallback list is incomplete and stale. Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) is now available and recommended, along with other variants not currently included:
Add claude-sonnet-4-5-20250929 (latest Sonnet model, released Sept 29, 2025)
Add claude-3-5-sonnet-latest (Sonnet 3.5 alias)
Add claude-3-opus-latest (Opus 3 alias)
Standardize to "-latest" aliases where available for stability, or use consistent canonical IDs.
Periodically sync with Anthropic's current model offerings to prevent breakage when fallbacks are needed.
commands/timedPrompts.ts (1)
171-174: Prevent notice/interval overlap for small delays.
With delaySeconds = 1, Math.max(1000, delay-500) yields 1000ms, equal to interval and can overlap the next notice. Clamp duration below the interval.
- const notificationDuration = Math.max(1000, (delaySeconds * 1000) - 500);
+ const delayMs = delaySeconds * 1000;
+ // If very short delays, cap at 500ms; otherwise end 500ms before next tick
+ const notificationDuration = delayMs > 1000 ? (delayMs - 500) : 500;
Looping with after=last_id until has_more=false fixes the one-page-only issue flagged earlier.
settings.ts (1)
60-63: Nice: Debounced model refresh with proper cleanup.
Debounce on API key changes and clearing the timer in hide() addresses the prior review about excessive API calls. Looks solid.
Also applies to: 75-85, 120-126
🧹 Nitpick comments (12)
commands/notePrompts.ts (1)
48-56: Use the existing guard helper for consistency.
execute duplicates the context check; reuse canExecute for a single source of truth.
- if (!editor || !view) {
+ if (!NotePromptsCommand.canExecute(editor, view)) {
new Notice('No active note found. Please open a note first.');
return;
}
api/anthropicClient.ts (3)
137-146: Reduce pagination calls by requesting larger pages.
Add limit=1000 (Anthropic allows 1–1000) to minimize round trips while keeping the loop for safety.
Showing a Notice every time fetching fails can spam users (e.g., during offline sessions). Consider rate-limiting (once per session/TTL window) or logging only.
Also applies to: 105-107
services/promptGenerator.ts (1)
156-168: Enforce the requested prompt count.
Models can occasionally over-generate. Trim to requested count for deterministic UX and cache keys.
50-53: Don’t merge modelCache into settings; destructure first.
Object.assign({}, DEFAULT_SETTINGS, data) copies modelCache into settings (type drift). Destructure to keep settings pure.
- const data = await this.loadData() as FreewritingPromptsData | null;
- this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
+ const data = await this.loadData() as FreewritingPromptsData | null;
+ const { modelCache, ...savedSettings } = data ?? {};
+ this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings);
+ // Load model cache after services are ready (kept below)
96-105: Unify settings load path or remove dead code.
onload() already loads/merges settings; loadSettings() duplicates that logic and may diverge. Pick one path to avoid drift.
113-125: Avoid unnecessary cache clears on save.
updateApiKey() clears the prompt cache; calling it on every save can purge cached prompts even when the key didn’t change. Consider updating the key only if it actually changed.
- if (this.promptGenerator) {
- this.promptGenerator.updateApiKey(this.settings.apiKey);
- }
+ if (this.promptGenerator) {
+ // Track last saved key to avoid redundant clears
+ // (Add: private lastApiKey?: string;)
+ if ((this as any).lastApiKey !== this.settings.apiKey) {
+ this.promptGenerator.updateApiKey(this.settings.apiKey);
+ (this as any).lastApiKey = this.settings.apiKey;
+ }
+ }
settings.ts (2)
110-113: Deduplicate API key propagation to avoid double cache clears.
You call updateApiKey() here and again inside saveSettings(); this can clear the prompt cache twice per keystroke. Rely on the post-save update (or move save into the debounced block) and drop the immediate call.
356-393: Persist after model fallback; UX copy tweak.
Flow is good. Two small tweaks:
When falling back to first available model, include the model id in the notice for clarity.
Save only if selection actually changed to reduce unnecessary writes.
- this.modelDropdown.setValue(fallbackModel.id);
- this.plugin.settings.model = fallbackModel.id;
- new Notice('Your selected model is no longer available. Defaulting to ' + fallbackModel.displayName);
+ this.modelDropdown.setValue(fallbackModel.id);
+ if (this.plugin.settings.model !== fallbackModel.id) {
+ this.plugin.settings.model = fallbackModel.id;
+ new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`);
+ }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 03d2b1c93d and ee7faef92b.
143-145: No action required—anthropic-version header is current.
The anthropic-version: 2023-06-01 header in both locations (lines 143-145 and 239-242) matches the current required value for the Messages and Models endpoints. No update needed.
**Actionable comments posted: 1**
> [!CAUTION]
> Some comments are outside the diff and can’t be posted inline due to platform limitations.
>
>
>
> <details>
> <summary>⚠️ Outside diff range comments (4)</summary><blockquote>
>
> <details>
> <summary>commands/notePrompts.ts (2)</summary><blockquote>
>
> `95-128`: **Prevent content merge when inserting mid-line; handle selections explicitly.**
>
> Current logic inserts a leading newline based on the entire line’s content and a trailing newline only if not at document end. This can merge inserted prompts with trailing text on the same line and ignores non-collapsed selections.
>
> - Add newline after if there is text after the cursor (or selection end).
> - Collapse selection before inserting to make cursor math deterministic.
>
>
> Apply:
>
> ```diff
> - private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
> - const cursor = editor.getCursor();
> - const currentLine = editor.getLine(cursor.line);
> - // Determine if we need to add a newline before our content
> - const needsNewlineBefore = currentLine.trim().length > 0;
> + private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
> + // Normalize to an insertion point (collapse any selection)
> + const from = editor.getCursor('from');
> + const to = editor.getCursor('to');
> + const hasSelection = from.line !== to.line || from.ch !== to.ch;
> + if (hasSelection) {
> + editor.setSelection(from, from);
> + }
> + const cursor = editor.getCursor(); // refreshed after collapse
> + const currentLine = editor.getLine(cursor.line) ?? '';
> +
> + const hasTextBefore = cursor.ch > 0 && currentLine.slice(0, cursor.ch).trim().length > 0;
> + const hasTextAfter = cursor.ch < currentLine.length && currentLine.slice(cursor.ch).trim().length > 0;
>
> // Format the prompts
> const formattedPrompts = this.formatPrompts(prompts);
>
> // Prepare the content to insert
> - let contentToInsert = '';
> -
> - if (needsNewlineBefore) {
> - contentToInsert += '\n';
> - }
> -
> - contentToInsert += formattedPrompts;
> -
> - // If we're not at the end of the document, add a trailing newline
> - const lastLine = editor.lastLine();
> - if (cursor.line < lastLine) {
> - contentToInsert += '\n';
> - }
> -
> - // Insert the content at the cursor position
> - editor.replaceSelection(contentToInsert);
> + const lastLine = editor.lastLine();
> + let contentToInsert = '';
> + if (hasTextBefore) contentToInsert += '\n';
> + contentToInsert += formattedPrompts;
> + if (hasTextAfter || cursor.line < lastLine) contentToInsert += '\n';
> +
> + // Insert the content at the cursor position
> + editor.replaceSelection(contentToInsert);
>
> // Position cursor at the end of the inserted content
> const lines = contentToInsert.split('\n');
> const newCursorLine = cursor.line + lines.length - 1;
> const newCursorCh = lines[lines.length - 1].length;
>
> editor.setCursor(newCursorLine, newCursorCh);
> }
> ```
>
> ---
>
> `149-156`: **Timestamp won’t include time with toLocaleDateString; use Intl.DateTimeFormat or toLocaleString.**
>
> toLocaleDateString typically ignores time fields. Switch to Intl.DateTimeFormat (or toLocaleString) to reliably include time.
>
>
> ```diff
> - const timestamp = new Date().toLocaleDateString('en-US', {
> - year: 'numeric',
> - month: 'short',
> - day: 'numeric',
> - hour: '2-digit',
> - minute: '2-digit'
> - });
> + const timestamp = new Intl.DateTimeFormat('en-US', {
> + year: 'numeric',
> + month: 'short',
> + day: 'numeric',
> + hour: '2-digit',
> + minute: '2-digit'
> + }).format(new Date());
> ```
>
> </blockquote></details>
> <details>
> <summary>types.ts (1)</summary><blockquote>
>
> `158-165`: **Update ANTHROPIC_MODELS list—missing latest Claude models.**
>
> The fallback list is incomplete and stale. Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) is now available and recommended, along with other variants not currently included:
>
> - **Add** claude-sonnet-4-5-20250929 (latest Sonnet model, released Sept 29, 2025)
> - **Add** claude-3-5-sonnet-latest (Sonnet 3.5 alias)
> - **Add** claude-3-opus-latest (Opus 3 alias)
> - **Standardize** to "-latest" aliases where available for stability, or use consistent canonical IDs.
>
> Periodically sync with Anthropic's current model offerings to prevent breakage when fallbacks are needed.
>
> </blockquote></details>
> <details>
> <summary>commands/timedPrompts.ts (1)</summary><blockquote>
>
> `171-174`: **Prevent notice/interval overlap for small delays.**
>
> With delaySeconds = 1, Math.max(1000, delay-500) yields 1000ms, equal to interval and can overlap the next notice. Clamp duration below the interval.
>
>
>
>
> ```diff
> - const notificationDuration = Math.max(1000, (delaySeconds * 1000) - 500);
> + const delayMs = delaySeconds * 1000;
> + // If very short delays, cap at 500ms; otherwise end 500ms before next tick
> + const notificationDuration = delayMs > 1000 ? (delayMs - 500) : 500;
> ```
>
> </blockquote></details>
>
> </blockquote></details>
<details>
<summary>♻️ Duplicate comments (2)</summary><blockquote>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
`121-199`: **Pagination implemented correctly; resolves prior concern.**
Looping with after=last_id until has_more=false fixes the one-page-only issue flagged earlier.
</blockquote></details>
<details>
<summary>settings.ts (1)</summary><blockquote>
`60-63`: **Nice: Debounced model refresh with proper cleanup.**
Debounce on API key changes and clearing the timer in hide() addresses the prior review about excessive API calls. Looks solid.
Also applies to: 75-85, 120-126
</blockquote></details>
</blockquote></details>
<details>
<summary>🧹 Nitpick comments (12)</summary><blockquote>
<details>
<summary>commands/notePrompts.ts (1)</summary><blockquote>
`48-56`: **Use the existing guard helper for consistency.**
execute duplicates the context check; reuse canExecute for a single source of truth.
```diff
- if (!editor || !view) {
+ if (!NotePromptsCommand.canExecute(editor, view)) {
new Notice('No active note found. Please open a note first.');
return;
}
```
</blockquote></details>
<details>
<summary>api/anthropicClient.ts (3)</summary><blockquote>
`137-146`: **Reduce pagination calls by requesting larger pages.**
Add limit=1000 (Anthropic allows 1–1000) to minimize round trips while keeping the loop for safety.
```diff
- const url = afterId ? `${this.modelsUrl}?after=${afterId}` : this.modelsUrl;
+ const params = new URLSearchParams();
+ if (afterId) params.set('after', afterId);
+ params.set('limit', '1000');
+ const url = `${this.modelsUrl}?${params.toString()}`;
```
If unsure about the current max limit, verify with the latest docs.
---
`271-289`: **Parse all text blocks, not just the first.**
Anthropic can return multiple text blocks. Join them before splitting into prompts.
```diff
- const text = response.content[0].text;
+ const text = response.content
+ .filter(c => c && c.type === 'text' && typeof c.text === 'string')
+ .map(c => c.text)
+ .join('\n');
```
---
`355-374`: **Validate the “ping” in testApiKey for a stronger sanity check.**
Currently success is based on any 2xx response. Ensure the assistant actually returned “ping”.
```diff
- const response = await this.makeRequest(testRequest);
+ const response = await this.makeRequest(testRequest);
const responseTime = Date.now() - startTime;
+ const returned = (response.content?.[0]?.text || '').trim().toLowerCase();
+ const ok = returned === 'ping';
- return {
- success: true,
- message: 'API key is valid and working correctly',
+ return {
+ success: ok,
+ message: ok ? 'API key is valid and working correctly'
+ : 'API responded but returned unexpected content',
details: {
model: response.model,
responseTime,
inputTokens: response.usage?.input_tokens,
outputTokens: response.usage?.output_tokens
}
- };
+ };
```
</blockquote></details>
<details>
<summary>services/modelService.ts (2)</summary><blockquote>
`172-177`: **Deduplicate models by id before caching.**
Defensive guard against accidental duplicates across pages.
```diff
- private updateCache(models: ModelInfo[]): void {
- this.modelCache = {
- models,
- fetchedAt: Date.now()
- };
- }
+ private updateCache(models: ModelInfo[]): void {
+ const byId = new Map<string, ModelInfo>();
+ for (const m of models) byId.set(m.id, m);
+ this.modelCache = {
+ models: Array.from(byId.values()),
+ fetchedAt: Date.now()
+ };
+ }
```
---
`79-82`: **Avoid noisy fallback notices.**
Showing a Notice every time fetching fails can spam users (e.g., during offline sessions). Consider rate-limiting (once per session/TTL window) or logging only.
Also applies to: 105-107
</blockquote></details>
<details>
<summary>services/promptGenerator.ts (1)</summary><blockquote>
`156-168`: **Enforce the requested prompt count.**
Models can occasionally over-generate. Trim to requested count for deterministic UX and cache keys.
```diff
- const prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type);
+ let prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type);
+ if (prompts.length > count) {
+ prompts = prompts.slice(0, count);
+ }
```
</blockquote></details>
<details>
<summary>main.ts (3)</summary><blockquote>
`50-53`: **Don’t merge modelCache into settings; destructure first.**
Object.assign({}, DEFAULT_SETTINGS, data) copies modelCache into settings (type drift). Destructure to keep settings pure.
```diff
- const data = await this.loadData() as FreewritingPromptsData | null;
- this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
+ const data = await this.loadData() as FreewritingPromptsData | null;
+ const { modelCache, ...savedSettings } = data ?? {};
+ this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings);
+ // Load model cache after services are ready (kept below)
```
---
`96-105`: **Unify settings load path or remove dead code.**
onload() already loads/merges settings; loadSettings() duplicates that logic and may diverge. Pick one path to avoid drift.
---
`113-125`: **Avoid unnecessary cache clears on save.**
updateApiKey() clears the prompt cache; calling it on every save can purge cached prompts even when the key didn’t change. Consider updating the key only if it actually changed.
```diff
- if (this.promptGenerator) {
- this.promptGenerator.updateApiKey(this.settings.apiKey);
- }
+ if (this.promptGenerator) {
+ // Track last saved key to avoid redundant clears
+ // (Add: private lastApiKey?: string;)
+ if ((this as any).lastApiKey !== this.settings.apiKey) {
+ this.promptGenerator.updateApiKey(this.settings.apiKey);
+ (this as any).lastApiKey = this.settings.apiKey;
+ }
+ }
```
</blockquote></details>
<details>
<summary>settings.ts (2)</summary><blockquote>
`110-113`: **Deduplicate API key propagation to avoid double cache clears.**
You call updateApiKey() here and again inside saveSettings(); this can clear the prompt cache twice per keystroke. Rely on the post-save update (or move save into the debounced block) and drop the immediate call.
```diff
- await this.plugin.saveSettings();
- this.plugin.promptGenerator.updateApiKey(value);
+ await this.plugin.saveSettings();
```
---
`356-393`: **Persist after model fallback; UX copy tweak.**
Flow is good. Two small tweaks:
- When falling back to first available model, include the model id in the notice for clarity.
- Save only if selection actually changed to reduce unnecessary writes.
```diff
- this.modelDropdown.setValue(fallbackModel.id);
- this.plugin.settings.model = fallbackModel.id;
- new Notice('Your selected model is no longer available. Defaulting to ' + fallbackModel.displayName);
+ this.modelDropdown.setValue(fallbackModel.id);
+ if (this.plugin.settings.model !== fallbackModel.id) {
+ this.plugin.settings.model = fallbackModel.id;
+ new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`);
+ }
```
</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 03d2b1c93df48dd4cc12a717d9b549495a93cbbf and ee7faef92bd7543876a57be06b39ba7e49562033.
</details>
<details>
<summary>📒 Files selected for processing (8)</summary>
* `api/anthropicClient.ts` (7 hunks)
* `commands/notePrompts.ts` (4 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `main.ts` (7 hunks)
* `services/modelService.ts` (1 hunks)
* `services/promptGenerator.ts` (6 hunks)
* `settings.ts` (4 hunks)
* `types.ts` (2 hunks)
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>🧬 Code graph analysis (7)</summary>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
<details>
<summary>types.ts (4)</summary>
* `AnthropicRequest` (57-66)
* `ModelsListResponse` (131-140)
* `ModelInfo` (116-125)
* `AnthropicResponse` (72-99)
</details>
</blockquote></details>
<details>
<summary>settings.ts (3)</summary><blockquote>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
<details>
<summary>main.ts (1)</summary>
* `FreewritingPromptsPlugin` (29-266)
</details>
<details>
<summary>services/modelService.ts (1)</summary>
* `ModelOption` (12-17)
</details>
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (2)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (23-292)
</details>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
</blockquote></details>
<details>
<summary>services/modelService.ts (1)</summary><blockquote>
<details>
<summary>types.ts (3)</summary>
* `ModelCache` (146-151)
* `ModelInfo` (116-125)
* `ANTHROPIC_MODELS` (158-165)
</details>
</blockquote></details>
<details>
<summary>commands/notePrompts.ts (1)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (23-292)
</details>
</blockquote></details>
<details>
<summary>main.ts (3)</summary><blockquote>
<details>
<summary>types.ts (2)</summary>
* `FreewritingPromptsSettings` (14-31)
* `FreewritingPromptsData` (37-40)
</details>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (23-292)
</details>
<details>
<summary>services/modelService.ts (1)</summary>
* `ModelService` (32-211)
</details>
</blockquote></details>
<details>
<summary>services/promptGenerator.ts (2)</summary><blockquote>
<details>
<summary>api/anthropicClient.ts (1)</summary>
* `AnthropicClient` (18-475)
</details>
<details>
<summary>types.ts (2)</summary>
* `GeneratedPrompt` (105-110)
* `FreewritingPromptsSettings` (14-31)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (1)</summary><blockquote>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
`143-145`: **No action required—anthropic-version header is current.**
The `anthropic-version: 2023-06-01` header in both locations (lines 143-145 and 239-242) matches the current required value for the Messages and Models endpoints. No update needed.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
Fix inProgress lifecycle to avoid races (stop() resets it).
execute() sets inProgress=true, then stop() immediately flips it back to false. A second execute can slip in while prompts are still generating. Reorder and remove the flag mutation from stop() so inProgress reliably guards concurrent runs.
@@
- // Check if already in progress to prevent race conditions
+ // Check if already in progress to prevent race conditions
if (this.inProgress) {
new Notice('Timed prompts are already being generated. Please wait.');
return;
}
-
- this.inProgress = true;
-
- // Stop any existing timed sequence
- this.stop();
+ // Stop any existing timed sequence
+ this.stop();
+ // Mark as in-progress only after cleanup to prevent re-entry
+ this.inProgress = true;
@@
stop(): void {
if (this.activeInterval !== null) {
clearInterval(this.activeInterval);
this.activeInterval = null;
}
this.promptQueue = [];
this.currentIndex = 0;
- this.inProgress = false;
}
Also applies to: 101-116
🤖 Prompt for AI Agents
In commands/timedPrompts.ts around lines 60-67 (and similarly lines 101-116),
execute() sets this.inProgress = true but stop() immediately resets it to false,
allowing a second execute() to slip in during generation; remove the mutation of
this.inProgress from stop(), ensure execute() sets this.inProgress = true before
starting async work, and only reset this.inProgress = false after all generation
and cleanup have completed (use a finally block or end-of-flow path to guarantee
reset) so the flag reliably prevents concurrent runs.
_⚠️ Potential issue_ | _🔴 Critical_
**Fix inProgress lifecycle to avoid races (stop() resets it).**
execute() sets inProgress=true, then stop() immediately flips it back to false. A second execute can slip in while prompts are still generating. Reorder and remove the flag mutation from stop() so inProgress reliably guards concurrent runs.
```diff
@@
- // Check if already in progress to prevent race conditions
+ // Check if already in progress to prevent race conditions
if (this.inProgress) {
new Notice('Timed prompts are already being generated. Please wait.');
return;
}
-
- this.inProgress = true;
-
- // Stop any existing timed sequence
- this.stop();
+ // Stop any existing timed sequence
+ this.stop();
+ // Mark as in-progress only after cleanup to prevent re-entry
+ this.inProgress = true;
@@
stop(): void {
if (this.activeInterval !== null) {
clearInterval(this.activeInterval);
this.activeInterval = null;
}
this.promptQueue = [];
this.currentIndex = 0;
- this.inProgress = false;
}
```
Also applies to: 101-116
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In commands/timedPrompts.ts around lines 60-67 (and similarly lines 101-116),
execute() sets this.inProgress = true but stop() immediately resets it to false,
allowing a second execute() to slip in during generation; remove the mutation of
this.inProgress from stop(), ensure execute() sets this.inProgress = true before
starting async work, and only reset this.inProgress = false after all generation
and cleanup have completed (use a finally block or end-of-flow path to guarantee
reset) so the flag reliably prevents concurrent runs.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits da6056b to 893aae5
64-91: Deduplicate concurrent fetches to avoid redundant API calls.
If multiple views request models simultaneously, this can fire parallel fetches. Cache the in‑flight promise and return it to callers until it settles.
export class ModelService {
private anthropicClient: AnthropicClient;
private modelCache: ModelCache | null = null;
+ /** In-flight fetch promise to dedupe concurrent calls */
+ private inFlight: Promise<ModelOption[]> | null = null;
async getAvailableModels(): Promise<ModelOption[]> {
// Check if we have a valid cache
if (this.isCacheValid() && this.modelCache) {
return this.formatModels(this.modelCache.models);
}
// If no API key, quietly return fallback
if (!this.anthropicClient.validateApiKey()) {
return this.getFallbackModels();
}
- // Try to fetch from API
- try {
- const response = await this.anthropicClient.fetchModels();
- this.updateCache(response.data);
- // Reset notice flag on successful fetch
- this.hasShownFallbackNotice = false;
- return this.formatModels(response.data);
- } catch (error) {
+ // Try to fetch from API (deduped)
+ if (!this.inFlight) {
+ this.inFlight = (async () => {
+ const response = await this.anthropicClient.fetchModels();
+ this.updateCache(response.data);
+ this.hasShownFallbackNotice = false;
+ return this.formatModels(response.data);
+ })().finally(() => (this.inFlight = null));
+ }
+ try {
+ return await this.inFlight;
+ } catch (error) {
console.error('Failed to fetch models from API:', error);
// Only show notice once per session to avoid spamming during offline periods
if (!this.hasShownFallbackNotice) {
new Notice('Could not fetch latest models from API. Using default model list.');
this.hasShownFallbackNotice = true;
}
return this.getFallbackModels();
}
}
169-177: Serve stale cache on fetch failure before falling back.
If a cache exists but is just past TTL, prefer returning it on API failure. It’s often better UX than dropping to a potentially outdated hardcoded list.
private isCacheValid(): boolean {
if (!this.modelCache) {
return false;
}
const now = Date.now();
const age = now - this.modelCache.fetchedAt;
return age < this.CACHE_TTL_MS;
}
+
+ /** Returns cached models if present, regardless of TTL */
+ private getStaleCacheModels(): ModelOption[] | null {
+ if (!this.modelCache) return null;
+ return this.formatModels(this.modelCache.models);
+ }
85-90: Optional: decouple UI notifications from the service.
Emitting Notice inside the service couples logic to UI. Consider injecting a notifier interface or bubbling errors to the caller (settings tab) to decide when/how to notify.
Also applies to: 117-121
main.ts (2)
52-61: Guard against corrupted persisted data.
Wrap loadData + merge in try/catch to avoid failing plugin load if the JSON is malformed. Fallback to DEFAULT_SETTINGS.
- const data = await this.loadData() as FreewritingPromptsData | null;
-
- // Destructure to prevent modelCache from being merged into settings (type drift)
- const { modelCache, ...savedSettings } = data ?? {};
- this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings);
+ let modelCache: FreewritingPromptsData['modelCache'] | undefined;
+ try {
+ const data = (await this.loadData()) as FreewritingPromptsData | null;
+ const loaded = data ?? {};
+ ({ modelCache, ...this.settings } = Object.assign({}, DEFAULT_SETTINGS, loaded));
+ } catch (e) {
+ console.error('Failed to load settings; using defaults.', e);
+ this.settings = { ...DEFAULT_SETTINGS };
+ modelCache = undefined;
+ }
112-124: High-frequency saves from settings UI.
display()’s input handlers call saveSettings on each keystroke. Consider debouncing saveSettings calls or saving on blur to reduce disk writes. This is already partially mitigated for model refresh; apply similarly to saving.
commands/notePrompts.ts (2)
95-104: Replace selection instead of collapsing it.
Current behavior discards the selection without deleting it, then inserts prompts. Users typically expect insertion to replace the selection. Either replace selection directly or make this behavior configurable.
- // Normalize to an insertion point (collapse any selection)
- const from = editor.getCursor('from');
- const to = editor.getCursor('to');
- const hasSelection = from.line !== to.line || from.ch !== to.ch;
- if (hasSelection) {
- editor.setSelection(from, from);
- }
- const cursor = editor.getCursor(); // refreshed after collapse
+ // Replace selection if present; otherwise insert at cursor
+ const from = editor.getCursor('from');
+ const to = editor.getCursor('to');
+ const hasSelection = from.line !== to.line || from.ch !== to.ch;
+ const cursor = hasSelection ? to : editor.getCursor(); // end-of-selection as insertion point
@@
- // Insert the content at the cursor position
- editor.replaceSelection(contentToInsert);
+ // Insert or replace selection with the content
+ editor.replaceSelection(contentToInsert);
Also applies to: 119-128
148-156: Use user locale for timestamps.
Hardcoding 'en-US' reduces i18n quality. Prefer the user’s locale (navigator.language) and options that respect 12/24h conventions.
146-156: Guard dropdown state when models haven’t loaded.
If availableModels is empty, setValue(this.plugin.settings.model) may set an option that doesn’t exist. You already disable the dropdown; also skip setValue until options are present.
153-176: Minimize maintenance burden in fallback model list.
Release dates and point-in-time IDs drift quickly. Prefer stable “-latest” aliases where possible and trim dated commentary to avoid stale docs in code.
Proposed tweaks:
Favor “…-latest” where Anthropic provides it.
Move release notes to a CHANGELOG instead of inline comments.
Add a TODO with a link to docs rather than specific dates.
services/promptGenerator.ts (2)
116-184: Add in‑flight request deduplication to prevent duplicate API calls.
Concurrent calls with identical params can bypass the cache and hit the API multiple times.
export class PromptGeneratorService {
@@
- private cache: Map<string, GeneratedPrompt[]> = new Map();
+ private cache: Map<string, GeneratedPrompt[]> = new Map();
+ private inFlight: Map<string, Promise<string[]>> = new Map();
@@
private async generatePrompts(
@@
- if (cachedPrompts) {
+ if (cachedPrompts) {
return cachedPrompts.map(p => p.text);
}
+
+ // Deduplicate concurrent requests
+ const existing = this.inFlight.get(cacheKey);
+ if (existing) return existing;
@@
- try {
+ try {
new Notice('Generating prompts...');
- let prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type);
+ const pending = this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type);
+ this.inFlight.set(cacheKey, pending);
+ let prompts = await pending;
@@
} catch (error) {
console.error('Error in PromptGeneratorService:', error);
if (error instanceof Error) {
new Notice(`Error generating prompts: ${error.message}`);
} else {
new Notice('Unknown error occurred while generating prompts');
}
throw error;
- }
+ } finally {
+ this.inFlight.delete(cacheKey);
+ }
270-297: Validation is good; consider exposing it to callers.
If not already, ensure settings UI calls validateSettings and surfaces all errors together.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ee7faef92b and 893aae5bca.
⛔ Files ignored due to path filters (1)
package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
.eslintignore (0 hunks)
.eslintrc (0 hunks)
api/anthropicClient.ts (8 hunks)
commands/notePrompts.ts (4 hunks)
commands/timedPrompts.ts (4 hunks)
eslint.config.mjs (1 hunks)
main.ts (6 hunks)
package.json (1 hunks)
services/modelService.ts (1 hunks)
services/promptGenerator.ts (7 hunks)
settings.ts (4 hunks)
types.ts (1 hunks)
💤 Files with no reviewable changes (2)
.eslintignore
.eslintrc
🚧 Files skipped from review as they are similar to previous changes (1)
Add loop‑safety guard and de‑duplication for models pagination.
Defensive guards prevent runaway loops and duplicate model ids if the API misbehaves or cursors don’t advance.
Apply this diff:
- // Fetch all pages
- while (hasMore) {
+ // Fetch all pages with safety guards
+ const seen = new Set<string>();
+ let pageCount = 0;
+ const MAX_PAGES = 100;
+ while (hasMore) {
+ if (pageCount++ > MAX_PAGES) {
+ throw new Error(`Models pagination exceeded ${MAX_PAGES} pages (cursor did not converge)`);
+ }
@@
- const pageResponse = data as ModelsListResponse;
+ const pageResponse = data as ModelsListResponse;
@@
- allModels.push(...pageResponse.data);
+ for (const m of pageResponse.data) {
+ if (!seen.has(m.id)) {
+ seen.add(m.id);
+ allModels.push(m);
+ }
+ }
@@
- // Set up for next iteration
- if (hasMore) {
- afterId = lastId;
- }
+ // Set up for next iteration; break if cursor didn’t advance
+ if (hasMore) {
+ if (afterId === lastId) {
+ throw new Error('Models pagination cursor did not advance (after_id equals last_id)');
+ }
+ afterId = lastId;
+ }
🤖 Prompt for AI Agents
In api/anthropicClient.ts around lines 134 to 190, the pagination loop lacks
protections against runaway loops and duplicate models if the API returns the
same cursor or repeated items; add a loop-safety guard (e.g., maxIterations =
1000 and increment a counter each loop, throw if exceeded), track seen model ids
with a Set to filter out duplicates before pushing into allModels, detect lack
of cursor progress by checking if lastId is falsy or equals the previous afterId
and break to avoid infinite looping, and ensure afterId is only updated to
lastId when it advances.
_🛠️ Refactor suggestion_ | _🟠 Major_
**Add loop‑safety guard and de‑duplication for models pagination.**
Defensive guards prevent runaway loops and duplicate model ids if the API misbehaves or cursors don’t advance.
Apply this diff:
```diff
- // Fetch all pages
- while (hasMore) {
+ // Fetch all pages with safety guards
+ const seen = new Set<string>();
+ let pageCount = 0;
+ const MAX_PAGES = 100;
+ while (hasMore) {
+ if (pageCount++ > MAX_PAGES) {
+ throw new Error(`Models pagination exceeded ${MAX_PAGES} pages (cursor did not converge)`);
+ }
@@
- const pageResponse = data as ModelsListResponse;
+ const pageResponse = data as ModelsListResponse;
@@
- allModels.push(...pageResponse.data);
+ for (const m of pageResponse.data) {
+ if (!seen.has(m.id)) {
+ seen.add(m.id);
+ allModels.push(m);
+ }
+ }
@@
- // Set up for next iteration
- if (hasMore) {
- afterId = lastId;
- }
+ // Set up for next iteration; break if cursor didn’t advance
+ if (hasMore) {
+ if (afterId === lastId) {
+ throw new Error('Models pagination cursor did not advance (after_id equals last_id)');
+ }
+ afterId = lastId;
+ }
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In api/anthropicClient.ts around lines 134 to 190, the pagination loop lacks
protections against runaway loops and duplicate models if the API returns the
same cursor or repeated items; add a loop-safety guard (e.g., maxIterations =
1000 and increment a counter each loop, throw if exceeded), track seen model ids
with a Set to filter out duplicates before pushing into allModels, detect lack
of cursor progress by checking if lastId is falsy or equals the previous afterId
and break to avoid infinite looping, and ensure afterId is only updated to
lastId when it advances.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits afa725d to 3f53bb5
Critical: Pagination uses after instead of after_id — can cause infinite loop/duplicate pages.
Anthropic’s models pagination uses before_id/after_id. Using after likely re-fetches the first page forever if has_more is true, looping and duplicating results.
Apply this diff:
- if (afterId) {
- params.set('after', afterId);
- }
+ if (afterId) {
+ params.set('after_id', afterId);
+ }
Please confirm param naming against current docs:
🌐 Web query:
Does Anthropic's List Models endpoint use the query param name `after_id` (not `after`) for pagination?
💡 Result:
Yes — the List Models endpoint uses the query parameter after_id (not after) for pagination. [1][2]
Sources:
Anthropic API — List Models documentation. [1]
Claude (Anthropic) localized docs — List Models (shows after_id). [2]
🏁 Script executed:
#!/bin/bash
# Verify the pagination bug in api/anthropicClient.ts
fd api/anthropicClient.ts --exec cat {}
Length of output: 0
🏁 Script executed:
#!/bin/bash
# Search for anthropicClient file with broader pattern
fd -e ts anthropicClient
Length of output: 22
🏁 Script executed:
#!/bin/bash
# View the anthropicClient.ts file with line numbers, focusing on pagination section
cat -n api/anthropicClient.ts | sed -n '130,150p'
Critical: Fix pagination parameter from after to after_id at line 141.
Anthropic's List Models endpoint uses the query parameter after_id (not after) for pagination. The current code at line 141 uses the incorrect parameter name, which will cause the API to ignore the pagination cursor and potentially loop indefinitely or return duplicate results.
if (afterId) {
- params.set('after', afterId);
+ params.set('after_id', afterId);
}
📝 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.
// Build URL with pagination parameters
// Use limit=1000 (Anthropic's max) to minimize round trips
const params = new URLSearchParams();
params.set('limit', '1000');
if (afterId) {
params.set('after_id', afterId);
}
const url = `${this.modelsUrl}?${params.toString()}`;
🤖 Prompt for AI Agents
In api/anthropicClient.ts around lines 136 to 144, the code sets the pagination
query parameter as 'after' which is incorrect for Anthropic's List Models
endpoint; change the parameter key to 'after_id' when afterId is present (i.e.,
params.set('after_id', afterId)) so the pagination cursor is passed correctly,
leaving the rest of the URL construction and limit=1000 logic unchanged.
_⚠️ Potential issue_ | _🔴 Critical_
<details>
<summary>🧩 Analysis chain</summary>
**Critical: Pagination uses `after` instead of `after_id` — can cause infinite loop/duplicate pages.**
Anthropic’s models pagination uses `before_id`/`after_id`. Using `after` likely re-fetches the first page forever if `has_more` is true, looping and duplicating results.
Apply this diff:
```diff
- if (afterId) {
- params.set('after', afterId);
- }
+ if (afterId) {
+ params.set('after_id', afterId);
+ }
```
Please confirm param naming against current docs:
---
🌐 Web query:
```web
Does Anthropic's List Models endpoint use the query param name `after_id` (not `after`) for pagination?
```
💡 Result:
Yes — the List Models endpoint uses the query parameter after_id (not after) for pagination. [1][2]
Sources:
- Anthropic API — List Models documentation. [1]
- Claude (Anthropic) localized docs — List Models (shows after_id). [2]
---
🏁 Script executed:
```shell
#!/bin/bash
# Verify the pagination bug in api/anthropicClient.ts
fd api/anthropicClient.ts --exec cat {}
```
Length of output: 0
---
🏁 Script executed:
```shell
#!/bin/bash
# Search for anthropicClient file with broader pattern
fd -e ts anthropicClient
```
Length of output: 22
---
🏁 Script executed:
```shell
#!/bin/bash
# View the anthropicClient.ts file with line numbers, focusing on pagination section
cat -n api/anthropicClient.ts | sed -n '130,150p'
```
Length of output: 976
---
🏁 Script executed:
```shell
#!/bin/bash
# View complete pagination loop
cat -n api/anthropicClient.ts | sed -n '135,190p'
```
Length of output: 2700
---
</details>
**Critical: Fix pagination parameter from `after` to `after_id` at line 141.**
Anthropic's List Models endpoint uses the query parameter `after_id` (not `after`) for pagination. The current code at line 141 uses the incorrect parameter name, which will cause the API to ignore the pagination cursor and potentially loop indefinitely or return duplicate results.
```diff
if (afterId) {
- params.set('after', afterId);
+ params.set('after_id', afterId);
}
```
<!-- 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
// Build URL with pagination parameters
// Use limit=1000 (Anthropic's max) to minimize round trips
const params = new URLSearchParams();
params.set('limit', '1000');
if (afterId) {
params.set('after_id', afterId);
}
const url = `${this.modelsUrl}?${params.toString()}`;
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In api/anthropicClient.ts around lines 136 to 144, the code sets the pagination
query parameter as 'after' which is incorrect for Anthropic's List Models
endpoint; change the parameter key to 'after_id' when afterId is present (i.e.,
params.set('after_id', afterId)) so the pagination cursor is passed correctly,
leaving the rest of the URL construction and limit=1000 logic unchanged.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits afa725d to 3f53bb5
coderabbitai[bot]
(Migrated from github.com)
left a comment
Copy link
Copy source
Actionable comments posted: 0
🧹 Nitpick comments (15)
eslint.config.mjs (2)
25-31: Set tsconfigRootDir (and consider projectService) to avoid path resolution issues.
Without tsconfigRootDir, ESLint resolves project from CWD; this can break in editors/monorepos. Also consider projectService for faster type-aware linting.
languageOptions: {
parser: tseslint.parser,
parserOptions: {
sourceType: 'module',
ecmaVersion: 'latest',
- project: ['./tsconfig.json']
+ project: ['./tsconfig.json'],
+ tsconfigRootDir: new URL('.', import.meta.url),
+ // Optional: use the TS Project Service instead of explicit project for perf
+ // projectService: true
},
113-135: Unify fetch path to reuse in‑flight dedupe (optional).
refreshModels bypasses in‑flight, so concurrent getAvailableModels+refreshModels can double‑call the API. Consider a shared private fetchAndCache() used by both.
If both API and fallback unexpectedly return empty, avoid accessing index 0 and keep the dropdown disabled with a clear message.
- } else {
+ } else {
// Fall back to first available model if current one is gone
const fallbackModel = this.availableModels[0];
- if (fallbackModel && this.plugin.settings.model !== fallbackModel.id) {
+ if (!fallbackModel) {
+ this.modelDropdown.setDisabled(true);
+ this.modelDropdown.selectEl.empty();
+ this.modelDropdown.addOption('', 'No models available');
+ } else if (this.plugin.settings.model !== fallbackModel.id) {
this.modelDropdown.setValue(fallbackModel.id);
this.plugin.settings.model = fallbackModel.id;
await this.plugin.saveSettings();
new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`);
}
}
389-426: Add a “Clear model list cache” action in Settings.
Currently only prompt cache is clearable. Exposing modelService.clearCache helps users force re-fetch after outages.
// In display(), under // MARK: - Actions
new Setting(containerEl)
.setName('Clear Cache')
@@
setTimeout(() => notice.hide(), 2000);
}));
+new Setting(containerEl)
+ .setName('Clear Model List Cache')
+ .setDesc('Clear cached Claude model list to force a fresh fetch')
+ .addButton(button => button
+ .setButtonText('Clear Models Cache')
+ .onClick(() => {
+ this.plugin.modelService.clearCache();
+ const notice = new Notice('Model list cache cleared');
+ setTimeout(() => notice.hide(), 2000);
+ }));
main.ts (1)
126-139: Also clear model cache when API key changes (defensive).
Settings tab refreshes models, but clearing here guarantees no cross‑key cache leakage if settings are changed programmatically.
if (this.promptGenerator && this.lastApiKey !== this.settings.apiKey) {
this.promptGenerator.updateApiKey(this.settings.apiKey);
this.lastApiKey = this.settings.apiKey;
+ // Ensure model list reflects new account entitlements
+ this.modelService?.clearCache();
}
commands/notePrompts.ts (2)
96-104: Use setCursor() to collapse selection (clearer, same behavior).
setSelection(from, from) works but is less idiomatic than setCursor(from).
- if (hasSelection) {
- editor.setSelection(from, from);
- }
- const cursor = editor.getCursor(); // refreshed after collapse
+ if (hasSelection) {
+ editor.setCursor(from);
+ }
+ const cursor = editor.getCursor(); // refreshed after collapse
149-157: Avoid navigator dependency for locale; let Intl pick the default.
Intl.DateTimeFormat(undefined, …) uses the environment’s default locale and removes the need to touch navigator.
- // Use user's locale for timestamp formatting to respect regional preferences
- const locale = navigator?.language ?? 'en-US';
- const timestamp = new Intl.DateTimeFormat(locale, {
+ // Let Intl pick the default environment locale
+ const timestamp = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(new Date());
api/anthropicClient.ts (2)
322-326: Harden prompt-line cleanup to handle more list prefixes.
Current regex removes only "1. ". Handle "1)" and bullets like "-", "*", "•".
If Anthropic ever returns a non-text block first, this change avoids false negatives.
settings.ts (4)
296-306: Persist the “Clear Models Cache” action to disk.
Currently clears in memory only; cache will reappear after reload until settings are saved.
.onClick(() => {
this.plugin.modelService.clearCache();
// Show a temporary notice
const notice = new Notice('Model list cache cleared');
setTimeout(() => notice.hide(), 2000);
+ // Persist the cleared cache so it doesn't restore on restart
+ void this.plugin.saveSettings();
}));
192-205: Use numeric input attributes to enforce bounds in the UI (Timed Count).
Helps prevent invalid characters and guides users.
143-218: Pagination, dedup, and loop safety look solid.
Using limit=1000, after_id, seen-id de-dupe, and cursor-advance guard is robust. Nice work.
96-100: The code is correct; no API contract issue exists.
Anthropic Messages v1 allows message content to be either a plain string or an array of content blocks, with a string serving as shorthand for a single text block. The content: userMessage format in your code is valid and will not produce 400 errors.
160-167: Remove timeout parameters — Obsidian's requestUrl API does not support them.
Obsidian's RequestUrlParam does not include a timeout option. The documented fields are url, method, contentType, body, headers, and throw only. The proposed diff adding timeout: 15000 and timeout: 20000 will not work.
If request timeouts are needed, use Promise.race to wrap requestUrl with a timeout (though the underlying request will still run), or adopt a proxy/backend approach for true request cancellation.
Likely an incorrect or invalid review comment.
settings.ts (1)
131-154: Debounced save + async model loading is clean.
Nice debounce handling and non-blocking dropdown population.
Also applies to: 185-187
commands/notePrompts.ts (1)
95-128: LGTM on editor checks and insertion heuristics.
Selection collapse, before/after newline handling, and cursor repositioning read well.
Also applies to: 181-183
main.ts (1)
52-92: Solid lifecycle and settings orchestration.
Data load with safe destructuring, service init, command registration, and selective cache clear on API-key change look good.
Also applies to: 116-142
services/modelService.ts (1)
153-179: Model caching/fallback path is robust.
In-flight dedupe, 24h TTL, stale-cache preference, and dedup/filter on updateCache are well-implemented.
Also applies to: 227-243, 271-276
commands/timedPrompts.ts (2)
61-104: LGTM! Race condition properly addressed.
The inProgress flag lifecycle now correctly prevents concurrent execution during async prompt generation. Setting the flag before any async work (line 69), ensuring stop() doesn't reset it (line 123), and resetting it in the finally block (line 102) provides reliable concurrency protection.
116-124: LGTM! Clean implementation with proper lifecycle management.
The supporting methods are well-implemented:
stop() correctly cleans up state without interfering with concurrency control
startInterval() properly manages the display cycle and completion
‼️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.
// For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller)
// Clamp to minimum 300ms to prevent flicker/invisible notices
const delayMs = Math.max(0, delaySeconds * 1000);
const notificationDuration =
delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
🤖 Prompt for AI Agents
In commands/timedPrompts.ts around lines 180 to 184, the ternary uses `delayMs >
1000` which creates a discontinuity at exactly 1000ms; change the condition to
`delayMs >= 1000` so the branch that computes the shorter notification duration
runs at 1000ms and smooths the transition, and update the adjacent comment to
reflect the new boundary behavior.
_⚠️ Potential issue_ | _🟡 Minor_
**Smoothen notification duration transition at 1-second boundary.**
The condition `delayMs > 1000` creates a discontinuity:
- At 1000ms delay → 900ms notification
- At 1001ms delay → 501ms notification (~400ms jump)
Consider using `>=` instead to create a smoother transition:
Apply this diff:
```diff
- const notificationDuration =
- delayMs > 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
+ const notificationDuration =
+ delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
```
With this change:
- At 1000ms: 500ms notification (smooth)
- At 999ms: 899ms notification (capped)
- At 1001ms: 501ms notification (smooth)
<!-- 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
// For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller)
// Clamp to minimum 300ms to prevent flicker/invisible notices
const delayMs = Math.max(0, delaySeconds * 1000);
const notificationDuration =
delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In commands/timedPrompts.ts around lines 180 to 184, the ternary uses `delayMs >
1000` which creates a discontinuity at exactly 1000ms; change the condition to
`delayMs >= 1000` so the branch that computes the shorter notification duration
runs at 1000ms and smooths the transition, and update the adjacent comment to
reflect the new boundary behavior.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits d5af2a0 to 9b8ff31
The class-level JSDoc is comprehensive and clearly explains the command's responsibilities, including the race condition prevention and notification timing strategy. This makes the code very maintainable.
61-104: Race condition properly addressed!
The inProgress lifecycle is now correct:
Flag is checked before any work begins (line 63)
Flag is set before async work starts (line 69)
stop() does NOT reset the flag (avoiding the previous race)
finally block ensures the flag is always reset after completion
This prevents concurrent executions during async prompt generation and resolves the critical issue from the previous review.
106-124: Clean separation of concerns in stop().
The method correctly handles cleanup while explicitly NOT resetting inProgress, as documented. This design ensures that only execute() manages the concurrency flag, preventing the race condition that existed before.
210-219: Robust bounds checking in getStatus().
The calculation of currentPrompt properly handles edge cases (empty queue, completion) and correctly converts the 0-based index to a 1-based prompt number for UI display.
228-233: LGTM!
The implementation correctly returns prompts that haven't been displayed yet, excluding the current prompt (which has already been shown when this is called).
137-158: Clean interval management.
The method properly manages the interval lifecycle, shows prompts sequentially, and handles completion with appropriate cleanup and user feedback.
**Actionable comments posted: 2**
<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 d31cec03834e9df8929a688fea4b678d344eeefd and 9b8ff3181aba03386174722e9d2e87e8171ce1f7.
</details>
<details>
<summary>📒 Files selected for processing (4)</summary>
* `api/anthropicClient.ts` (8 hunks)
* `commands/notePrompts.ts` (3 hunks)
* `commands/timedPrompts.ts` (4 hunks)
* `settings.ts` (10 hunks)
</details>
<details>
<summary>🧰 Additional context used</summary>
<details>
<summary>🧬 Code graph analysis (4)</summary>
<details>
<summary>api/anthropicClient.ts (1)</summary><blockquote>
<details>
<summary>types.ts (4)</summary>
* `AnthropicRequest` (57-66)
* `ModelsListResponse` (131-140)
* `ModelInfo` (116-125)
* `AnthropicResponse` (72-99)
</details>
</blockquote></details>
<details>
<summary>commands/timedPrompts.ts (2)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (23-310)
</details>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
</blockquote></details>
<details>
<summary>commands/notePrompts.ts (2)</summary><blockquote>
<details>
<summary>services/promptGenerator.ts (1)</summary>
* `PromptGeneratorService` (23-310)
</details>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
</blockquote></details>
<details>
<summary>settings.ts (3)</summary><blockquote>
<details>
<summary>types.ts (1)</summary>
* `FreewritingPromptsSettings` (14-31)
</details>
<details>
<summary>main.ts (1)</summary>
* `FreewritingPromptsPlugin` (29-283)
</details>
<details>
<summary>services/modelService.ts (1)</summary>
* `ModelOption` (12-17)
</details>
</blockquote></details>
</details>
</details>
<details>
<summary>🔇 Additional comments (6)</summary><blockquote>
<details>
<summary>commands/timedPrompts.ts (6)</summary><blockquote>
`8-24`: **Excellent documentation!**
The class-level JSDoc is comprehensive and clearly explains the command's responsibilities, including the race condition prevention and notification timing strategy. This makes the code very maintainable.
---
`61-104`: **Race condition properly addressed!**
The `inProgress` lifecycle is now correct:
1. Flag is checked before any work begins (line 63)
2. Flag is set **before** async work starts (line 69)
3. `stop()` does NOT reset the flag (avoiding the previous race)
4. `finally` block ensures the flag is always reset after completion
This prevents concurrent executions during async prompt generation and resolves the critical issue from the previous review.
---
`106-124`: **Clean separation of concerns in stop().**
The method correctly handles cleanup while explicitly NOT resetting `inProgress`, as documented. This design ensures that only `execute()` manages the concurrency flag, preventing the race condition that existed before.
---
`210-219`: **Robust bounds checking in getStatus().**
The calculation of `currentPrompt` properly handles edge cases (empty queue, completion) and correctly converts the 0-based index to a 1-based prompt number for UI display.
---
`228-233`: **LGTM!**
The implementation correctly returns prompts that haven't been displayed yet, excluding the current prompt (which has already been shown when this is called).
---
`137-158`: **Clean interval management.**
The method properly manages the interval lifecycle, shows prompts sequentially, and handles completion with appropriate cleanup and user feedback.
</blockquote></details>
</blockquote></details>
</details>
<!-- This is an auto-generated comment by CodeRabbit for review status -->
Sorting the collected models before returning them means the original first_id/last_id no longer describe the first and last entries in data. Any consumer that trusts those fields for cache validation or pagination deltas will now read inconsistent state. Recompute the IDs from the sorted array (or skip the sort) before returning.
‼️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.
In api/anthropicClient.ts around lines 221 to 231, sorting the collected models
before returning makes the previously computed first_id/last_id inconsistent
with the returned data; recompute the pagination IDs from the sorted array (or
avoid sorting) so they match the response: after creating sorted, set first_id
to sorted[0].id and last_id to sorted[sorted.length-1].id (guard for empty array
and use null/undefined as appropriate), keep has_more as before, and return
those recomputed IDs so consumers see consistent pagination metadata.
_⚠️ Potential issue_ | _🟠 Major_
**Keep pagination metadata in sync after sorting**
Sorting the collected models before returning them means the original `first_id`/`last_id` no longer describe the first and last entries in `data`. Any consumer that trusts those fields for cache validation or pagination deltas will now read inconsistent state. Recompute the IDs from the sorted array (or skip the sort) before returning.
```diff
const sorted = allModels.slice().sort((a, b) =>
(a.display_name ?? a.id).localeCompare(b.display_name ?? b.id)
);
// Return combined response with all models
return {
- data: sorted,
- first_id: firstId,
- has_more: false, // We've fetched all pages
- last_id: lastId
+ data: sorted,
+ first_id: sorted[0]?.id ?? firstId ?? '',
+ has_more: false, // We've fetched all pages
+ last_id: sorted[sorted.length - 1]?.id ?? lastId ?? ''
};
```
<!-- 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
const sorted = allModels.slice().sort((a, b) =>
(a.display_name ?? a.id).localeCompare(b.display_name ?? b.id)
);
// Return combined response with all models
return {
data: sorted,
first_id: sorted[0]?.id ?? firstId ?? '',
has_more: false, // We've fetched all pages
last_id: sorted[sorted.length - 1]?.id ?? lastId ?? ''
};
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In api/anthropicClient.ts around lines 221 to 231, sorting the collected models
before returning makes the previously computed first_id/last_id inconsistent
with the returned data; recompute the pagination IDs from the sorted array (or
avoid sorting) so they match the response: after creating sorted, set first_id
to sorted[0].id and last_id to sorted[sorted.length-1].id (guard for empty array
and use null/undefined as appropriate), keep has_more as before, and return
those recomputed IDs so consumers see consistent pagination metadata.
```
</details>
<!-- fingerprinting:phantom:medusa:sabertoothed -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits 5bf804b to 4cb2308
The notification duration logic correctly uses >= (line 185), which addresses the previous review's concern about the 1-second boundary. However, the comment on line 180 still says ">1s" instead of ">=1s".
Apply this diff to align the comment with the implementation:
- // For delays >1s, end 500ms before next tick
+ // For delays >=1s, end 500ms before next tick
🤖 Prompt for AI Agents
In commands/timedPrompts.ts around lines 179 to 185, the inline comment
incorrectly says ">1s" while the code uses ">= 1000" to branch on the 1-second
boundary; update the comment to say ">=1s" (or "1s or greater") so the comment
matches the implementation, keeping the rest of the explanatory text unchanged.
_⚠️ Potential issue_ | _🟡 Minor_
**Update comment to match the code boundary.**
The notification duration logic correctly uses `>=` (line 185), which addresses the previous review's concern about the 1-second boundary. However, the comment on line 180 still says ">1s" instead of ">=1s".
Apply this diff to align the comment with the implementation:
```diff
- // For delays >1s, end 500ms before next tick
+ // For delays >=1s, end 500ms before next tick
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In commands/timedPrompts.ts around lines 179 to 185, the inline comment
incorrectly says ">1s" while the code uses ">= 1000" to branch on the 1-second
boundary; update the comment to say ">=1s" (or "1s or greater") so the comment
matches the implementation, keeping the rest of the explanatory text unchanged.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits 5bf804b to 4cb2308
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Overview
Introduces a comprehensive model management system for Anthropic Claude models with the following key improvements:
Features
Improvements
Changes
Additional Notes
Enables more dynamic and up-to-date model selection for AI-powered writing prompts.
Summary by CodeRabbit
New Features
Bug Fixes
Chores / Documentation
@coderabbitai review
@coderabbit review
✅ Actions performed
Review triggered.
Walkthrough
Updated CI release action and repository references; changed license/author metadata; added model discovery, caching, and UI dropdown; refactored Anthropic client for messages/models endpoints and key testing; added ModelService and PromptGenerator caching; introduced timed and note prompt commands and plugin lifecycle/settings updates.
Changes
\.github/workflows/release.yml,CHANGELOG.md,README.md,package.jsonsoftprops/action-gh-releasev1 → v2; normalized repo owner/name capitalization in links; updated changelog dates/entries; changed license MIT → GPL‑3.0‑only and updated author; adjusted package devDependencies and metadata.types.tsModelId,ModelInfo,ModelsListResponse,ModelCache,AnthropicMessage,AnthropicRequest,AnthropicResponse,GeneratedPrompt,FreewritingPromptsData; changedFreewritingPromptsSettings.modeltoModelId; addedANTHROPIC_MODELSand related type.api/anthropicClient.tsstring; addedfetchModels(),testApiKey(), API key management (updateApiKey,validateApiKey), and helpers for requests, parsing, pagination, dedupe, and error handling.services/modelService.tsModelService+ModelOption: 24‑hour cache, refresh/load/clear, in‑flight dedupe, API-backed fetch with hardcoded fallback, formatting for UI, Notice gating, and cache persistence hooks.services/promptGenerator.tsAnthropicModelwithstring; addedgenerateTimedPrompts/generateNotePrompts, 10‑minute prompt cache,updateApiKey,clearCache, cache keying,anthropicClientgetter, and stricter settings validation (Claude model required).main.tsmodelService: ModelService; load/persistmodelCachewith settings; initialize ModelService; stop/cleanup timed prompts on unload; register commands (timed, note, stop); API-key changes clear model cache; removed oldloadSettings.settings.tshide()lifecycle method, and user Notices for model availability and tests.commands/timedPrompts.ts,commands/notePrompts.tsTimedPromptsCommand: new class for interval sequencing, lifecycle (start/stop/isRunning/getStatus/getRemainingPrompts), concurrency guards.NotePromptsCommand: insert numbered, timestamped prompts into active note with insertion/formatting helpers and editor/view checks..eslintrc,eslint.config.mjs,.eslintignore.eslintrc; addedeslint.config.mjsTypeScript-aware config with explicit ignores and rules;.eslintignoreentries adjusted.package.json(devDeps/metadata)Sequence Diagram(s)
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~60 minutes
Poem
Pre-merge checks and finishing touches
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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
9b8ff3181aand4cb2308bd6.📒 Files selected for processing (2)
api/anthropicClient.ts(8 hunks)commands/timedPrompts.ts(4 hunks)🧰 Additional context used
🧬 Code graph analysis (2)
api/anthropicClient.ts (1)
commands/timedPrompts.ts (1)
🔇 Additional comments (9)
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 helpto get the list of available commands and usage tips.Actionable comments posted: 0
🧹 Nitpick comments (5)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
520ac6e826and20530142e4.📒 Files selected for processing (12)
.github/workflows/release.yml(2 hunks)CHANGELOG.md(4 hunks)README.md(2 hunks)api/anthropicClient.ts(5 hunks)commands/notePrompts.ts(1 hunks)commands/timedPrompts.ts(4 hunks)main.ts(3 hunks)package.json(1 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(4 hunks)settings.ts(5 hunks)types.ts(3 hunks)🔇 Additional comments (25)
@coderabbitai full review
✅ Actions performed
Full review triggered.
Actionable comments posted: 0
🧹 Nitpick comments (7)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
520ac6e826and20530142e4.📒 Files selected for processing (12)
.github/workflows/release.yml(2 hunks)CHANGELOG.md(4 hunks)README.md(2 hunks)api/anthropicClient.ts(5 hunks)commands/notePrompts.ts(1 hunks)commands/timedPrompts.ts(4 hunks)main.ts(3 hunks)package.json(1 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(4 hunks)settings.ts(5 hunks)types.ts(3 hunks)🔇 Additional comments (15)
Actionable comments posted: 0
🧹 Nitpick comments (3)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
20530142e4and6ccfb9e023.📒 Files selected for processing (8)
README.md(3 hunks)api/anthropicClient.ts(6 hunks)commands/timedPrompts.ts(4 hunks)main.ts(2 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(5 hunks)settings.ts(5 hunks)types.ts(3 hunks)🚧 Files skipped from review as they are similar to previous changes (3)
🧰 Additional context used
🧬 Code graph analysis (4)
api/anthropicClient.ts (1)
settings.ts (2)
commands/timedPrompts.ts (2)
services/modelService.ts (2)
🔇 Additional comments (21)
Actionable comments posted: 2
🧹 Nitpick comments (1)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
6ccfb9e023and03d2b1c93d.📒 Files selected for processing (3)
api/anthropicClient.ts(6 hunks)commands/timedPrompts.ts(4 hunks)settings.ts(5 hunks)🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used
🧬 Code graph analysis (2)
settings.ts (2)
api/anthropicClient.ts (1)
🔇 Additional comments (11)
@@ -18,2 +51,4 @@// MARK: - Public Methods/*** Generates writing prompts using the Claude API.⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Pagination is not handled for model listing.
The
ModelsListResponseinterface includeshas_more,first_id, andlast_idfields that indicate pagination support, butfetchModels()only retrieves the first page of results. If Anthropic returns more than one page of models, subsequent pages are silently ignored.Verify whether pagination is needed:
If pagination is required, consider implementing it or documenting the limitation. Otherwise, if all Claude models fit in a single page, add a comment explaining why pagination isn't needed.
🏁 Script executed:
Length of output: 128
I'll verify whether pagination is actually used or documented elsewhere in the codebase.
Length of output: 1321
🏁 Script executed:
Length of output: 2163
🌐 Web query:
💡 Result:
By default the List Models endpoint returns 20 models per page. You can set the query param limit to any integer 1–1000 to change this. Pagination uses before_id / after_id with has_more, first_id and last_id in the response. [1]
Implement pagination in
fetchModels()or document why it's not needed.Verification confirms the issue: The
ModelsListResponseinterface includes pagination fields, but the implementation only retrieves the first page. Anthropic's models API endpoint returns 20 models per page by default, and pagination fields are never used anywhere in the codebase. If Anthropic returns more than 20 models, subsequent pages are silently ignored.Either:
has_more,last_id)🤖 Prompt for AI Agents
✅ Addressed in commits
e96ef65toee7faef@@ -19,0 +44,4 @@* - Actions: Cache clearing and other utility functions** Key UX considerations:* - Model dropdown loads asynchronously to avoid blocking UI⚠️ Potential issue | 🟡 Minor
Consider debouncing or using blur event for model refresh.
Refreshing models on every keystroke while the user types their API key will trigger multiple unnecessary API calls (likely to fail with incomplete keys), degrading UX and potentially hitting rate limits.
Consider one of these approaches:
Option 1: Trigger on blur event
Option 2: Debounce the refresh (requires a debounce utility function)
🤖 Prompt for AI Agents
✅ Addressed in commits
e96ef65toee7faefActionable comments posted: 1
♻️ Duplicate comments (2)
🧹 Nitpick comments (12)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
03d2b1c93dandee7faef92b.📒 Files selected for processing (8)
api/anthropicClient.ts(7 hunks)commands/notePrompts.ts(4 hunks)commands/timedPrompts.ts(4 hunks)main.ts(7 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(6 hunks)settings.ts(4 hunks)types.ts(2 hunks)🧰 Additional context used
🧬 Code graph analysis (7)
api/anthropicClient.ts (1)
settings.ts (3)
commands/timedPrompts.ts (2)
services/modelService.ts (1)
commands/notePrompts.ts (1)
main.ts (3)
services/promptGenerator.ts (2)
🔇 Additional comments (1)
@@ -5,19 +5,73 @@ import { Notice } from 'obsidian';import { PromptGeneratorService } from '../services/promptGenerator';⚠️ Potential issue | 🔴 Critical
Fix inProgress lifecycle to avoid races (stop() resets it).
execute() sets inProgress=true, then stop() immediately flips it back to false. A second execute can slip in while prompts are still generating. Reorder and remove the flag mutation from stop() so inProgress reliably guards concurrent runs.
Also applies to: 101-116
🤖 Prompt for AI Agents
✅ Addressed in commits
da6056bto893aae5Actionable comments posted: 2
♻️ Duplicate comments (1)
🧹 Nitpick comments (18)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
ee7faef92band893aae5bca.⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json📒 Files selected for processing (12)
.eslintignore(0 hunks).eslintrc(0 hunks)api/anthropicClient.ts(8 hunks)commands/notePrompts.ts(4 hunks)commands/timedPrompts.ts(4 hunks)eslint.config.mjs(1 hunks)main.ts(6 hunks)package.json(1 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(7 hunks)settings.ts(4 hunks)types.ts(1 hunks)💤 Files with no reviewable changes (2)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used
🧬 Code graph analysis (7)
main.ts (4)
settings.ts (3)
services/promptGenerator.ts (2)
services/modelService.ts (2)
api/anthropicClient.ts (1)
commands/notePrompts.ts (2)
commands/timedPrompts.ts (2)
@@ -44,3 +97,4 @@max_tokens: maxTokens,messages: [{ role: 'user', content: userMessage }],system: finalSystemPrompt};🛠️ Refactor suggestion | 🟠 Major
Add loop‑safety guard and de‑duplication for models pagination.
Defensive guards prevent runaway loops and duplicate model ids if the API misbehaves or cursors don’t advance.
Apply this diff:
🤖 Prompt for AI Agents
✅ Addressed in commits
afa725dto3f53bb5@@ -62,0 +249,4 @@** If an example prompt is provided, it's included to guide the AI's style.* The message emphasizes the exact output format needed for reliable parsing.*⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Critical: Pagination uses
afterinstead ofafter_id— can cause infinite loop/duplicate pages.Anthropic’s models pagination uses
before_id/after_id. Usingafterlikely re-fetches the first page forever ifhas_moreis true, looping and duplicating results.Apply this diff:
Please confirm param naming against current docs:
🌐 Web query:
💡 Result:
Yes — the List Models endpoint uses the query parameter after_id (not after) for pagination. [1][2]
Sources:
🏁 Script executed:
Length of output: 0
🏁 Script executed:
Length of output: 22
🏁 Script executed:
Length of output: 976
🏁 Script executed:
Length of output: 2700
Critical: Fix pagination parameter from
aftertoafter_idat line 141.Anthropic's List Models endpoint uses the query parameter
after_id(notafter) for pagination. The current code at line 141 uses the incorrect parameter name, which will cause the API to ignore the pagination cursor and potentially loop indefinitely or return duplicate results.📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
afa725dto3f53bb5Actionable comments posted: 0
🧹 Nitpick comments (15)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
893aae5bcaand3f53bb5a30.⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json📒 Files selected for processing (10)
api/anthropicClient.ts(8 hunks)commands/notePrompts.ts(4 hunks)commands/timedPrompts.ts(4 hunks)eslint.config.mjs(1 hunks)main.ts(6 hunks)package.json(1 hunks)services/modelService.ts(1 hunks)services/promptGenerator.ts(7 hunks)settings.ts(7 hunks)types.ts(1 hunks)🚧 Files skipped from review as they are similar to previous changes (2)
🧰 Additional context used
🧬 Code graph analysis (6)
main.ts (4)
api/anthropicClient.ts (1)
commands/notePrompts.ts (2)
commands/timedPrompts.ts (2)
services/modelService.ts (1)
settings.ts (3)
🔇 Additional comments (10)
Actionable comments posted: 1
🧹 Nitpick comments (6)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
3f53bb5a30andd31cec0383.📒 Files selected for processing (6)
api/anthropicClient.ts(8 hunks)commands/notePrompts.ts(4 hunks)commands/timedPrompts.ts(4 hunks)main.ts(6 hunks)services/modelService.ts(1 hunks)settings.ts(7 hunks)🧰 Additional context used
🧬 Code graph analysis (6)
commands/timedPrompts.ts (2)
settings.ts (3)
commands/notePrompts.ts (2)
api/anthropicClient.ts (1)
services/modelService.ts (1)
main.ts (6)
🔇 Additional comments (9)
@@ -74,6 +157,19 @@ export class TimedPromptsCommand {}, delaySeconds * 1000);⚠️ Potential issue | 🟡 Minor
Smoothen notification duration transition at 1-second boundary.
The condition
delayMs > 1000creates a discontinuity:Consider using
>=instead to create a smoother transition:Apply this diff:
With this change:
📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
d5af2a0to9b8ff31Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between
d31cec0383and9b8ff3181a.📒 Files selected for processing (4)
api/anthropicClient.ts(8 hunks)commands/notePrompts.ts(3 hunks)commands/timedPrompts.ts(4 hunks)settings.ts(10 hunks)🧰 Additional context used
🧬 Code graph analysis (4)
api/anthropicClient.ts (1)
commands/timedPrompts.ts (2)
commands/notePrompts.ts (2)
settings.ts (3)
🔇 Additional comments (6)
@@ -50,15 +104,156 @@ export class AnthropicClient {} catch (error) {⚠️ Potential issue | 🟠 Major
Keep pagination metadata in sync after sorting
Sorting the collected models before returning them means the original
first_id/last_idno longer describe the first and last entries indata. Any consumer that trusts those fields for cache validation or pagination deltas will now read inconsistent state. Recompute the IDs from the sorted array (or skip the sort) before returning.📝 Committable suggestion
🤖 Prompt for AI Agents
✅ Addressed in commits
5bf804bto4cb2308⚠️ Potential issue | 🟡 Minor
Update comment to match the code boundary.
The notification duration logic correctly uses
>=(line 185), which addresses the previous review's concern about the 1-second boundary. However, the comment on line 180 still says ">1s" instead of ">=1s".Apply this diff to align the comment with the implementation:
🤖 Prompt for AI Agents
✅ Addressed in commits
5bf804bto4cb2308