Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfacb78da4 | ||
|
|
f2972a5b83 | ||
|
|
7aae6fa45b | ||
|
|
10a4a9f215 | ||
|
|
4cb2308bd6 | ||
|
|
5bf804b266 | ||
|
|
9b8ff3181a | ||
|
|
9ee37cd087 | ||
|
|
bdb4949c1b | ||
|
|
d5af2a08ce | ||
|
|
d31cec0383 | ||
|
|
fc04d3f1af | ||
|
|
fca191b850 | ||
|
|
2b9c8fbc5b | ||
|
|
1c1cba6ce5 | ||
|
|
4c03bed948 | ||
|
|
3f53bb5a30 | ||
|
|
b57fe8cd89 | ||
|
|
902d2b1b9a | ||
|
|
ea14071d22 | ||
|
|
329c12ab4b | ||
|
|
a93c887cad | ||
|
|
8e6441ff7d | ||
|
|
13645af300 | ||
|
|
c9adf05a82 | ||
|
|
afa725df7f | ||
|
|
893aae5bca | ||
|
|
52ea9de4c0 | ||
|
|
53e61abd3b | ||
|
|
61788b39ad | ||
|
|
b76f085137 | ||
|
|
e5c7a523c5 | ||
|
|
cc1b452872 | ||
|
|
c698a19345 | ||
|
|
db641cfe9d | ||
|
|
456a2226ea | ||
|
|
da6056bf0d | ||
|
|
ee7faef92b | ||
|
|
f9fefceac1 | ||
|
|
def8bbcfe5 | ||
|
|
e96ef65200 | ||
|
|
03d2b1c93d | ||
|
|
361f946d87 | ||
|
|
92e109e2e8 | ||
|
|
6ccfb9e023 | ||
|
|
e8443a878d | ||
|
|
e06b07eb26 | ||
|
|
7932663d2a | ||
|
|
435af4ccab | ||
|
|
8e19f6bc8f | ||
|
|
766eb26df3 | ||
|
|
4164471ed0 | ||
|
|
6875a7c06c | ||
|
|
c06afe7a4a | ||
|
|
20530142e4 | ||
|
|
a79dcec18f | ||
|
|
8dc28ccd5e | ||
|
|
f589057912 | ||
|
|
8b0b4f6607 | ||
|
|
b8b701d78b | ||
|
|
d7497c1259 | ||
|
|
9249897d27 | ||
|
|
847768417c | ||
|
|
ac20fadef6 | ||
|
|
520ac6e826 | ||
|
|
5a97bd50a6 | ||
|
|
ac1468c72e | ||
|
|
16901f9ec6 | ||
|
|
383f355e45 | ||
|
|
39c9578ebc | ||
|
|
143097a973 | ||
|
|
4786e7647d | ||
|
|
8147662d61 | ||
|
|
6729851cb4 | ||
|
|
c34ee2edd6 | ||
|
|
2fbe582c4d | ||
|
|
eaab2012db | ||
|
|
49e3f5523c |
No files matched your search
@@ -1,3 +0,0 @@
|
|||||||
node_modules/
|
|
||||||
|
|
||||||
main.js
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{
|
|
||||||
"root": true,
|
|
||||||
"parser": "@typescript-eslint/parser",
|
|
||||||
"env": { "node": true },
|
|
||||||
"plugins": [
|
|
||||||
"@typescript-eslint"
|
|
||||||
],
|
|
||||||
"extends": [
|
|
||||||
"eslint:recommended",
|
|
||||||
"plugin:@typescript-eslint/eslint-recommended",
|
|
||||||
"plugin:@typescript-eslint/recommended"
|
|
||||||
],
|
|
||||||
"parserOptions": {
|
|
||||||
"sourceType": "module"
|
|
||||||
},
|
|
||||||
"rules": {
|
|
||||||
"no-unused-vars": "off",
|
|
||||||
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
|
|
||||||
"@typescript-eslint/ban-ts-comment": "off",
|
|
||||||
"no-prototype-builtins": "off",
|
|
||||||
"@typescript-eslint/no-empty-function": "off"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -108,7 +108,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v2
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
with:
|
||||||
@@ -127,7 +127,7 @@ jobs:
|
|||||||
### BRAT (Beta Reviewer's Auto-update Tool)
|
### BRAT (Beta Reviewer's Auto-update Tool)
|
||||||
|
|
||||||
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
||||||
2. Add this repository: `alexanderkucera/obsidian-freewriting-prompts`
|
2. Add this repository: `AlexKucera/freewriting-prompts`
|
||||||
3. Enable the plugin after installation
|
3. Enable the plugin after installation
|
||||||
|
|
||||||
### Manual Installation
|
### Manual Installation
|
||||||
|
|||||||
+99
-3
@@ -7,7 +7,100 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
## [1.0.0] - 2025-01-20
|
## [1.2.0] - 2025-10-31
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Dynamic model fetching from Anthropic API
|
||||||
|
- Pagination support for Anthropic models API
|
||||||
|
- Fallback for unavailable AI models
|
||||||
|
- User notification for ongoing timed prompts
|
||||||
|
- API key validation and model sorting
|
||||||
|
- Type refinement for dynamic model selection
|
||||||
|
- Required Claude model validation check
|
||||||
|
- Deduplication for concurrent prompt generation
|
||||||
|
- Input constraints to settings numeric fields
|
||||||
|
- Debounce mechanism for API key refresh
|
||||||
|
- DocStrings throughout codebase
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Improves timed prompt notification duration calculation
|
||||||
|
- Enhances model selection and caching in settings
|
||||||
|
- Refactors model fetching with deduplication strategy
|
||||||
|
- Improves model list pagination with safety measures
|
||||||
|
- Refactors Anthropic API client configuration
|
||||||
|
- Optimizes settings handling with debounce and async improvements
|
||||||
|
- Improves timestamp localization for note prompts
|
||||||
|
- Improves data loading with robust error handling
|
||||||
|
- Improves model fetching resilience and performance
|
||||||
|
- Enhances ESLint configuration for TypeScript project
|
||||||
|
- Improves timed prompts command concurrency handling
|
||||||
|
- Improves model fallback and settings handling
|
||||||
|
- Optimizes settings and API key management
|
||||||
|
- Improves Anthropic API client robustness
|
||||||
|
- Extracts note command execute validation logic
|
||||||
|
- Updates ANTHROPIC_MODELS with latest model versions
|
||||||
|
- Updates ESLint configuration to latest standards
|
||||||
|
- Improves prompt insertion logic and timestamp formatting
|
||||||
|
- Improves Anthropic models API response validation
|
||||||
|
- Improves async model loading for settings UI
|
||||||
|
- Optimizes token usage for timed prompts
|
||||||
|
- Improves model selection fallback handling
|
||||||
|
- Simplifies data loading and initialization logic
|
||||||
|
- Improves model fetch error notification message
|
||||||
|
- Simplifies cursor placement after prompt insertion
|
||||||
|
- Updates project license badge to GPL v3
|
||||||
|
- Updates repository URLs and links
|
||||||
|
- Updates author and license info
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Pagination ID consistency in model sorting
|
||||||
|
- Cross-key model cache leakage
|
||||||
|
- Timed prompts generation race condition
|
||||||
|
- Broken links in README
|
||||||
|
- Empty cache arrays guard
|
||||||
|
- Race conditions in timed prompts
|
||||||
|
- Removes unnecessary error notification
|
||||||
|
- Refines notification timing for timed prompts
|
||||||
|
- Sanitizes writing prompts for consistent formatting
|
||||||
|
- Refines timed prompt notification duration logic
|
||||||
|
- Improves ping response validation robustness
|
||||||
|
|
||||||
|
## [1.1.1] - 2025-09-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Plugin combination recommendations for enhanced writing workflow
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Command Naming**: Renamed "Staggered Prompts" to "Timed Prompts" for better clarity
|
||||||
|
- Command now called "Show Timed Prompts" instead of "Show Staggered Prompts"
|
||||||
|
- Settings renamed from "Staggered Count" to "Timed Count"
|
||||||
|
- All user-facing text updated to reflect regular interval timing rather than staggered/irregular timing
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Type Safety**: Improved TypeScript type safety throughout codebase
|
||||||
|
- Replaced `any` types with proper Obsidian API types (App, ButtonComponent)
|
||||||
|
- Added null safety for button text content
|
||||||
|
- Enhanced code quality and maintainability
|
||||||
|
- **Settings UI**: Removed redundant "Settings" text from settings tab heading
|
||||||
|
|
||||||
|
## [1.1.0] - 2025-09-20
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Enhanced Staggered Prompts**: Now generates ultra-short, direct prompts perfect for quick responses (1-5 words or single sentence)
|
||||||
|
- **Improved Timing**: Fixed staggered prompt display timing to prevent notification overlap with smooth fade transitions
|
||||||
|
- **Better Type Safety**: Simplified prompt generation model usage with proper TypeScript typing
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Obsidian Compliance**: Moved inline styles to CSS for better theme compatibility
|
||||||
|
- **Command Naming**: Updated command names to follow Obsidian conventions ("Show Staggered Prompts", "Add Note Prompts")
|
||||||
|
- **Code Quality**: Removed TypeScript type casting issues and improved code structure
|
||||||
|
|
||||||
|
### Technical Details
|
||||||
|
- Type-specific prompt generation (staggered vs note prompts use different instructions)
|
||||||
|
- Dynamic notification duration based on user delay settings
|
||||||
|
- Enhanced Claude model support including latest Opus 4.1 and Sonnet models
|
||||||
|
|
||||||
|
## [1.0.0] - 2025-09-19
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- **Staggered Freewriting Prompts** command for timed writing sessions
|
- **Staggered Freewriting Prompts** command for timed writing sessions
|
||||||
@@ -52,5 +145,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
- Input validation for all user settings
|
- Input validation for all user settings
|
||||||
- Rate limiting awareness with appropriate error handling
|
- Rate limiting awareness with appropriate error handling
|
||||||
|
|
||||||
[Unreleased]: https://github.com/alexanderkucera/obsidian-freewriting-prompts/compare/v1.0.0...HEAD
|
[Unreleased]: https://github.com/AlexKucera/freewriting-prompts/compare/1.2.0...HEAD
|
||||||
[1.0.0]: https://github.com/alexanderkucera/obsidian-freewriting-prompts/releases/tag/v1.0.0
|
[1.2.0]: https://github.com/AlexKucera/freewriting-prompts/compare/1.1.1...1.2.0
|
||||||
|
[1.1.1]: https://github.com/AlexKucera/freewriting-prompts/compare/1.1.0...1.1.1
|
||||||
|
[1.1.0]: https://github.com/AlexKucera/freewriting-prompts/compare/1.0.0...1.1.0
|
||||||
|
[1.0.0]: https://github.com/AlexKucera/freewriting-prompts/releases/tag/1.0.0
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
# Freewriting Prompts
|
# Freewriting Prompts
|
||||||
|
|
||||||
[](https://github.com/alexanderkucera/obsidian-freewriting-prompts/releases)
|
[](https://github.com/AlexKucera/freewriting-prompts/releases)
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||||
|
[](https://github.com/AlexKucera/freewriting-prompts/releases)
|
||||||
|
[](https://coderabbit.ai/)
|
||||||

|

|
||||||
|
|
||||||
Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude. Break through writer's block with creative, thought-provoking prompts delivered exactly when you need them.
|
Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude. Break through writer's block with creative, thought-provoking prompts delivered exactly when you need them.
|
||||||
@@ -21,7 +23,7 @@ Generate AI-powered writing prompts for freewriting sessions using Anthropic's C
|
|||||||
|
|
||||||
## Key Features
|
## Key Features
|
||||||
|
|
||||||
- **🎯 Two Prompt Modes**: Staggered notifications for timed writing sessions, or direct note insertion
|
- **🎯 Two Prompt Modes**: Timed notifications for writing sessions, or direct note insertion
|
||||||
- **🤖 AI-Powered**: Uses Anthropic's Claude models for creative, diverse prompt generation
|
- **🤖 AI-Powered**: Uses Anthropic's Claude models for creative, diverse prompt generation
|
||||||
- **⚡ Customizable Timing**: Configure prompt count and delay intervals for your writing rhythm
|
- **⚡ Customizable Timing**: Configure prompt count and delay intervals for your writing rhythm
|
||||||
- **🎨 Personalized Prompts**: System prompts and examples to match your writing style
|
- **🎨 Personalized Prompts**: System prompts and examples to match your writing style
|
||||||
@@ -41,6 +43,28 @@ Writer's block is real, and sometimes you need external inspiration to get the c
|
|||||||
|
|
||||||
Rather than browsing random prompt websites or books, get personalized, AI-generated prompts delivered right in your writing environment.
|
Rather than browsing random prompt websites or books, get personalized, AI-generated prompts delivered right in your writing environment.
|
||||||
|
|
||||||
|
## Perfect Plugin Combination
|
||||||
|
|
||||||
|
This plugin works exceptionally well with other freewriting tools to create a complete writing workflow:
|
||||||
|
|
||||||
|
### ✍️ [Freewriting Cleanup](https://github.com/AlexKucera/freewriting-cleanup)
|
||||||
|
Transform your messy freewriting into polished prose using AI. Perfect companion to this plugin:
|
||||||
|
1. **Generate inspiration** with creative prompts from this plugin
|
||||||
|
2. **Write freely** without worrying about mistakes
|
||||||
|
3. **Clean up the output** with Freewriting Cleanup to polish your raw writing
|
||||||
|
|
||||||
|
### 📝 [Digital Paper](https://github.com/danferns/digital-paper-obsidian-plugin)
|
||||||
|
Write without the ability to delete or edit - just like pen on paper. Perfect for true freewriting sessions:
|
||||||
|
1. **Enable Digital Paper mode** to disable all delete functions (backspace, delete key, Ctrl+X)
|
||||||
|
2. **Use this plugin** to generate writing prompts for inspiration
|
||||||
|
3. **Write continuously** without stopping to edit or second-guess yourself
|
||||||
|
4. **Clean up afterwards** using Freewriting Cleanup to polish the unedited output
|
||||||
|
|
||||||
|
**Recommended Workflow:**
|
||||||
|
- Generate prompts with this plugin when you need inspiration
|
||||||
|
- Enable Digital Paper mode for uninterrupted freewriting sessions
|
||||||
|
- Use Freewriting Cleanup to polish your raw, unedited writing into readable text
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Method 1: Community Plugin Store (Recommended)
|
### Method 1: Community Plugin Store (Recommended)
|
||||||
@@ -52,7 +76,7 @@ Rather than browsing random prompt websites or books, get personalized, AI-gener
|
|||||||
|
|
||||||
### Method 2: Manual Installation
|
### Method 2: Manual Installation
|
||||||
|
|
||||||
1. Go to [GitHub Releases](https://github.com/alexanderkucera/obsidian-freewriting-prompts/releases)
|
1. Go to [GitHub Releases](https://github.com/AlexKucera/freewriting-prompts/releases)
|
||||||
2. Download the latest `main.js`, `manifest.json`, and `styles.css`
|
2. Download the latest `main.js`, `manifest.json`, and `styles.css`
|
||||||
3. Create a folder `{VaultFolder}/.obsidian/plugins/freewriting-prompts/`
|
3. Create a folder `{VaultFolder}/.obsidian/plugins/freewriting-prompts/`
|
||||||
4. Place the downloaded files in this folder
|
4. Place the downloaded files in this folder
|
||||||
@@ -62,7 +86,7 @@ Rather than browsing random prompt websites or books, get personalized, AI-gener
|
|||||||
### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
|
### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
|
||||||
|
|
||||||
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
||||||
2. Add this repository: `alexanderkucera/obsidian-freewriting-prompts`
|
2. Add this repository: `https://github.com/AlexKucera/freewriting-prompts`
|
||||||
3. Enable the plugin after installation
|
3. Enable the plugin after installation
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
@@ -84,7 +108,7 @@ Rather than browsing random prompt websites or books, get personalized, AI-gener
|
|||||||
### 3. Start Using Prompts
|
### 3. Start Using Prompts
|
||||||
|
|
||||||
**For Timed Writing Sessions:**
|
**For Timed Writing Sessions:**
|
||||||
1. Use `Ctrl/Cmd + P` → "Staggered Freewriting Prompts"
|
1. Use `Ctrl/Cmd + P` → "Show Timed Prompts"
|
||||||
2. Prompts will appear as notifications at your configured intervals
|
2. Prompts will appear as notifications at your configured intervals
|
||||||
|
|
||||||
**For Note Integration:**
|
**For Note Integration:**
|
||||||
@@ -105,19 +129,19 @@ Rather than browsing random prompt websites or books, get personalized, AI-gener
|
|||||||
|
|
||||||
| Setting | Description | Default | Range |
|
| Setting | Description | Default | Range |
|
||||||
|---------|-------------|---------|-------|
|
|---------|-------------|---------|-------|
|
||||||
| **Staggered Count** | Number of timed prompts | 10 | 1-50 |
|
| **Timed Count** | Number of timed prompts | 10 | 1-50 |
|
||||||
| **Delay Seconds** | Seconds between prompts | 6 | 1-300 |
|
| **Delay Seconds** | Seconds between prompts | 6 | 1-300 |
|
||||||
| **Note Count** | Prompts inserted in notes | 3 | 1-20 |
|
| **Note Count** | Prompts inserted in notes | 3 | 1-20 |
|
||||||
|
|
||||||
### Prompt Customization
|
### Prompt Customization
|
||||||
|
|
||||||
- **System Prompt**: Instructions for the AI on how to generate prompts
|
- **System Prompt**: Instructions for the AI on how to generate prompts
|
||||||
- **Staggered Example**: Example prompt for timed sessions
|
- **Timed Example**: Example prompt for timed sessions
|
||||||
- **Freewriting Example**: Example prompt for note insertion
|
- **Freewriting Example**: Example prompt for note insertion
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
### Staggered Freewriting Prompts
|
### Timed Freewriting Prompts
|
||||||
|
|
||||||
Delivers prompts as timed notifications perfect for writing sprints:
|
Delivers prompts as timed notifications perfect for writing sprints:
|
||||||
|
|
||||||
@@ -147,9 +171,9 @@ Inserts prompts directly into your current note:
|
|||||||
- Creating prompt libraries
|
- Creating prompt libraries
|
||||||
- Inspiration gathering
|
- Inspiration gathering
|
||||||
|
|
||||||
### Stop Staggered Prompts
|
### Stop Timed Prompts
|
||||||
|
|
||||||
Cancels any running staggered prompt sequence.
|
Cancels any running timed prompt sequence.
|
||||||
|
|
||||||
## Settings
|
## Settings
|
||||||
|
|
||||||
@@ -202,8 +226,8 @@ The plugin provides detailed error messages for different scenarios:
|
|||||||
|
|
||||||
### Getting Help
|
### Getting Help
|
||||||
|
|
||||||
- **Issues**: Report bugs on [GitHub Issues](https://github.com/alexanderkucera/obsidian-freewriting-prompts/issues)
|
- **Issues**: Report bugs on [GitHub Issues](https://github.com/AlexKucera/freewriting-prompts/issues)
|
||||||
- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/alexanderkucera/obsidian-freewriting-prompts/discussions)
|
- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/AlexKucera/freewriting-prompts/discussions)
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -211,8 +235,8 @@ The plugin provides detailed error messages for different scenarios:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clone the repository
|
# Clone the repository
|
||||||
git clone https://github.com/alexanderkucera/obsidian-freewriting-prompts.git
|
git clone https://github.com/AlexKucera/freewriting-prompts.git
|
||||||
cd obsidian-freewriting-prompts
|
cd freewriting-prompts
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
npm install
|
npm install
|
||||||
@@ -228,7 +252,7 @@ freewriting-prompts/
|
|||||||
├── api/
|
├── api/
|
||||||
│ └── anthropicClient.ts # Anthropic API integration
|
│ └── anthropicClient.ts # Anthropic API integration
|
||||||
├── commands/
|
├── commands/
|
||||||
│ ├── staggeredPrompts.ts # Timed notification prompts
|
│ ├── timedPrompts.ts # Timed notification prompts
|
||||||
│ └── notePrompts.ts # Note insertion prompts
|
│ └── notePrompts.ts # Note insertion prompts
|
||||||
├── services/
|
├── services/
|
||||||
│ └── promptGenerator.ts # Prompt generation service
|
│ └── promptGenerator.ts # Prompt generation service
|
||||||
@@ -260,7 +284,7 @@ Contributions are welcome! Please feel free to submit a Pull Request.
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
This project is licensed under the GNU General Public License v3 (GPLv3) - see the [LICENSE](LICENSE) file for details.
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
|
|||||||
+309
-24
@@ -1,24 +1,79 @@
|
|||||||
// ABOUTME: Anthropic API client for generating writing prompts using Claude
|
// ABOUTME: Anthropic API client for generating writing prompts using Claude
|
||||||
// ABOUTME: Handles API requests, error handling, and response parsing
|
// ABOUTME: Handles API requests, error handling, and response parsing
|
||||||
|
|
||||||
import { Notice, requestUrl } from 'obsidian';
|
import { requestUrl } from 'obsidian';
|
||||||
import { AnthropicRequest, AnthropicResponse, AnthropicModel } from '../types';
|
import { AnthropicRequest, AnthropicResponse, ModelInfo, ModelsListResponse } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client for interacting with the Anthropic API to generate writing prompts.
|
||||||
|
* Handles authentication, request formatting, error handling, and response parsing.
|
||||||
|
*
|
||||||
|
* This client manages two key responsibilities:
|
||||||
|
* 1. Generating writing prompts using the Messages API
|
||||||
|
* 2. Fetching available Claude models using the Models API
|
||||||
|
*
|
||||||
|
* It includes type-specific prompt modifiers to ensure timed prompts are short
|
||||||
|
* and immediate while note prompts can be more elaborate and creative.
|
||||||
|
*/
|
||||||
export class AnthropicClient {
|
export class AnthropicClient {
|
||||||
private apiKey: string;
|
private apiKey: string;
|
||||||
private baseUrl = 'https://api.anthropic.com/v1/messages';
|
/** Anthropic API base URL - centralized to avoid drift */
|
||||||
|
private readonly API_BASE = 'https://api.anthropic.com/v1';
|
||||||
|
/** Anthropic API version - centralized for consistency across all requests */
|
||||||
|
private readonly API_VERSION = '2023-06-01';
|
||||||
|
/** Base URL for the Anthropic Messages API endpoint */
|
||||||
|
private messagesUrl = `${this.API_BASE}/messages`;
|
||||||
|
/** Base URL for the Anthropic Models API endpoint */
|
||||||
|
private modelsUrl = `${this.API_BASE}/models`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suffix appended to all system prompts to enforce consistent output format.
|
||||||
|
* Ensures Claude returns only numbered prompts without additional commentary,
|
||||||
|
* which simplifies parsing and provides a predictable user experience.
|
||||||
|
*/
|
||||||
|
private readonly SYSTEM_PROMPT_SUFFIX = '\n\nIMPORTANT OUTPUT REQUIREMENTS:\n- Return ONLY the numbered writing prompts, nothing else\n- Do not include any explanations, questions, or additional commentary\n- Do not ask if the user wants more prompts or different styles\n- Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Additional instructions for timed prompts to make them extremely brief.
|
||||||
|
* Timed prompts appear as notifications and need to be answerable quickly,
|
||||||
|
* so we enforce a short, concrete style optimized for rapid freewriting.
|
||||||
|
*/
|
||||||
|
private readonly TIMED_PROMPT_MODIFIER = '\n\nFOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT:\n- Each prompt should be answerable in 1-5 words or a single sentence\n- Focus on immediate, concrete observations or quick thoughts\n- Avoid complex scenarios or deep philosophical questions\n- Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft"\n- Keep prompts simple, immediate, and concrete';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new Anthropic API client.
|
||||||
|
* @param apiKey - The Anthropic API key for authentication
|
||||||
|
*/
|
||||||
constructor(apiKey: string) {
|
constructor(apiKey: string) {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates writing prompts using the Claude API.
|
||||||
|
*
|
||||||
|
* This method constructs an appropriate prompt based on the type (timed vs note),
|
||||||
|
* applies relevant system instructions, and parses the response into an array
|
||||||
|
* of clean prompt strings.
|
||||||
|
*
|
||||||
|
* Timed prompts use fewer tokens (256) for faster generation and lower cost,
|
||||||
|
* while note prompts use more tokens (1000) for richer, more elaborate prompts.
|
||||||
|
*
|
||||||
|
* @param count - Number of prompts to generate
|
||||||
|
* @param model - Claude model ID to use (e.g., 'claude-3-5-haiku-latest')
|
||||||
|
* @param systemPrompt - Base system instructions for the AI
|
||||||
|
* @param examplePrompt - Example prompt to guide the style
|
||||||
|
* @param type - Whether this is for 'timed' notifications or 'note' insertion
|
||||||
|
* @returns Array of generated prompt strings
|
||||||
|
* @throws Error if API key is missing or API request fails
|
||||||
|
*/
|
||||||
async generatePrompts(
|
async generatePrompts(
|
||||||
count: number,
|
count: number,
|
||||||
model: AnthropicModel,
|
model: string,
|
||||||
systemPrompt: string,
|
systemPrompt: string,
|
||||||
examplePrompt: string
|
examplePrompt: string,
|
||||||
|
type: 'timed' | 'note'
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
if (!this.apiKey) {
|
if (!this.apiKey) {
|
||||||
throw new Error('API key is required');
|
throw new Error('API key is required');
|
||||||
@@ -26,11 +81,22 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const userMessage = this.createUserMessage(count, examplePrompt);
|
const userMessage = this.createUserMessage(count, examplePrompt);
|
||||||
|
|
||||||
|
// Build system prompt with type-specific modifiers
|
||||||
|
let finalSystemPrompt = systemPrompt;
|
||||||
|
if (type === 'timed') {
|
||||||
|
finalSystemPrompt += this.TIMED_PROMPT_MODIFIER;
|
||||||
|
}
|
||||||
|
finalSystemPrompt += this.SYSTEM_PROMPT_SUFFIX;
|
||||||
|
|
||||||
|
// Use smaller max_tokens for timed prompts to reduce latency/cost
|
||||||
|
const maxTokens = type === 'timed' ? 256 : 1000;
|
||||||
|
|
||||||
const request: AnthropicRequest = {
|
const request: AnthropicRequest = {
|
||||||
model,
|
model,
|
||||||
max_tokens: 1000,
|
max_tokens: maxTokens,
|
||||||
messages: [{ role: 'user', content: userMessage }],
|
messages: [{ role: 'user', content: userMessage }],
|
||||||
system: systemPrompt
|
system: finalSystemPrompt
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await this.makeRequest(request);
|
const response = await this.makeRequest(request);
|
||||||
@@ -38,34 +104,185 @@ export class AnthropicClient {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error generating prompts:', error);
|
console.error('Error generating prompts:', error);
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
new Notice(`Failed to generate prompts: ${error.message}`);
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
throw new Error('Unknown error occurred while generating prompts');
|
throw new Error('Unknown error occurred while generating prompts');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
/**
|
||||||
|
* Fetches the list of available Claude models from the Anthropic API.
|
||||||
private createUserMessage(count: number, examplePrompt: string): string {
|
*
|
||||||
const baseMessage = `Please generate ${count} creative writing prompts.`;
|
* This method implements pagination to ensure all available models are retrieved.
|
||||||
|
* It continues fetching pages while has_more is true, using the after parameter
|
||||||
if (examplePrompt.trim()) {
|
* with the last_id from each response to request subsequent pages.
|
||||||
return `${baseMessage} Here's an example of the style I'm looking for:\n\n"${examplePrompt}"\n\nPlease provide ${count} similar prompts, each on a new line, numbered 1-${count}.`;
|
*
|
||||||
|
* The response is cached by ModelService with a 24-hour TTL.
|
||||||
|
*
|
||||||
|
* @returns Response containing array of all available models with final pagination metadata
|
||||||
|
* @throws Error if API key is missing, request fails, or response is malformed
|
||||||
|
*/
|
||||||
|
async fetchModels(): Promise<ModelsListResponse> {
|
||||||
|
if (!this.apiKey) {
|
||||||
|
throw new Error('API key is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${baseMessage} Please provide ${count} diverse and engaging writing prompts, each on a new line, numbered 1-${count}.`;
|
try {
|
||||||
|
// Accumulate all models across pages
|
||||||
|
const allModels: ModelInfo[] = [];
|
||||||
|
// Track seen model IDs to filter duplicates
|
||||||
|
const seenIds = new Set<string>();
|
||||||
|
let hasMore = true;
|
||||||
|
let afterId: string | undefined = undefined;
|
||||||
|
let firstId = '';
|
||||||
|
let lastId = '';
|
||||||
|
// Loop safety: prevent runaway pagination
|
||||||
|
let iterations = 0;
|
||||||
|
const maxIterations = 1000;
|
||||||
|
|
||||||
|
// Fetch all pages with safety guards
|
||||||
|
while (hasMore) {
|
||||||
|
// Guard against infinite loops
|
||||||
|
iterations++;
|
||||||
|
if (iterations > maxIterations) {
|
||||||
|
throw new Error(`Pagination exceeded maximum iterations (${maxIterations}). Possible API issue.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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()}`;
|
||||||
|
|
||||||
|
const response = await requestUrl({
|
||||||
|
url,
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'x-api-key': this.apiKey,
|
||||||
|
'anthropic-version': this.API_VERSION
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 300) {
|
||||||
|
throw new Error(`Models API request failed: ${response.status}\n${response.text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate basic response structure
|
||||||
|
const data = response.json as unknown;
|
||||||
|
if (!data || typeof data !== 'object' || !('data' in data) || !Array.isArray((data as { data: unknown }).data)) {
|
||||||
|
throw new Error('Invalid models API response structure');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate that each model has required fields
|
||||||
|
const modelsData = (data as { data: unknown[] }).data;
|
||||||
|
if (!modelsData.every((model: unknown) =>
|
||||||
|
model && typeof model === 'object' && 'id' in model && typeof (model as { id: unknown }).id === 'string'
|
||||||
|
)) {
|
||||||
|
throw new Error('Invalid model structure in API response');
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageResponse = data as ModelsListResponse;
|
||||||
|
|
||||||
|
// Accumulate models from this page, filtering out duplicates
|
||||||
|
for (const model of pageResponse.data) {
|
||||||
|
if (!seenIds.has(model.id)) {
|
||||||
|
seenIds.add(model.id);
|
||||||
|
allModels.push(model);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store first_id from the first page
|
||||||
|
if (!firstId) {
|
||||||
|
firstId = pageResponse.first_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update pagination state
|
||||||
|
const previousAfterId: string | undefined = afterId;
|
||||||
|
lastId = pageResponse.last_id;
|
||||||
|
hasMore = pageResponse.has_more;
|
||||||
|
|
||||||
|
// Guard against cursor not advancing (would cause infinite loop)
|
||||||
|
if (!lastId || lastId === previousAfterId) {
|
||||||
|
// Cursor didn't advance - break to prevent infinite loop
|
||||||
|
console.warn('Pagination cursor did not advance. Stopping pagination.');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up for next iteration
|
||||||
|
if (hasMore) {
|
||||||
|
afterId = lastId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort models for stable dropdown UX across sessions/pages
|
||||||
|
const sorted = allModels.slice().sort((a, b) =>
|
||||||
|
(a.display_name ?? a.id).localeCompare(b.display_name ?? b.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Recompute pagination IDs from sorted array to maintain consistency
|
||||||
|
// with returned data (original IDs were from unsorted API responses)
|
||||||
|
const sortedFirstId = sorted.length > 0 ? sorted[0].id : firstId;
|
||||||
|
const sortedLastId = sorted.length > 0 ? sorted[sorted.length - 1].id : lastId;
|
||||||
|
|
||||||
|
// Return combined response with all models
|
||||||
|
return {
|
||||||
|
data: sorted,
|
||||||
|
first_id: sortedFirstId,
|
||||||
|
has_more: false, // We've fetched all pages
|
||||||
|
last_id: sortedLastId
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error(`Network request failed: ${String(error)}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs the user message for prompt generation requests.
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @param count - Number of prompts requested
|
||||||
|
* @param examplePrompt - Optional example to demonstrate desired style
|
||||||
|
* @returns Formatted user message string
|
||||||
|
*/
|
||||||
|
private createUserMessage(count: number, examplePrompt: string): string {
|
||||||
|
const baseMessage = `Generate exactly ${count} creative writing prompts. Return ONLY the numbered prompts with no additional text or commentary.`;
|
||||||
|
|
||||||
|
if (examplePrompt.trim()) {
|
||||||
|
return `${baseMessage}\n\nExample style: "${examplePrompt}"\n\nProvide ${count} similar prompts in this exact format:\n1. [prompt]\n2. [prompt]\n(etc.)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${baseMessage}\n\nProvide ${count} diverse writing prompts in this exact format:\n1. [prompt]\n2. [prompt]\n(etc.)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes an HTTP request to the Anthropic Messages API.
|
||||||
|
*
|
||||||
|
* Handles authentication headers, request serialization, and basic error checking.
|
||||||
|
* Uses Obsidian's requestUrl for compatibility with the plugin environment.
|
||||||
|
*
|
||||||
|
* @param request - Structured request payload for the API
|
||||||
|
* @returns Parsed API response
|
||||||
|
* @throws Error if request fails or returns non-2xx status
|
||||||
|
*/
|
||||||
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
private async makeRequest(request: AnthropicRequest): Promise<AnthropicResponse> {
|
||||||
try {
|
try {
|
||||||
const response = await requestUrl({
|
const response = await requestUrl({
|
||||||
url: this.baseUrl,
|
url: this.messagesUrl,
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'x-api-key': this.apiKey,
|
'x-api-key': this.apiKey,
|
||||||
'anthropic-version': '2023-06-01'
|
'anthropic-version': this.API_VERSION
|
||||||
},
|
},
|
||||||
body: JSON.stringify(request)
|
body: JSON.stringify(request)
|
||||||
});
|
});
|
||||||
@@ -83,12 +300,29 @@ export class AnthropicClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses writing prompts from the API response.
|
||||||
|
*
|
||||||
|
* Extracts text content, splits by newlines, removes numbering prefixes,
|
||||||
|
* and cleans whitespace to produce an array of ready-to-use prompt strings.
|
||||||
|
*
|
||||||
|
* This parsing assumes the AI follows the format specified in SYSTEM_PROMPT_SUFFIX.
|
||||||
|
*
|
||||||
|
* @param response - API response containing generated content
|
||||||
|
* @returns Array of cleaned prompt strings
|
||||||
|
* @throws Error if response is empty or contains no valid prompts
|
||||||
|
*/
|
||||||
private parsePromptsFromResponse(response: AnthropicResponse): string[] {
|
private parsePromptsFromResponse(response: AnthropicResponse): string[] {
|
||||||
if (!response.content || response.content.length === 0) {
|
if (!response.content || response.content.length === 0) {
|
||||||
throw new Error('No content received from API');
|
throw new Error('No content received from API');
|
||||||
}
|
}
|
||||||
|
|
||||||
const text = response.content[0].text;
|
// Parse all text blocks, not just the first one
|
||||||
|
// Anthropic API can return multiple content blocks
|
||||||
|
const text = response.content
|
||||||
|
.filter(c => c && c.type === 'text' && typeof c.text === 'string')
|
||||||
|
.map(c => c.text)
|
||||||
|
.join('\n');
|
||||||
const lines = text.split('\n')
|
const lines = text.split('\n')
|
||||||
.map(line => line.trim())
|
.map(line => line.trim())
|
||||||
.filter(line => line.length > 0);
|
.filter(line => line.length > 0);
|
||||||
@@ -96,8 +330,8 @@ export class AnthropicClient {
|
|||||||
const prompts: string[] = [];
|
const prompts: string[] = [];
|
||||||
|
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
// Remove numbering (1., 2., etc.) and clean up the prompt
|
// Remove list prefixes: numbered (1., 1)), bullets (-, *, •)
|
||||||
const cleaned = line.replace(/^\d+\.\s*/, '').trim();
|
const cleaned = line.replace(/^\s*(?:\d+[.)]|[-*•])\s*/, '').trim();
|
||||||
if (cleaned.length > 0) {
|
if (cleaned.length > 0) {
|
||||||
prompts.push(cleaned);
|
prompts.push(cleaned);
|
||||||
}
|
}
|
||||||
@@ -112,15 +346,40 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
// MARK: - Configuration Methods
|
// MARK: - Configuration Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the API key used for authentication.
|
||||||
|
* Called when the user changes their API key in settings.
|
||||||
|
*
|
||||||
|
* @param apiKey - New Anthropic API key
|
||||||
|
*/
|
||||||
updateApiKey(apiKey: string): void {
|
updateApiKey(apiKey: string): void {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates that an API key is configured and non-empty.
|
||||||
|
*
|
||||||
|
* @returns true if API key exists and has content, false otherwise
|
||||||
|
*/
|
||||||
validateApiKey(): boolean {
|
validateApiKey(): boolean {
|
||||||
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
return !!(this.apiKey && this.apiKey.trim().length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
async testApiKey(model: AnthropicModel): Promise<{
|
/**
|
||||||
|
* Tests the configured API key by making a minimal request to Claude.
|
||||||
|
*
|
||||||
|
* This method sends a simple "ping" request to verify:
|
||||||
|
* - The API key is valid and authorized
|
||||||
|
* - The network connection works
|
||||||
|
* - The selected model is available
|
||||||
|
*
|
||||||
|
* It uses minimal tokens (max_tokens: 10) to keep costs negligible while
|
||||||
|
* still exercising the full authentication and request pipeline.
|
||||||
|
*
|
||||||
|
* @param model - Claude model ID to test with
|
||||||
|
* @returns Detailed test result including success status, timing, and error details
|
||||||
|
*/
|
||||||
|
async testApiKey(model: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
details?: {
|
details?: {
|
||||||
@@ -152,9 +411,24 @@ export class AnthropicClient {
|
|||||||
const response = await this.makeRequest(testRequest);
|
const response = await this.makeRequest(testRequest);
|
||||||
const responseTime = Date.now() - startTime;
|
const responseTime = Date.now() - startTime;
|
||||||
|
|
||||||
|
// Validate that the assistant actually returned "ping"
|
||||||
|
// This ensures the API is working correctly, not just returning a 2xx status
|
||||||
|
// Check all content blocks (not just first) in case of multiple text blocks
|
||||||
|
// Normalize to tolerate punctuation and quotes (e.g., "ping.", ""ping"")
|
||||||
|
const returnedText = (response.content || [])
|
||||||
|
.filter(c => c && c.type === 'text' && typeof c.text === 'string')
|
||||||
|
.map(c => c.text)
|
||||||
|
.join(' ')
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
const normalized = returnedText.replace(/^[^a-z]+|[^a-z]+$/g, '').replace(/\s+/g, '');
|
||||||
|
const isValid = normalized === 'ping';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: isValid,
|
||||||
message: 'API key is valid and working correctly',
|
message: isValid
|
||||||
|
? 'API key is valid and working correctly'
|
||||||
|
: 'API responded but returned unexpected content',
|
||||||
details: {
|
details: {
|
||||||
model: response.model,
|
model: response.model,
|
||||||
responseTime,
|
responseTime,
|
||||||
@@ -169,6 +443,17 @@ export class AnthropicClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses errors from API test attempts into user-friendly messages.
|
||||||
|
*
|
||||||
|
* Categorizes errors by HTTP status code and error type to provide
|
||||||
|
* specific troubleshooting guidance. This helps users quickly identify
|
||||||
|
* whether the issue is with their API key, account, network, or the service.
|
||||||
|
*
|
||||||
|
* @param error - Caught error object (typically an Error instance)
|
||||||
|
* @param responseTime - How long the request took before failing
|
||||||
|
* @returns Structured error result with categorization and guidance
|
||||||
|
*/
|
||||||
private parseTestError(error: unknown, responseTime: number): {
|
private parseTestError(error: unknown, responseTime: number): {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
|
|||||||
+115
-28
@@ -1,21 +1,56 @@
|
|||||||
// ABOUTME: Note prompts command implementation that appends prompts to the current note
|
// ABOUTME: Note prompts command implementation that appends prompts to the current note
|
||||||
// ABOUTME: Handles editor interaction, cursor positioning, and prompt formatting
|
// ABOUTME: Handles editor interaction, cursor positioning, and prompt formatting
|
||||||
|
|
||||||
import { Editor, MarkdownView, Notice } from 'obsidian';
|
import { App, Editor, MarkdownView, Notice } from 'obsidian';
|
||||||
import { PromptGeneratorService } from '../services/promptGenerator';
|
import { PromptGeneratorService } from '../services/promptGenerator';
|
||||||
import { FreewritingPromptsSettings } from '../types';
|
import { FreewritingPromptsSettings } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command handler for inserting writing prompts directly into notes.
|
||||||
|
*
|
||||||
|
* This command generates prompts and inserts them at the cursor position in
|
||||||
|
* the active note as formatted markdown. Unlike timed prompts, these are
|
||||||
|
* persistent and remain in the note for reference.
|
||||||
|
*
|
||||||
|
* Key responsibilities:
|
||||||
|
* - Validates editor and view state before execution
|
||||||
|
* - Generates prompts via the prompt service
|
||||||
|
* - Formats prompts with timestamp and numbering
|
||||||
|
* - Inserts at cursor with intelligent newline handling
|
||||||
|
* - Positions cursor after inserted content
|
||||||
|
*
|
||||||
|
* The formatting includes a timestamp to help users track when prompts were
|
||||||
|
* added, and numbered list format for easy reference.
|
||||||
|
*/
|
||||||
export class NotePromptsCommand {
|
export class NotePromptsCommand {
|
||||||
|
/**
|
||||||
|
* Creates a new note prompts command handler.
|
||||||
|
*
|
||||||
|
* @param promptGenerator - Service for generating prompts from the API
|
||||||
|
*/
|
||||||
constructor(private promptGenerator: PromptGeneratorService) {}
|
constructor(private promptGenerator: PromptGeneratorService) {}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the note prompts insertion.
|
||||||
|
*
|
||||||
|
* This method:
|
||||||
|
* 1. Validates that editor and view are available
|
||||||
|
* 2. Generates prompts through the service
|
||||||
|
* 3. Formats and inserts prompts at the cursor position
|
||||||
|
* 4. Shows success feedback to the user
|
||||||
|
*
|
||||||
|
* @param settings - Current plugin settings for generation parameters
|
||||||
|
* @param editor - Active editor instance for text insertion
|
||||||
|
* @param view - Active markdown view for context
|
||||||
|
*/
|
||||||
async execute(
|
async execute(
|
||||||
settings: FreewritingPromptsSettings,
|
settings: FreewritingPromptsSettings,
|
||||||
editor: Editor,
|
editor: Editor,
|
||||||
view: MarkdownView
|
view: MarkdownView
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (!editor || !view) {
|
if (!NotePromptsCommand.canExecute(editor, view)) {
|
||||||
new Notice('No active note found. Please open a note first.');
|
new Notice('No active note found. Please open a note first.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -42,30 +77,44 @@ export class NotePromptsCommand {
|
|||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts formatted prompts into the note at the cursor position.
|
||||||
|
*
|
||||||
|
* This method handles several edge cases:
|
||||||
|
* - Collapses any text selection before insertion
|
||||||
|
* - Adds newline before if there's text before the cursor
|
||||||
|
* - Adds newline after if there's text after the cursor or more lines below
|
||||||
|
* - Positions cursor at the end of inserted content
|
||||||
|
*
|
||||||
|
* The intelligent newline handling ensures prompts don't run into existing
|
||||||
|
* text and maintains proper spacing in the document.
|
||||||
|
*
|
||||||
|
* @param editor - Editor instance for text manipulation
|
||||||
|
* @param prompts - Array of prompt strings to insert
|
||||||
|
*/
|
||||||
private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
|
private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
|
||||||
const cursor = editor.getCursor();
|
// Normalize to an insertion point (collapse any selection)
|
||||||
const currentLine = editor.getLine(cursor.line);
|
const from = editor.getCursor('from');
|
||||||
|
const to = editor.getCursor('to');
|
||||||
|
const hasSelection = from.line !== to.line || from.ch !== to.ch;
|
||||||
|
if (hasSelection) {
|
||||||
|
editor.setCursor(from);
|
||||||
|
}
|
||||||
|
const cursor = editor.getCursor(); // refreshed after collapse
|
||||||
|
const currentLine = editor.getLine(cursor.line) ?? '';
|
||||||
|
|
||||||
// Determine if we need to add a newline before our content
|
const hasTextBefore = cursor.ch > 0 && currentLine.slice(0, cursor.ch).trim().length > 0;
|
||||||
const needsNewlineBefore = currentLine.trim().length > 0;
|
const hasTextAfter = cursor.ch < currentLine.length && currentLine.slice(cursor.ch).trim().length > 0;
|
||||||
|
|
||||||
// Format the prompts
|
// Format the prompts
|
||||||
const formattedPrompts = this.formatPrompts(prompts);
|
const formattedPrompts = this.formatPrompts(prompts);
|
||||||
|
|
||||||
// Prepare the content to insert
|
// 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();
|
const lastLine = editor.lastLine();
|
||||||
if (cursor.line < lastLine) {
|
let contentToInsert = '';
|
||||||
contentToInsert += '\n';
|
if (hasTextBefore) contentToInsert += '\n';
|
||||||
}
|
contentToInsert += formattedPrompts;
|
||||||
|
if (hasTextAfter || cursor.line < lastLine) contentToInsert += '\n';
|
||||||
|
|
||||||
// Insert the content at the cursor position
|
// Insert the content at the cursor position
|
||||||
editor.replaceSelection(contentToInsert);
|
editor.replaceSelection(contentToInsert);
|
||||||
@@ -75,27 +124,44 @@ export class NotePromptsCommand {
|
|||||||
const newCursorLine = cursor.line + lines.length - 1;
|
const newCursorLine = cursor.line + lines.length - 1;
|
||||||
const newCursorCh = lines[lines.length - 1].length;
|
const newCursorCh = lines[lines.length - 1].length;
|
||||||
|
|
||||||
if (cursor.line === lastLine && !needsNewlineBefore) {
|
editor.setCursor(newCursorLine, newCursorCh);
|
||||||
// If we were at the last line and didn't add a newline before, adjust
|
|
||||||
editor.setCursor(cursor.line, cursor.ch + contentToInsert.length);
|
|
||||||
} else {
|
|
||||||
editor.setCursor(newCursorLine, newCursorCh);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats prompts as markdown with timestamp header and numbered list.
|
||||||
|
*
|
||||||
|
* The format is:
|
||||||
|
* ```
|
||||||
|
* ## Writing Prompts (Jan 15, 2025, 02:30 PM)
|
||||||
|
*
|
||||||
|
* 1. [First prompt]
|
||||||
|
*
|
||||||
|
* 2. [Second prompt]
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* The timestamp helps users track when prompts were generated, and the
|
||||||
|
* numbered list makes it easy to reference specific prompts.
|
||||||
|
*
|
||||||
|
* @param prompts - Array of prompt strings to format
|
||||||
|
* @returns Formatted markdown string ready for insertion
|
||||||
|
*/
|
||||||
private formatPrompts(prompts: string[]): string {
|
private formatPrompts(prompts: string[]): string {
|
||||||
const timestamp = new Date().toLocaleDateString('en-US', {
|
// Let Intl pick the default environment locale automatically
|
||||||
|
const timestamp = new Intl.DateTimeFormat(undefined, {
|
||||||
year: 'numeric',
|
year: 'numeric',
|
||||||
month: 'short',
|
month: 'short',
|
||||||
day: 'numeric',
|
day: 'numeric',
|
||||||
hour: '2-digit',
|
hour: '2-digit',
|
||||||
minute: '2-digit'
|
minute: '2-digit'
|
||||||
});
|
}).format(new Date());
|
||||||
|
|
||||||
let formatted = `## Writing Prompts (${timestamp})\n\n`;
|
let formatted = `## Writing Prompts (${timestamp})\n\n`;
|
||||||
|
|
||||||
prompts.forEach((prompt, index) => {
|
prompts.forEach((prompt, index) => {
|
||||||
formatted += `${index + 1}. ${prompt}\n\n`;
|
// Sanitize to single line: collapse whitespace and trim
|
||||||
|
// Prevents malformed prompts with newlines from breaking list formatting
|
||||||
|
const oneLine = String(prompt).replace(/\s+/g, ' ').trim();
|
||||||
|
formatted += `${index + 1}. ${oneLine}\n\n`;
|
||||||
});
|
});
|
||||||
|
|
||||||
return formatted;
|
return formatted;
|
||||||
@@ -103,11 +169,32 @@ export class NotePromptsCommand {
|
|||||||
|
|
||||||
// MARK: - Utility Methods
|
// MARK: - Utility Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the command can be executed in the current context.
|
||||||
|
*
|
||||||
|
* Validates that:
|
||||||
|
* - Editor instance exists
|
||||||
|
* - Markdown view exists
|
||||||
|
* - An actual file is open (not just an empty pane)
|
||||||
|
*
|
||||||
|
* @param editor - Editor instance to validate
|
||||||
|
* @param view - Markdown view to validate
|
||||||
|
* @returns true if command can execute, false otherwise
|
||||||
|
*/
|
||||||
static canExecute(editor: Editor, view: MarkdownView): boolean {
|
static canExecute(editor: Editor, view: MarkdownView): boolean {
|
||||||
return !!(editor && view && view.file);
|
return !!(editor && view && view.file);
|
||||||
}
|
}
|
||||||
|
|
||||||
static getExecutionContext(app: any): { editor: Editor | null; view: MarkdownView | null } {
|
/**
|
||||||
|
* Retrieves the current execution context from the app.
|
||||||
|
*
|
||||||
|
* Helper method for getting the active editor and view without having
|
||||||
|
* them explicitly passed. Useful for manual command invocation.
|
||||||
|
*
|
||||||
|
* @param app - Obsidian app instance
|
||||||
|
* @returns Object containing editor and view, or nulls if not available
|
||||||
|
*/
|
||||||
|
static getExecutionContext(app: App): { editor: Editor | null; view: MarkdownView | null } {
|
||||||
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
|
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
|
||||||
|
|
||||||
if (!activeView) {
|
if (!activeView) {
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
// ABOUTME: Staggered prompts command implementation that shows prompts as timed notifications
|
|
||||||
// ABOUTME: Manages interval-based prompt display with proper cleanup and error handling
|
|
||||||
|
|
||||||
import { Notice } from 'obsidian';
|
|
||||||
import { PromptGeneratorService } from '../services/promptGenerator';
|
|
||||||
import { FreewritingPromptsSettings } from '../types';
|
|
||||||
|
|
||||||
export class StaggeredPromptsCommand {
|
|
||||||
private activeInterval: number | null = null;
|
|
||||||
private promptQueue: string[] = [];
|
|
||||||
private currentIndex = 0;
|
|
||||||
|
|
||||||
constructor(private promptGenerator: PromptGeneratorService) {}
|
|
||||||
|
|
||||||
// MARK: - Public Methods
|
|
||||||
|
|
||||||
async execute(settings: FreewritingPromptsSettings): Promise<void> {
|
|
||||||
// Stop any existing staggered sequence
|
|
||||||
this.stop();
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Generate prompts
|
|
||||||
const prompts = await this.promptGenerator.generateStaggeredPrompts(settings);
|
|
||||||
|
|
||||||
if (prompts.length === 0) {
|
|
||||||
new Notice('No prompts were generated');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize the prompt queue
|
|
||||||
this.promptQueue = prompts;
|
|
||||||
this.currentIndex = 0;
|
|
||||||
|
|
||||||
// Show the first prompt immediately
|
|
||||||
this.showCurrentPrompt();
|
|
||||||
|
|
||||||
// If there are more prompts, start the interval
|
|
||||||
if (prompts.length > 1) {
|
|
||||||
this.startInterval(settings.delaySeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error executing staggered prompts command:', error);
|
|
||||||
// Error handling is done in the service layer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stop(): void {
|
|
||||||
if (this.activeInterval !== null) {
|
|
||||||
clearInterval(this.activeInterval);
|
|
||||||
this.activeInterval = null;
|
|
||||||
}
|
|
||||||
this.promptQueue = [];
|
|
||||||
this.currentIndex = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
isRunning(): boolean {
|
|
||||||
return this.activeInterval !== null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Private Methods
|
|
||||||
|
|
||||||
private startInterval(delaySeconds: number): void {
|
|
||||||
this.activeInterval = window.setInterval(() => {
|
|
||||||
this.currentIndex++;
|
|
||||||
|
|
||||||
if (this.currentIndex < this.promptQueue.length) {
|
|
||||||
this.showCurrentPrompt();
|
|
||||||
} else {
|
|
||||||
// We've shown all prompts, stop the interval
|
|
||||||
this.stop();
|
|
||||||
new Notice('All prompts have been shown');
|
|
||||||
}
|
|
||||||
}, delaySeconds * 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
private showCurrentPrompt(): void {
|
|
||||||
if (this.currentIndex < this.promptQueue.length) {
|
|
||||||
const prompt = this.promptQueue[this.currentIndex];
|
|
||||||
const promptNumber = this.currentIndex + 1;
|
|
||||||
const totalPrompts = this.promptQueue.length;
|
|
||||||
|
|
||||||
// Create a longer-lasting notice for the prompt
|
|
||||||
const notice = new Notice(
|
|
||||||
`Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`,
|
|
||||||
8000 // Show for 8 seconds
|
|
||||||
);
|
|
||||||
|
|
||||||
// Add some styling to make it more prominent
|
|
||||||
const noticeEl = notice.noticeEl;
|
|
||||||
if (noticeEl) {
|
|
||||||
noticeEl.style.maxWidth = '400px';
|
|
||||||
noticeEl.style.whiteSpace = 'pre-wrap';
|
|
||||||
noticeEl.style.fontSize = '14px';
|
|
||||||
noticeEl.style.lineHeight = '1.4';
|
|
||||||
noticeEl.addClass('freewriting-prompt-notice');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Status Methods
|
|
||||||
|
|
||||||
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
|
||||||
return {
|
|
||||||
isRunning: this.isRunning(),
|
|
||||||
currentPrompt: this.currentIndex + 1,
|
|
||||||
totalPrompts: this.promptQueue.length
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
getRemainingPrompts(): string[] {
|
|
||||||
if (this.currentIndex >= this.promptQueue.length) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
return this.promptQueue.slice(this.currentIndex + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
// ABOUTME: Timed prompts command implementation that shows prompts as timed notifications
|
||||||
|
// ABOUTME: Manages interval-based prompt display with proper cleanup and error handling
|
||||||
|
|
||||||
|
import { Notice } from 'obsidian';
|
||||||
|
import { PromptGeneratorService } from '../services/promptGenerator';
|
||||||
|
import { FreewritingPromptsSettings } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command handler for displaying timed writing prompts as notifications.
|
||||||
|
*
|
||||||
|
* This command manages a sequence of prompts shown at regular intervals, useful
|
||||||
|
* for freewriting sessions where the writer wants periodic prompts to maintain
|
||||||
|
* creative flow.
|
||||||
|
*
|
||||||
|
* Key responsibilities:
|
||||||
|
* - Generates a queue of prompts upfront (prevents race conditions)
|
||||||
|
* - Displays prompts as timed Obsidian notifications
|
||||||
|
* - Manages window.setInterval for timed display
|
||||||
|
* - Prevents concurrent executions with inProgress flag
|
||||||
|
* - Provides proper cleanup to prevent memory leaks
|
||||||
|
*
|
||||||
|
* The notification duration is calibrated to avoid overlap - each notification
|
||||||
|
* disappears 500ms before the next one appears for a clean transition.
|
||||||
|
*/
|
||||||
|
export class TimedPromptsCommand {
|
||||||
|
/** Active interval ID from window.setInterval, null when not running */
|
||||||
|
private activeInterval: number | null = null;
|
||||||
|
/** Queue of prompts to display, loaded at command start */
|
||||||
|
private promptQueue: string[] = [];
|
||||||
|
/** Index of the currently displayed or next-to-display prompt */
|
||||||
|
private currentIndex = 0;
|
||||||
|
/** Flag preventing concurrent command execution */
|
||||||
|
private inProgress = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new timed prompts command handler.
|
||||||
|
*
|
||||||
|
* @param promptGenerator - Service for generating prompts from the API
|
||||||
|
*/
|
||||||
|
constructor(private promptGenerator: PromptGeneratorService) {}
|
||||||
|
|
||||||
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the timed prompts sequence.
|
||||||
|
*
|
||||||
|
* This method:
|
||||||
|
* 1. Prevents race conditions by checking inProgress flag
|
||||||
|
* 2. Stops any existing timed sequence
|
||||||
|
* 3. Generates all prompts upfront to avoid async issues during intervals
|
||||||
|
* 4. Shows the first prompt immediately
|
||||||
|
* 5. Starts an interval to show remaining prompts
|
||||||
|
*
|
||||||
|
* The inProgress flag prevents concurrent executions during async prompt
|
||||||
|
* generation. It's set to true before any async work begins and reset to
|
||||||
|
* false in the finally block after all work completes, ensuring reliable
|
||||||
|
* concurrency protection.
|
||||||
|
*
|
||||||
|
* @param settings - Current plugin settings for generation parameters
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set flag BEFORE any async work to prevent concurrent execution
|
||||||
|
this.inProgress = true;
|
||||||
|
|
||||||
|
// Stop any existing timed sequence (does NOT reset inProgress)
|
||||||
|
this.stop();
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Generate prompts
|
||||||
|
const prompts = await this.promptGenerator.generateTimedPrompts(settings);
|
||||||
|
|
||||||
|
if (prompts.length === 0) {
|
||||||
|
new Notice('No prompts were generated');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize the prompt queue
|
||||||
|
this.promptQueue = prompts;
|
||||||
|
this.currentIndex = 0;
|
||||||
|
|
||||||
|
// Show the first prompt immediately
|
||||||
|
this.showCurrentPrompt(settings.delaySeconds);
|
||||||
|
|
||||||
|
// If there are more prompts, start the interval
|
||||||
|
if (prompts.length > 1) {
|
||||||
|
this.startInterval(settings.delaySeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error executing timed prompts command:', error);
|
||||||
|
// Error handling is done in the service layer
|
||||||
|
} finally {
|
||||||
|
// Reset flag after all work completes (success or failure)
|
||||||
|
// This ensures the flag is always reset and prevents stuck state
|
||||||
|
this.inProgress = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the currently running timed prompts sequence.
|
||||||
|
*
|
||||||
|
* Cleans up the interval timer and resets all state. This is important
|
||||||
|
* for preventing memory leaks and ensuring the next execution starts fresh.
|
||||||
|
* Safe to call even when no sequence is running.
|
||||||
|
*
|
||||||
|
* Note: Does NOT reset inProgress flag - that's managed by execute() to
|
||||||
|
* prevent race conditions during async prompt generation.
|
||||||
|
*/
|
||||||
|
stop(): void {
|
||||||
|
if (this.activeInterval !== null) {
|
||||||
|
clearInterval(this.activeInterval);
|
||||||
|
this.activeInterval = null;
|
||||||
|
}
|
||||||
|
this.promptQueue = [];
|
||||||
|
this.currentIndex = 0;
|
||||||
|
// inProgress is NOT reset here - only execute() manages this flag
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a timed prompts sequence is currently running.
|
||||||
|
*
|
||||||
|
* @returns true if prompts are being displayed on an interval, false otherwise
|
||||||
|
*/
|
||||||
|
isRunning(): boolean {
|
||||||
|
return this.activeInterval !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the interval timer for displaying subsequent prompts.
|
||||||
|
*
|
||||||
|
* The timer increments the current index and displays the next prompt
|
||||||
|
* until the queue is exhausted. Automatically stops and shows a completion
|
||||||
|
* notice when all prompts have been displayed.
|
||||||
|
*
|
||||||
|
* @param delaySeconds - Seconds to wait between each prompt display
|
||||||
|
*/
|
||||||
|
private startInterval(delaySeconds: number): void {
|
||||||
|
this.activeInterval = window.setInterval(() => {
|
||||||
|
this.currentIndex++;
|
||||||
|
|
||||||
|
if (this.currentIndex < this.promptQueue.length) {
|
||||||
|
this.showCurrentPrompt(delaySeconds);
|
||||||
|
} else {
|
||||||
|
// We've shown all prompts, stop the interval
|
||||||
|
this.stop();
|
||||||
|
new Notice('All prompts have been shown');
|
||||||
|
}
|
||||||
|
}, delaySeconds * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the current prompt as an Obsidian notice.
|
||||||
|
*
|
||||||
|
* The notification includes:
|
||||||
|
* - Current position in sequence (e.g., "3/10")
|
||||||
|
* - The prompt text
|
||||||
|
* - Custom CSS class for potential styling
|
||||||
|
*
|
||||||
|
* Notification duration is calibrated to avoid overlap with the next prompt,
|
||||||
|
* disappearing 500ms before the next one arrives for smooth transitions.
|
||||||
|
*
|
||||||
|
* @param delaySeconds - Delay setting used to calculate notification duration
|
||||||
|
*/
|
||||||
|
private showCurrentPrompt(delaySeconds: number): void {
|
||||||
|
if (this.currentIndex < this.promptQueue.length) {
|
||||||
|
const prompt = this.promptQueue[this.currentIndex];
|
||||||
|
const promptNumber = this.currentIndex + 1;
|
||||||
|
const totalPrompts = this.promptQueue.length;
|
||||||
|
|
||||||
|
// Calculate notification duration: slightly less than delay to avoid overlap
|
||||||
|
// For delays >=1s, end 500ms before next tick
|
||||||
|
// For 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));
|
||||||
|
|
||||||
|
const notice = new Notice(
|
||||||
|
`Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`,
|
||||||
|
notificationDuration
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add CSS class for styling
|
||||||
|
const noticeEl = notice.messageEl;
|
||||||
|
if (noticeEl) {
|
||||||
|
noticeEl.addClass('freewriting-prompt-notice');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Status Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the current status of the timed prompts sequence.
|
||||||
|
*
|
||||||
|
* Provides information for UI feedback (like status bar displays) about
|
||||||
|
* the current state of the prompt sequence.
|
||||||
|
*
|
||||||
|
* @returns Object containing running state and progress information
|
||||||
|
*/
|
||||||
|
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
||||||
|
const totalPrompts = this.promptQueue.length;
|
||||||
|
const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isRunning: this.isRunning(),
|
||||||
|
currentPrompt,
|
||||||
|
totalPrompts
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the prompts that haven't been displayed yet.
|
||||||
|
*
|
||||||
|
* Useful for debugging or if users want to preview upcoming prompts.
|
||||||
|
*
|
||||||
|
* @returns Array of remaining prompt strings, empty if sequence is complete
|
||||||
|
*/
|
||||||
|
getRemainingPrompts(): string[] {
|
||||||
|
if (this.currentIndex >= this.promptQueue.length) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return this.promptQueue.slice(this.currentIndex + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import globals from 'globals';
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
// Ignore patterns (replaces .eslintignore)
|
||||||
|
{
|
||||||
|
ignores: [
|
||||||
|
'node_modules/**',
|
||||||
|
'main.js',
|
||||||
|
'dist/**',
|
||||||
|
'*.config.js',
|
||||||
|
'*.config.mjs'
|
||||||
|
]
|
||||||
|
},
|
||||||
|
// Base ESLint recommended rules
|
||||||
|
eslint.configs.recommended,
|
||||||
|
// TypeScript ESLint recommended rules
|
||||||
|
...tseslint.configs.recommended,
|
||||||
|
// Type-aware rules (requires tsconfig.json)
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Project-specific configuration
|
||||||
|
{
|
||||||
|
files: ['**/*.ts'],
|
||||||
|
languageOptions: {
|
||||||
|
parser: tseslint.parser,
|
||||||
|
parserOptions: {
|
||||||
|
sourceType: 'module',
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
project: ['./tsconfig.json']
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.browser
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'@typescript-eslint': tseslint.plugin
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
// Disable base rule in favor of TypeScript version
|
||||||
|
'no-unused-vars': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
|
||||||
|
'@typescript-eslint/ban-ts-comment': 'off',
|
||||||
|
'no-prototype-builtins': 'off',
|
||||||
|
'@typescript-eslint/no-empty-function': 'off'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -2,26 +2,88 @@
|
|||||||
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle
|
||||||
|
|
||||||
import { Editor, MarkdownView, Notice, Plugin } from 'obsidian';
|
import { Editor, MarkdownView, Notice, Plugin } from 'obsidian';
|
||||||
import { FreewritingPromptsSettings } from './types';
|
import { FreewritingPromptsSettings, FreewritingPromptsData, ModelCache } from './types';
|
||||||
import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings';
|
import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings';
|
||||||
import { PromptGeneratorService } from './services/promptGenerator';
|
import { PromptGeneratorService } from './services/promptGenerator';
|
||||||
import { StaggeredPromptsCommand } from './commands/staggeredPrompts';
|
import { ModelService } from './services/modelService';
|
||||||
|
import { TimedPromptsCommand } from './commands/timedPrompts';
|
||||||
import { NotePromptsCommand } from './commands/notePrompts';
|
import { NotePromptsCommand } from './commands/notePrompts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main plugin class for Freewriting Prompts.
|
||||||
|
*
|
||||||
|
* This plugin helps writers overcome creative blocks by generating AI-powered
|
||||||
|
* writing prompts using Claude. It provides two main features:
|
||||||
|
* 1. Timed prompts: Shows prompts as notifications at regular intervals
|
||||||
|
* 2. Note prompts: Inserts prompts directly into the current note
|
||||||
|
*
|
||||||
|
* Architecture:
|
||||||
|
* - Services: Core business logic (prompt generation, model management)
|
||||||
|
* - Commands: User-facing actions (timed prompts, note prompts)
|
||||||
|
* - API Client: Low-level Anthropic API communication
|
||||||
|
* - Settings: User configuration UI and persistence
|
||||||
|
*
|
||||||
|
* The plugin manages the full lifecycle including initialization, cleanup,
|
||||||
|
* settings persistence (including model cache), and command registration.
|
||||||
|
*/
|
||||||
export default class FreewritingPromptsPlugin extends Plugin {
|
export default class FreewritingPromptsPlugin extends Plugin {
|
||||||
|
/** Current plugin settings */
|
||||||
settings: FreewritingPromptsSettings;
|
settings: FreewritingPromptsSettings;
|
||||||
|
/** Service for generating writing prompts */
|
||||||
promptGenerator: PromptGeneratorService;
|
promptGenerator: PromptGeneratorService;
|
||||||
staggeredCommand: StaggeredPromptsCommand;
|
/** Service for managing available Claude models */
|
||||||
|
modelService: ModelService;
|
||||||
|
/** Command handler for timed prompt notifications */
|
||||||
|
timedCommand: TimedPromptsCommand;
|
||||||
|
/** Command handler for note prompt insertion */
|
||||||
noteCommand: NotePromptsCommand;
|
noteCommand: NotePromptsCommand;
|
||||||
|
/** Tracks last saved API key to avoid unnecessary cache clears */
|
||||||
|
private lastApiKey?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when the plugin loads.
|
||||||
|
*
|
||||||
|
* Initializes all services and commands, loads settings and model cache
|
||||||
|
* from disk, and registers commands with Obsidian. This method ensures
|
||||||
|
* the model cache is loaded before ModelService tries to use it, avoiding
|
||||||
|
* an unnecessary API call on startup.
|
||||||
|
*/
|
||||||
async onload() {
|
async onload() {
|
||||||
await this.loadSettings();
|
// Load data once and use it for both settings and model cache
|
||||||
|
// Guard against corrupted persisted data to prevent plugin load failure
|
||||||
|
let modelCache: ModelCache | undefined;
|
||||||
|
try {
|
||||||
|
const data = await this.loadData() as FreewritingPromptsData | null;
|
||||||
|
if (data) {
|
||||||
|
// Destructure to prevent modelCache from being merged into settings (type drift)
|
||||||
|
const { modelCache: cache, ...savedSettings } = data;
|
||||||
|
modelCache = cache;
|
||||||
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings);
|
||||||
|
} else {
|
||||||
|
// No data loaded, use defaults
|
||||||
|
this.settings = { ...DEFAULT_SETTINGS };
|
||||||
|
modelCache = undefined;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load settings; using defaults.', error);
|
||||||
|
this.settings = { ...DEFAULT_SETTINGS };
|
||||||
|
modelCache = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track initial API key to detect changes on save
|
||||||
|
this.lastApiKey = this.settings.apiKey;
|
||||||
|
|
||||||
// Initialize services
|
// Initialize services
|
||||||
this.promptGenerator = new PromptGeneratorService(this.settings);
|
this.promptGenerator = new PromptGeneratorService(this.settings);
|
||||||
this.staggeredCommand = new StaggeredPromptsCommand(this.promptGenerator);
|
this.modelService = new ModelService(this.promptGenerator.anthropicClient);
|
||||||
|
this.timedCommand = new TimedPromptsCommand(this.promptGenerator);
|
||||||
this.noteCommand = new NotePromptsCommand(this.promptGenerator);
|
this.noteCommand = new NotePromptsCommand(this.promptGenerator);
|
||||||
|
|
||||||
|
// Load model cache
|
||||||
|
if (modelCache) {
|
||||||
|
this.modelService.loadCache(modelCache);
|
||||||
|
}
|
||||||
|
|
||||||
// Register commands
|
// Register commands
|
||||||
this.registerCommands();
|
this.registerCommands();
|
||||||
|
|
||||||
@@ -29,10 +91,20 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
this.addSettingTab(new FreewritingPromptsSettingTab(this.app, this));
|
this.addSettingTab(new FreewritingPromptsSettingTab(this.app, this));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when the plugin unloads.
|
||||||
|
*
|
||||||
|
* Performs cleanup to prevent memory leaks and ensure proper state:
|
||||||
|
* - Stops any running timed prompts (clears intervals)
|
||||||
|
* - Clears the in-memory prompt cache
|
||||||
|
*
|
||||||
|
* Model cache is NOT cleared here because it's persisted to disk and
|
||||||
|
* should be available on next load.
|
||||||
|
*/
|
||||||
onunload() {
|
onunload() {
|
||||||
// Stop any running staggered prompts
|
// Stop any running timed prompts
|
||||||
if (this.staggeredCommand) {
|
if (this.timedCommand) {
|
||||||
this.staggeredCommand.stop();
|
this.timedCommand.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear prompt cache
|
// Clear prompt cache
|
||||||
@@ -43,56 +115,90 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Settings Management
|
// MARK: - Settings Management
|
||||||
|
|
||||||
async loadSettings() {
|
/**
|
||||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
* Saves plugin settings to disk.
|
||||||
}
|
*
|
||||||
|
* Includes both user settings and the model cache to avoid re-fetching
|
||||||
|
* models on every startup. Updates the prompt generator with the new API
|
||||||
|
* key if it changed.
|
||||||
|
*/
|
||||||
async saveSettings() {
|
async saveSettings() {
|
||||||
await this.saveData(this.settings);
|
// Save settings with model cache
|
||||||
|
const data: FreewritingPromptsData = {
|
||||||
|
...this.settings,
|
||||||
|
modelCache: this.modelService?.getCache() || undefined
|
||||||
|
};
|
||||||
|
await this.saveData(data);
|
||||||
|
|
||||||
// Update the prompt generator with new settings
|
// Update the prompt generator only if API key actually changed
|
||||||
if (this.promptGenerator) {
|
// This avoids clearing the prompt cache unnecessarily on every save
|
||||||
|
if (this.promptGenerator && this.lastApiKey !== this.settings.apiKey) {
|
||||||
this.promptGenerator.updateApiKey(this.settings.apiKey);
|
this.promptGenerator.updateApiKey(this.settings.apiKey);
|
||||||
|
this.lastApiKey = this.settings.apiKey;
|
||||||
|
// Clear model cache to ensure model list reflects new account entitlements
|
||||||
|
// This prevents cross-key cache leakage if settings are changed programmatically
|
||||||
|
this.modelService?.clearCache();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Command Registration
|
// MARK: - Command Registration
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers all plugin commands with Obsidian.
|
||||||
|
*
|
||||||
|
* Three commands are registered:
|
||||||
|
* 1. 'timed-prompts': Starts a timed prompt sequence
|
||||||
|
* 2. 'note-prompts': Inserts prompts into the current note
|
||||||
|
* 3. 'stop-timed-prompts': Stops the active timed sequence
|
||||||
|
*
|
||||||
|
* Commands are available in the command palette and can be bound to hotkeys.
|
||||||
|
*/
|
||||||
private registerCommands() {
|
private registerCommands() {
|
||||||
// Staggered Freewriting Prompts command
|
// Timed prompts command
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
id: 'staggered-freewriting-prompts',
|
id: 'timed-prompts',
|
||||||
name: 'Staggered Freewriting Prompts',
|
name: 'Show timed prompts',
|
||||||
callback: async () => {
|
callback: async () => {
|
||||||
await this.executeStaggeredPrompts();
|
await this.executeTimedPrompts();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Freewriting Prompt command (editor-based)
|
// Note prompt command (editor-based)
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
id: 'freewriting-prompt',
|
id: 'note-prompts',
|
||||||
name: 'Freewriting Prompt',
|
name: 'Add note prompts',
|
||||||
editorCallback: async (editor: Editor, view: MarkdownView) => {
|
editorCallback: async (editor: Editor, view: MarkdownView) => {
|
||||||
await this.executeNotePrompts(editor, view);
|
await this.executeNotePrompts(editor, view);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Stop staggered prompts command
|
// Stop timed prompts command
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
id: 'stop-staggered-prompts',
|
id: 'stop-timed-prompts',
|
||||||
name: 'Stop Staggered Prompts',
|
name: 'Stop timed prompts',
|
||||||
callback: () => {
|
callback: () => {
|
||||||
this.stopStaggeredPrompts();
|
this.stopTimedPrompts();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Command Implementations
|
// MARK: - Command Implementations
|
||||||
|
|
||||||
private async executeStaggeredPrompts(): Promise<void> {
|
/**
|
||||||
// Check if staggered prompts are already running
|
* Executes the timed prompts command.
|
||||||
if (this.staggeredCommand.isRunning()) {
|
*
|
||||||
new Notice('Staggered prompts are already running. Use "Stop Staggered Prompts" to stop them first.');
|
* This method:
|
||||||
|
* 1. Checks if timed prompts are already running
|
||||||
|
* 2. Validates settings before making API calls
|
||||||
|
* 3. Delegates to the TimedPromptsCommand for execution
|
||||||
|
*
|
||||||
|
* Shows user-friendly error messages for common issues like missing
|
||||||
|
* API key or invalid settings.
|
||||||
|
*/
|
||||||
|
private async executeTimedPrompts(): Promise<void> {
|
||||||
|
// Check if timed prompts are already running
|
||||||
|
if (this.timedCommand.isRunning()) {
|
||||||
|
new Notice('Timed prompts are already running. Use "Stop timed prompts" to stop them first.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,13 +210,27 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.staggeredCommand.execute(this.settings);
|
await this.timedCommand.execute(this.settings);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error executing staggered prompts:', error);
|
console.error('Error executing timed prompts:', error);
|
||||||
// Error handling is done in the command layer
|
// Error handling is done in the command layer
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the note prompts command.
|
||||||
|
*
|
||||||
|
* This method:
|
||||||
|
* 1. Validates editor and view are available
|
||||||
|
* 2. Validates settings before making API calls
|
||||||
|
* 3. Delegates to the NotePromptsCommand for execution
|
||||||
|
*
|
||||||
|
* This is an editor command, so Obsidian ensures editor and view exist,
|
||||||
|
* but we double-check for safety.
|
||||||
|
*
|
||||||
|
* @param editor - Active editor instance
|
||||||
|
* @param view - Active markdown view
|
||||||
|
*/
|
||||||
private async executeNotePrompts(editor: Editor, view: MarkdownView): Promise<void> {
|
private async executeNotePrompts(editor: Editor, view: MarkdownView): Promise<void> {
|
||||||
// Check if we can execute the command
|
// Check if we can execute the command
|
||||||
if (!NotePromptsCommand.canExecute(editor, view)) {
|
if (!NotePromptsCommand.canExecute(editor, view)) {
|
||||||
@@ -133,18 +253,31 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private stopStaggeredPrompts(): void {
|
/**
|
||||||
if (this.staggeredCommand.isRunning()) {
|
* Stops the currently running timed prompts sequence.
|
||||||
this.staggeredCommand.stop();
|
*
|
||||||
new Notice('Staggered prompts stopped');
|
* Checks if prompts are actually running before attempting to stop
|
||||||
|
* to provide appropriate feedback messages.
|
||||||
|
*/
|
||||||
|
private stopTimedPrompts(): void {
|
||||||
|
if (this.timedCommand.isRunning()) {
|
||||||
|
this.timedCommand.stop();
|
||||||
|
new Notice('Timed prompts stopped');
|
||||||
} else {
|
} else {
|
||||||
new Notice('No staggered prompts are currently running');
|
new Notice('No timed prompts are currently running');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public API for Settings
|
// MARK: - Public API for Settings
|
||||||
|
|
||||||
getStaggeredStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
/**
|
||||||
return this.staggeredCommand.getStatus();
|
* Gets the current status of the timed prompts sequence.
|
||||||
|
*
|
||||||
|
* This is used by the settings tab or status bar to show current progress.
|
||||||
|
*
|
||||||
|
* @returns Object containing running state and progress information
|
||||||
|
*/
|
||||||
|
getTimedStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
||||||
|
return this.timedCommand.getStatus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"id": "freewriting-prompts",
|
"id": "freewriting-prompts",
|
||||||
"name": "Freewriting Prompts",
|
"name": "Freewriting Prompts",
|
||||||
"version": "1.0.0",
|
"version": "1.2.0",
|
||||||
"minAppVersion": "1.9.12",
|
"minAppVersion": "1.9.12",
|
||||||
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
|
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
|
||||||
"author": "Alexander Kucera",
|
"author": "Alexander Kucera",
|
||||||
|
|||||||
Generated
+604
-665
File diff suppressed because it is too large.
Load diff
+17
-7
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "obsidian-freewriting-prompts",
|
"name": "obsidian-freewriting-prompts",
|
||||||
"version": "1.0.0",
|
"version": "1.2.0",
|
||||||
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
|
"description": "Generate AI-powered writing prompts for freewriting sessions using Anthropic's Claude.",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -8,17 +8,27 @@
|
|||||||
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
|
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
|
||||||
"version": "node version-bump.mjs && git add manifest.json versions.json"
|
"version": "node version-bump.mjs && git add manifest.json versions.json"
|
||||||
},
|
},
|
||||||
"keywords": ["obsidian", "plugin", "writing", "prompts", "ai", "claude", "freewriting"],
|
"keywords": [
|
||||||
"author": "Alexander",
|
"obsidian",
|
||||||
"license": "MIT",
|
"plugin",
|
||||||
|
"writing",
|
||||||
|
"prompts",
|
||||||
|
"ai",
|
||||||
|
"claude",
|
||||||
|
"freewriting"
|
||||||
|
],
|
||||||
|
"author": "Alexander Kucera",
|
||||||
|
"license": "GPL-3.0-only",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.17.0",
|
||||||
"@types/node": "^16.11.6",
|
"@types/node": "^16.11.6",
|
||||||
"@typescript-eslint/eslint-plugin": "5.29.0",
|
|
||||||
"@typescript-eslint/parser": "5.29.0",
|
|
||||||
"builtin-modules": "3.3.0",
|
"builtin-modules": "3.3.0",
|
||||||
"esbuild": "0.17.3",
|
"esbuild": "0.17.3",
|
||||||
|
"eslint": "^9.17.0",
|
||||||
|
"globals": "^16.4.0",
|
||||||
"obsidian": "latest",
|
"obsidian": "latest",
|
||||||
"tslib": "2.4.0",
|
"tslib": "2.4.0",
|
||||||
"typescript": "4.7.4"
|
"typescript": "5.7.3",
|
||||||
|
"typescript-eslint": "^8.18.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
// ABOUTME: Service for managing Claude model list from Anthropic API
|
||||||
|
// ABOUTME: Handles fetching, caching with 24-hour TTL, and fallback to hardcoded list
|
||||||
|
|
||||||
|
import { Notice } from 'obsidian';
|
||||||
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
|
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simplified model representation for UI display purposes.
|
||||||
|
* Used to populate dropdown menus with user-friendly model names.
|
||||||
|
*/
|
||||||
|
export interface ModelOption {
|
||||||
|
/** Model identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
|
id: string;
|
||||||
|
/** Human-readable display name for the UI */
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service responsible for managing the list of available Claude models.
|
||||||
|
*
|
||||||
|
* Key responsibilities:
|
||||||
|
* - Fetches current model list from Anthropic API
|
||||||
|
* - Caches results for 24 hours to minimize API calls
|
||||||
|
* - Provides fallback to hardcoded model list when API is unavailable
|
||||||
|
* - Handles graceful degradation when API key is not configured
|
||||||
|
*
|
||||||
|
* The 24-hour cache TTL balances freshness with API efficiency - models don't
|
||||||
|
* change frequently enough to warrant more aggressive polling, but we want
|
||||||
|
* users to see new models within a reasonable timeframe.
|
||||||
|
*/
|
||||||
|
export class ModelService {
|
||||||
|
private anthropicClient: AnthropicClient;
|
||||||
|
private modelCache: ModelCache | null = null;
|
||||||
|
/** Cache time-to-live in milliseconds (24 hours) */
|
||||||
|
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
/** Track whether we've shown the fallback notice this session to avoid spam */
|
||||||
|
private hasShownFallbackNotice = false;
|
||||||
|
/** In-flight fetch promise to deduplicate concurrent API calls */
|
||||||
|
private inFlight: Promise<ModelOption[]> | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new model service instance.
|
||||||
|
*
|
||||||
|
* @param anthropicClient - Client for making API requests to Anthropic
|
||||||
|
*/
|
||||||
|
constructor(anthropicClient: AnthropicClient) {
|
||||||
|
this.anthropicClient = anthropicClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Public Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves available Claude models with intelligent caching and fallback.
|
||||||
|
*
|
||||||
|
* This method implements a three-tier strategy:
|
||||||
|
* 1. Return cached models if valid (within 24-hour TTL)
|
||||||
|
* 2. Fetch fresh models from API if cache is stale or empty
|
||||||
|
* 3. Fall back to hardcoded ANTHROPIC_MODELS if API fails
|
||||||
|
*
|
||||||
|
* If no API key is configured, quietly returns fallback without showing errors,
|
||||||
|
* since this is expected during initial plugin setup.
|
||||||
|
*
|
||||||
|
* @returns Array of model options formatted for UI display
|
||||||
|
*/
|
||||||
|
async getAvailableModels(): Promise<ModelOption[]> {
|
||||||
|
// Check if we have a valid cache
|
||||||
|
if (this.isCacheValid() && this.modelCache) {
|
||||||
|
return this.formatModels(this.modelCache.models);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no API key, quietly return fallback
|
||||||
|
if (!this.anthropicClient.validateApiKey()) {
|
||||||
|
return this.getFallbackModels();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use shared fetch path with deduplication
|
||||||
|
return this.fetchWithDeduplication('Could not fetch latest models from API. Using default model list.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forces a refresh of the model list from the API, bypassing cache.
|
||||||
|
*
|
||||||
|
* This is called when the user enters a new API key in settings, ensuring
|
||||||
|
* they immediately see the correct models available for their account.
|
||||||
|
* Falls back to hardcoded models if the API request fails.
|
||||||
|
*
|
||||||
|
* Uses the same in-flight deduplication as getAvailableModels to prevent
|
||||||
|
* concurrent refreshModels and getAvailableModels calls from both hitting the API.
|
||||||
|
*
|
||||||
|
* @returns Array of current available models
|
||||||
|
*/
|
||||||
|
async refreshModels(): Promise<ModelOption[]> {
|
||||||
|
// If no API key, quietly return fallback
|
||||||
|
if (!this.anthropicClient.validateApiKey()) {
|
||||||
|
return this.getFallbackModels();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use shared fetch path with deduplication
|
||||||
|
return this.fetchWithDeduplication('Fetching current models failed. Using hardcoded fallback list.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads cached model data from plugin persistent storage.
|
||||||
|
*
|
||||||
|
* Called during plugin initialization to restore the previous session's
|
||||||
|
* model list, avoiding an immediate API call on every startup.
|
||||||
|
*
|
||||||
|
* @param cache - Previously saved cache data, or null if none exists
|
||||||
|
*/
|
||||||
|
loadCache(cache: ModelCache | null): void {
|
||||||
|
this.modelCache = cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves current cache for persistence to disk.
|
||||||
|
*
|
||||||
|
* Called during plugin save operations to preserve the model cache
|
||||||
|
* across Obsidian restarts, maintaining the 24-hour TTL.
|
||||||
|
*
|
||||||
|
* @returns Current cache state, or null if no cache exists
|
||||||
|
*/
|
||||||
|
getCache(): ModelCache | null {
|
||||||
|
return this.modelCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears the cached model list, forcing a fresh fetch on next access.
|
||||||
|
*
|
||||||
|
* Also resets the fallback notice flag to allow showing error messages
|
||||||
|
* again after manual cache reset. This prevents stale "notice already shown"
|
||||||
|
* state across cache resets.
|
||||||
|
*
|
||||||
|
* Useful for testing or troubleshooting cache-related issues.
|
||||||
|
*/
|
||||||
|
clearCache(): void {
|
||||||
|
this.modelCache = null;
|
||||||
|
this.hasShownFallbackNotice = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared fetch method with in-flight deduplication.
|
||||||
|
*
|
||||||
|
* This method is used by both getAvailableModels and refreshModels to prevent
|
||||||
|
* concurrent calls from making duplicate API requests. If a fetch is already
|
||||||
|
* in progress, subsequent calls will wait for and return the same promise.
|
||||||
|
*
|
||||||
|
* @param errorNoticeMessage - Message to show user if fetch fails
|
||||||
|
* @returns Array of model options from the API or fallback
|
||||||
|
*/
|
||||||
|
private async fetchWithDeduplication(errorNoticeMessage: string): Promise<ModelOption[]> {
|
||||||
|
// Try to fetch from API (deduplicate concurrent calls)
|
||||||
|
if (!this.inFlight) {
|
||||||
|
this.inFlight = (async () => {
|
||||||
|
const response = await this.anthropicClient.fetchModels();
|
||||||
|
this.updateCache(response.data);
|
||||||
|
// Reset notice flag on successful fetch
|
||||||
|
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
|
||||||
|
if (!this.hasShownFallbackNotice) {
|
||||||
|
new Notice(errorNoticeMessage);
|
||||||
|
this.hasShownFallbackNotice = true;
|
||||||
|
}
|
||||||
|
// Prefer stale cache over hardcoded fallback if available
|
||||||
|
return this.getStaleCacheModels() ?? this.getFallbackModels();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the current cache is still valid based on TTL.
|
||||||
|
*
|
||||||
|
* Cache is considered valid if it exists and was fetched less than
|
||||||
|
* 24 hours ago. This prevents excessive API calls while ensuring
|
||||||
|
* reasonable freshness of model data.
|
||||||
|
*
|
||||||
|
* @returns true if cache exists and is within TTL, false otherwise
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
*
|
||||||
|
* This is used as a fallback when API fetch fails - a slightly stale cache
|
||||||
|
* is often better than falling back to the hardcoded model list, which may
|
||||||
|
* be more outdated than the cached data.
|
||||||
|
*
|
||||||
|
* @returns Array of cached model options, or null if no cache exists
|
||||||
|
*/
|
||||||
|
private getStaleCacheModels(): ModelOption[] | null {
|
||||||
|
if (!this.modelCache) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.formatModels(this.modelCache.models);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the cache with freshly fetched model data.
|
||||||
|
*
|
||||||
|
* Deduplicates models by ID to guard against accidental duplicates
|
||||||
|
* across pagination responses. Filters to include only model-like entries
|
||||||
|
* (type contains "model") to exclude non-chat API entries if they appear
|
||||||
|
* in future API responses. Sets the fetchedAt timestamp to now,
|
||||||
|
* starting the 24-hour TTL countdown.
|
||||||
|
*
|
||||||
|
* @param models - Array of model information from the API
|
||||||
|
*/
|
||||||
|
private updateCache(models: ModelInfo[]): void {
|
||||||
|
// Deduplicate by id using Map and filter to model-like entries only
|
||||||
|
const byId = new Map<string, ModelInfo>();
|
||||||
|
for (const model of models) {
|
||||||
|
// Filter out non-model entries (e.g., if API starts returning other types)
|
||||||
|
// Keep entries where type contains "model" (case-insensitive)
|
||||||
|
if (model.type && !/model/i.test(model.type)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
byId.set(model.id, model);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.modelCache = {
|
||||||
|
models: Array.from(byId.values()),
|
||||||
|
fetchedAt: Date.now()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transforms API model data into UI-friendly format.
|
||||||
|
*
|
||||||
|
* Prefers display_name when available for better UX, falls back to
|
||||||
|
* model ID if display_name is missing. Results are sorted alphabetically
|
||||||
|
* for easier scanning in the dropdown.
|
||||||
|
*
|
||||||
|
* @param models - Raw model info from API
|
||||||
|
* @returns Formatted options ready for dropdown display
|
||||||
|
*/
|
||||||
|
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||||
|
return models.map(model => ({
|
||||||
|
id: model.id,
|
||||||
|
displayName: model.display_name || model.id
|
||||||
|
})).sort((a, b) => a.displayName.localeCompare(b.displayName));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides fallback model list when API is unavailable.
|
||||||
|
*
|
||||||
|
* Uses the hardcoded ANTHROPIC_MODELS constant which should be periodically
|
||||||
|
* updated to include newly released models. This ensures the plugin remains
|
||||||
|
* functional even during API outages or when no API key is configured.
|
||||||
|
*
|
||||||
|
* @returns Array of fallback model options
|
||||||
|
*/
|
||||||
|
private getFallbackModels(): ModelOption[] {
|
||||||
|
return ANTHROPIC_MODELS.map(id => ({
|
||||||
|
id,
|
||||||
|
displayName: id
|
||||||
|
})).sort((a, b) => a.displayName.localeCompare(b.displayName));
|
||||||
|
}
|
||||||
|
}
|
||||||
+167
-15
@@ -3,61 +3,145 @@
|
|||||||
|
|
||||||
import { Notice } from 'obsidian';
|
import { Notice } from 'obsidian';
|
||||||
import { AnthropicClient } from '../api/anthropicClient';
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types';
|
import { FreewritingPromptsSettings, GeneratedPrompt } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service that coordinates prompt generation between commands and the API client.
|
||||||
|
*
|
||||||
|
* This service layer provides:
|
||||||
|
* - High-level methods for different prompt types (timed vs note)
|
||||||
|
* - In-memory caching with 10-minute TTL to avoid redundant API calls
|
||||||
|
* - Settings validation before attempting generation
|
||||||
|
* - User feedback via Obsidian notices
|
||||||
|
* - Error handling and propagation
|
||||||
|
*
|
||||||
|
* The 10-minute cache is relatively short because:
|
||||||
|
* 1. Users expect fresh prompts when they explicitly request them
|
||||||
|
* 2. The cache prevents rapid-fire duplicate requests during a single session
|
||||||
|
* 3. Memory usage is minimal (cache is just strings with timestamps)
|
||||||
|
*/
|
||||||
export class PromptGeneratorService {
|
export class PromptGeneratorService {
|
||||||
private client: AnthropicClient;
|
private client: AnthropicClient;
|
||||||
|
/** In-memory cache mapping request parameters to generated prompts */
|
||||||
private cache: Map<string, GeneratedPrompt[]> = new Map();
|
private cache: Map<string, GeneratedPrompt[]> = new Map();
|
||||||
|
/** In-flight requests to prevent duplicate concurrent API calls */
|
||||||
|
private inFlight: Map<string, Promise<string[]>> = new Map();
|
||||||
|
/** Cache expiry time in milliseconds (10 minutes) */
|
||||||
private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes
|
private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes
|
||||||
|
|
||||||
// Expose client for API testing in settings
|
/**
|
||||||
|
* Exposes the underlying API client for direct access.
|
||||||
|
* Used by settings tab to test API key connectivity.
|
||||||
|
*/
|
||||||
get anthropicClient(): AnthropicClient {
|
get anthropicClient(): AnthropicClient {
|
||||||
return this.client;
|
return this.client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new prompt generator service.
|
||||||
|
*
|
||||||
|
* @param settings - Plugin settings containing API key and configuration
|
||||||
|
*/
|
||||||
constructor(settings: FreewritingPromptsSettings) {
|
constructor(settings: FreewritingPromptsSettings) {
|
||||||
this.client = new AnthropicClient(settings.apiKey);
|
this.client = new AnthropicClient(settings.apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
async generateStaggeredPrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
|
/**
|
||||||
|
* Generates prompts optimized for timed notifications.
|
||||||
|
*
|
||||||
|
* These prompts are short and answerable quickly since they appear as
|
||||||
|
* timed notifications during freewriting sessions. Uses the timedExamplePrompt
|
||||||
|
* to guide style and applies special system instructions for brevity.
|
||||||
|
*
|
||||||
|
* @param settings - Current plugin settings
|
||||||
|
* @returns Array of short, focused prompts for rapid response
|
||||||
|
* @throws Error if API key is invalid or generation fails
|
||||||
|
*/
|
||||||
|
async generateTimedPrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
|
||||||
return this.generatePrompts(
|
return this.generatePrompts(
|
||||||
settings.staggeredCount,
|
settings.timedCount,
|
||||||
settings.model as AnthropicModel,
|
settings.model,
|
||||||
settings.systemPrompt,
|
settings.systemPrompt,
|
||||||
settings.staggeredExamplePrompt,
|
settings.timedExamplePrompt,
|
||||||
'staggered'
|
'timed'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates prompts for insertion into notes.
|
||||||
|
*
|
||||||
|
* These prompts can be more elaborate and creative since they're inserted
|
||||||
|
* as text into a note rather than appearing as brief notifications. Uses
|
||||||
|
* the freewritingExamplePrompt to guide style.
|
||||||
|
*
|
||||||
|
* @param settings - Current plugin settings
|
||||||
|
* @returns Array of creative prompts suitable for note insertion
|
||||||
|
* @throws Error if API key is invalid or generation fails
|
||||||
|
*/
|
||||||
async generateNotePrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
|
async generateNotePrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
|
||||||
return this.generatePrompts(
|
return this.generatePrompts(
|
||||||
settings.noteCount,
|
settings.noteCount,
|
||||||
settings.model as AnthropicModel,
|
settings.model,
|
||||||
settings.systemPrompt,
|
settings.systemPrompt,
|
||||||
settings.freewritingExamplePrompt,
|
settings.freewritingExamplePrompt,
|
||||||
'note'
|
'note'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the API key for the underlying client.
|
||||||
|
*
|
||||||
|
* Called when the user changes their API key in settings. Clears the cache
|
||||||
|
* since previous cached prompts may have been generated with a different key.
|
||||||
|
*
|
||||||
|
* @param apiKey - New Anthropic API key
|
||||||
|
*/
|
||||||
updateApiKey(apiKey: string): void {
|
updateApiKey(apiKey: string): void {
|
||||||
this.client.updateApiKey(apiKey);
|
this.client.updateApiKey(apiKey);
|
||||||
this.clearCache(); // Clear cache when API key changes
|
this.clearCache(); // Clear cache when API key changes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears all cached prompts.
|
||||||
|
*
|
||||||
|
* Forces fresh generation on next request. Useful when users want to
|
||||||
|
* ensure they're getting completely new prompts rather than cached ones.
|
||||||
|
*/
|
||||||
clearCache(): void {
|
clearCache(): void {
|
||||||
this.cache.clear();
|
this.cache.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Core prompt generation method with caching logic.
|
||||||
|
*
|
||||||
|
* Implements the full generation flow:
|
||||||
|
* 1. Validates API key configuration
|
||||||
|
* 2. Checks cache for matching prompts within TTL
|
||||||
|
* 3. Calls API if cache miss or expired
|
||||||
|
* 4. Stores results in cache with timestamp
|
||||||
|
* 5. Shows user feedback via notices
|
||||||
|
*
|
||||||
|
* The cache key is derived from all generation parameters to ensure
|
||||||
|
* cached prompts match the current settings exactly.
|
||||||
|
*
|
||||||
|
* @param count - Number of prompts to generate
|
||||||
|
* @param model - Claude model ID to use
|
||||||
|
* @param systemPrompt - Base system instructions
|
||||||
|
* @param examplePrompt - Example to guide style
|
||||||
|
* @param type - Prompt type ('timed' or 'note') affecting format and length
|
||||||
|
* @returns Array of generated prompt strings
|
||||||
|
* @throws Error if API key is missing or API call fails
|
||||||
|
*/
|
||||||
private async generatePrompts(
|
private async generatePrompts(
|
||||||
count: number,
|
count: number,
|
||||||
model: AnthropicModel,
|
model: string,
|
||||||
systemPrompt: string,
|
systemPrompt: string,
|
||||||
examplePrompt: string,
|
examplePrompt: string,
|
||||||
type: 'staggered' | 'note'
|
type: 'timed' | 'note'
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
if (!this.client.validateApiKey()) {
|
if (!this.client.validateApiKey()) {
|
||||||
new Notice('Please configure your Anthropic API key in settings');
|
new Notice('Please configure your Anthropic API key in settings');
|
||||||
@@ -71,9 +155,23 @@ export class PromptGeneratorService {
|
|||||||
return cachedPrompts.map(p => p.text);
|
return cachedPrompts.map(p => p.text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deduplicate concurrent requests with identical parameters
|
||||||
|
const existing = this.inFlight.get(cacheKey);
|
||||||
|
if (existing) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
new Notice('Generating prompts...');
|
new Notice('Generating prompts...');
|
||||||
const prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt);
|
const pending = this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type);
|
||||||
|
this.inFlight.set(cacheKey, pending);
|
||||||
|
let prompts = await pending;
|
||||||
|
|
||||||
|
// Enforce requested count - models can occasionally over-generate
|
||||||
|
// This ensures deterministic UX and correct cache key matching
|
||||||
|
if (prompts.length > count) {
|
||||||
|
prompts = prompts.slice(0, count);
|
||||||
|
}
|
||||||
|
|
||||||
const generatedPrompts: GeneratedPrompt[] = prompts.map(text => ({
|
const generatedPrompts: GeneratedPrompt[] = prompts.map(text => ({
|
||||||
text,
|
text,
|
||||||
@@ -92,15 +190,31 @@ export class PromptGeneratorService {
|
|||||||
new Notice('Unknown error occurred while generating prompts');
|
new Notice('Unknown error occurred while generating prompts');
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
|
} finally {
|
||||||
|
this.inFlight.delete(cacheKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a unique cache key from generation parameters.
|
||||||
|
*
|
||||||
|
* The key is a JSON string containing all parameters that affect output.
|
||||||
|
* This ensures we only serve cached prompts when ALL settings match,
|
||||||
|
* preventing incorrect reuse when the user changes any configuration.
|
||||||
|
*
|
||||||
|
* @param count - Number of prompts
|
||||||
|
* @param model - Model ID
|
||||||
|
* @param systemPrompt - System instructions
|
||||||
|
* @param examplePrompt - Example prompt
|
||||||
|
* @param type - Prompt type
|
||||||
|
* @returns JSON string uniquely identifying this parameter combination
|
||||||
|
*/
|
||||||
private createCacheKey(
|
private createCacheKey(
|
||||||
count: number,
|
count: number,
|
||||||
model: AnthropicModel,
|
model: string,
|
||||||
systemPrompt: string,
|
systemPrompt: string,
|
||||||
examplePrompt: string,
|
examplePrompt: string,
|
||||||
type: string
|
type: 'timed' | 'note'
|
||||||
): string {
|
): string {
|
||||||
const keyData = {
|
const keyData = {
|
||||||
count,
|
count,
|
||||||
@@ -112,12 +226,31 @@ export class PromptGeneratorService {
|
|||||||
return JSON.stringify(keyData);
|
return JSON.stringify(keyData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves cached prompts if they exist and are still valid.
|
||||||
|
*
|
||||||
|
* Checks both existence and age of cached prompts. Returns null if:
|
||||||
|
* - No cache entry exists for this key
|
||||||
|
* - Cache entry is empty (defensive guard)
|
||||||
|
* - Cache is older than 10 minutes (expired)
|
||||||
|
*
|
||||||
|
* Expired entries are automatically removed from the cache map.
|
||||||
|
*
|
||||||
|
* @param cacheKey - Cache key to look up
|
||||||
|
* @returns Array of cached prompts if valid, null otherwise
|
||||||
|
*/
|
||||||
private getCachedPrompts(cacheKey: string): GeneratedPrompt[] | null {
|
private getCachedPrompts(cacheKey: string): GeneratedPrompt[] | null {
|
||||||
const cached = this.cache.get(cacheKey);
|
const cached = this.cache.get(cacheKey);
|
||||||
if (!cached) {
|
if (!cached) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Guard against empty cache arrays
|
||||||
|
if (cached.length === 0) {
|
||||||
|
this.cache.delete(cacheKey);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const now = new Date().getTime();
|
const now = new Date().getTime();
|
||||||
const cacheTime = cached[0].timestamp.getTime();
|
const cacheTime = cached[0].timestamp.getTime();
|
||||||
|
|
||||||
@@ -131,6 +264,21 @@ export class PromptGeneratorService {
|
|||||||
|
|
||||||
// MARK: - Validation Methods
|
// MARK: - Validation Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates plugin settings before attempting prompt generation.
|
||||||
|
*
|
||||||
|
* Checks all settings that affect prompt generation to provide early
|
||||||
|
* feedback before making API calls. Validates:
|
||||||
|
* - API key is present
|
||||||
|
* - Model ID is specified
|
||||||
|
* - Numeric settings are within acceptable ranges
|
||||||
|
*
|
||||||
|
* This validation prevents API errors and gives users clear guidance
|
||||||
|
* about what needs to be fixed in their configuration.
|
||||||
|
*
|
||||||
|
* @param settings - Settings to validate
|
||||||
|
* @returns Object containing validity status and array of error messages
|
||||||
|
*/
|
||||||
validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } {
|
validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } {
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
|
|
||||||
@@ -138,8 +286,12 @@ export class PromptGeneratorService {
|
|||||||
errors.push('API key is required');
|
errors.push('API key is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings.staggeredCount < 1 || settings.staggeredCount > 50) {
|
if (!settings.model || settings.model.trim().length === 0) {
|
||||||
errors.push('Staggered count must be between 1 and 50');
|
errors.push('Claude model is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.timedCount < 1 || settings.timedCount > 50) {
|
||||||
|
errors.push('Timed count must be between 1 and 50');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings.delaySeconds < 1 || settings.delaySeconds > 300) {
|
if (settings.delaySeconds < 1 || settings.delaySeconds > 300) {
|
||||||
|
|||||||
+363
-55
@@ -1,49 +1,156 @@
|
|||||||
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin
|
// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin
|
||||||
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization
|
// ABOUTME: Handles user configuration including API key, model selection, and prompt customization
|
||||||
|
|
||||||
import { App, Notice, PluginSettingTab, Setting } from 'obsidian';
|
import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, Setting } from 'obsidian';
|
||||||
import FreewritingPromptsPlugin from './main';
|
import FreewritingPromptsPlugin from './main';
|
||||||
import { FreewritingPromptsSettings, ANTHROPIC_MODELS } from './types';
|
import { FreewritingPromptsSettings } from './types';
|
||||||
|
import { ModelOption } from './services/modelService';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default plugin settings applied on first installation.
|
||||||
|
*
|
||||||
|
* These defaults are chosen to:
|
||||||
|
* - Use the most cost-effective model (Haiku) for testing
|
||||||
|
* - Provide reasonable timing for timed prompts (6 seconds)
|
||||||
|
* - Include example prompts that demonstrate expected styles
|
||||||
|
* - Maintain reasonable limits on prompt counts
|
||||||
|
*/
|
||||||
export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
|
export const DEFAULT_SETTINGS: FreewritingPromptsSettings = {
|
||||||
|
/** Empty by default - user must provide their own API key */
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
model: 'claude-3-haiku-20240307',
|
/** Haiku is the fastest and most cost-effective model for prompt generation */
|
||||||
staggeredCount: 10,
|
model: 'claude-3-5-haiku-latest' as const,
|
||||||
|
/** 10 prompts provides a good freewriting session length */
|
||||||
|
timedCount: 10,
|
||||||
|
/** 6 seconds allows time to read and respond without feeling rushed */
|
||||||
delaySeconds: 6,
|
delaySeconds: 6,
|
||||||
|
/** 3 prompts is enough for a note without being overwhelming */
|
||||||
noteCount: 3,
|
noteCount: 3,
|
||||||
|
/** Base system prompt guiding the AI's creative writing style */
|
||||||
systemPrompt: 'You are a creative writing assistant. Generate engaging, thought-provoking writing prompts that inspire creativity and help writers overcome blocks. Focus on variety, originality, and emotional depth.',
|
systemPrompt: 'You are a creative writing assistant. Generate engaging, thought-provoking writing prompts that inspire creativity and help writers overcome blocks. Focus on variety, originality, and emotional depth.',
|
||||||
staggeredExamplePrompt: 'The interesting thing about a rose is…',
|
/** Example demonstrating short, immediate style for timed prompts */
|
||||||
|
timedExamplePrompt: 'The interesting thing about a rose is…',
|
||||||
|
/** Example demonstrating more elaborate style for note prompts */
|
||||||
freewritingExamplePrompt: 'Describe a world where colors have been outlawed and only exist in secret underground galleries.'
|
freewritingExamplePrompt: 'Describe a world where colors have been outlawed and only exist in secret underground galleries.'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings UI tab for the Freewriting Prompts plugin.
|
||||||
|
*
|
||||||
|
* This class builds the settings interface with several key sections:
|
||||||
|
* - API Configuration: API key, model selection, connection testing
|
||||||
|
* - Command Configuration: Counts and timing for different prompt types
|
||||||
|
* - Prompt Customization: System prompt and examples to guide style
|
||||||
|
* - Actions: Cache clearing and other utility functions
|
||||||
|
*
|
||||||
|
* Key UX considerations:
|
||||||
|
* - Model dropdown loads asynchronously to avoid blocking UI
|
||||||
|
* - API key is masked as a password field
|
||||||
|
* - Model refresh happens automatically when API key is entered
|
||||||
|
* - Fallback to hardcoded models if API is unavailable
|
||||||
|
* - Detailed test results help troubleshoot connection issues
|
||||||
|
*/
|
||||||
export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
||||||
plugin: FreewritingPromptsPlugin;
|
plugin: FreewritingPromptsPlugin;
|
||||||
|
/** Reference to model dropdown for dynamic updates */
|
||||||
|
private modelDropdown: DropdownComponent | null = null;
|
||||||
|
/** Cached list of available models for the dropdown */
|
||||||
|
private availableModels: ModelOption[] = [];
|
||||||
|
/** Debounce timer for API key changes to avoid excessive API calls */
|
||||||
|
private apiKeyDebounceTimer: number | null = null;
|
||||||
|
/** Debounce timer for settings saves to reduce disk writes */
|
||||||
|
private settingsSaveTimer: number | null = null;
|
||||||
|
/** Debounce delay in milliseconds */
|
||||||
|
private readonly API_KEY_DEBOUNCE_MS = 500;
|
||||||
|
/** Debounce delay for settings saves in milliseconds */
|
||||||
|
private readonly SETTINGS_SAVE_DEBOUNCE_MS = 500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new settings tab instance.
|
||||||
|
*
|
||||||
|
* @param app - Obsidian app instance
|
||||||
|
* @param plugin - Plugin instance for accessing services and settings
|
||||||
|
*/
|
||||||
constructor(app: App, plugin: FreewritingPromptsPlugin) {
|
constructor(app: App, plugin: FreewritingPromptsPlugin) {
|
||||||
super(app, plugin);
|
super(app, plugin);
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleanup method to clear any pending timers.
|
||||||
|
* Called when settings tab is closed or destroyed.
|
||||||
|
*/
|
||||||
|
hide(): void {
|
||||||
|
if (this.apiKeyDebounceTimer !== null) {
|
||||||
|
window.clearTimeout(this.apiKeyDebounceTimer);
|
||||||
|
this.apiKeyDebounceTimer = null;
|
||||||
|
}
|
||||||
|
if (this.settingsSaveTimer !== null) {
|
||||||
|
window.clearTimeout(this.settingsSaveTimer);
|
||||||
|
this.settingsSaveTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Debounces settings saves to reduce disk writes on rapid changes.
|
||||||
|
* Clears any pending save and schedules a new one after the debounce delay.
|
||||||
|
*/
|
||||||
|
private debounceSaveSettings(): void {
|
||||||
|
if (this.settingsSaveTimer !== null) {
|
||||||
|
window.clearTimeout(this.settingsSaveTimer);
|
||||||
|
}
|
||||||
|
this.settingsSaveTimer = window.setTimeout(() => {
|
||||||
|
void this.plugin.saveSettings();
|
||||||
|
this.settingsSaveTimer = null;
|
||||||
|
}, this.SETTINGS_SAVE_DEBOUNCE_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the settings UI.
|
||||||
|
*
|
||||||
|
* This method builds all settings sections and initiates async loading
|
||||||
|
* of model data without blocking the UI. The model dropdown starts with
|
||||||
|
* a "Loading models..." placeholder and updates when data arrives.
|
||||||
|
*/
|
||||||
display(): void {
|
display(): void {
|
||||||
const { containerEl } = this;
|
const { containerEl } = this;
|
||||||
containerEl.empty();
|
containerEl.empty();
|
||||||
|
|
||||||
containerEl.createEl('h2', { text: 'Freewriting Prompts Settings' });
|
|
||||||
|
|
||||||
// MARK: - API Configuration
|
// MARK: - API Configuration
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'API Configuration' });
|
new Setting(containerEl)
|
||||||
|
.setName('API configuration')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Anthropic API Key')
|
.setName('Anthropic API key')
|
||||||
.setDesc('Your Anthropic API key for Claude. Get one at https://console.anthropic.com/')
|
.setDesc('Your Anthropic API key for Claude. Get one at https://console.anthropic.com/')
|
||||||
.addText(text => text
|
.addText(text => text
|
||||||
.setPlaceholder('sk-ant-...')
|
.setPlaceholder('sk-ant-...')
|
||||||
.setValue(this.plugin.settings.apiKey)
|
.setValue(this.plugin.settings.apiKey)
|
||||||
.onChange(async (value) => {
|
.onChange((value) => {
|
||||||
this.plugin.settings.apiKey = value;
|
this.plugin.settings.apiKey = value;
|
||||||
await this.plugin.saveSettings();
|
|
||||||
this.plugin.promptGenerator.updateApiKey(value);
|
// Clear any existing debounce timer
|
||||||
|
if (this.apiKeyDebounceTimer !== null) {
|
||||||
|
window.clearTimeout(this.apiKeyDebounceTimer);
|
||||||
|
this.apiKeyDebounceTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debounce both saving and model refresh to reduce disk writes and API calls
|
||||||
|
this.apiKeyDebounceTimer = window.setTimeout(() => {
|
||||||
|
void (async () => {
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
// Note: updateApiKey is called by saveSettings only if key changed
|
||||||
|
// This avoids clearing the prompt cache twice
|
||||||
|
|
||||||
|
// Refresh models if API key has content
|
||||||
|
if (value.trim().length > 0) {
|
||||||
|
await this.refreshModels();
|
||||||
|
}
|
||||||
|
this.apiKeyDebounceTimer = null;
|
||||||
|
})();
|
||||||
|
}, this.API_KEY_DEBOUNCE_MS);
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
// Make it a password field
|
// Make it a password field
|
||||||
@@ -51,50 +158,65 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
});
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Test API Key')
|
.setName('Test API key')
|
||||||
.setDesc('Test your API key to verify it works correctly')
|
.setDesc('Test your API key to verify it works correctly')
|
||||||
.addButton(button => button
|
.addButton(button => button
|
||||||
.setButtonText('Test Connection')
|
.setButtonText('Test connection')
|
||||||
.onClick(async () => {
|
.onClick(() => {
|
||||||
await this.testApiKey(button);
|
void this.testApiKey(button);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Claude Model')
|
.setName('Claude model')
|
||||||
.setDesc('Which Claude model to use for generating prompts')
|
.setDesc('Which Claude model to use for generating prompts')
|
||||||
.addDropdown(dropdown => {
|
.addDropdown(dropdown => {
|
||||||
ANTHROPIC_MODELS.forEach(model => {
|
this.modelDropdown = dropdown;
|
||||||
dropdown.addOption(model, model);
|
this.populateModelDropdown(dropdown);
|
||||||
|
// Only set value if models are loaded to avoid setting non-existent options
|
||||||
|
if (this.availableModels.length > 0) {
|
||||||
|
dropdown.setValue(this.plugin.settings.model);
|
||||||
|
}
|
||||||
|
dropdown.onChange((value) => {
|
||||||
|
this.plugin.settings.model = value;
|
||||||
|
this.debounceSaveSettings();
|
||||||
});
|
});
|
||||||
dropdown
|
|
||||||
.setValue(this.plugin.settings.model)
|
|
||||||
.onChange(async (value) => {
|
|
||||||
this.plugin.settings.model = value;
|
|
||||||
await this.plugin.saveSettings();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Load models asynchronously without blocking UI
|
||||||
|
void this.loadModelsAsync();
|
||||||
|
|
||||||
// MARK: - Command Configuration
|
// MARK: - Command Configuration
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'Command Configuration' });
|
new Setting(containerEl)
|
||||||
|
.setName('Command configuration')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Staggered Prompts Count')
|
.setName('Timed prompts count')
|
||||||
.setDesc('Number of prompts to generate for staggered notifications (1-50)')
|
.setDesc('Number of prompts to generate for timed notifications (1-50)')
|
||||||
.addText(text => text
|
.addText(text => text
|
||||||
.setPlaceholder('10')
|
.setPlaceholder('10')
|
||||||
.setValue(this.plugin.settings.staggeredCount.toString())
|
.setValue(this.plugin.settings.timedCount.toString())
|
||||||
.onChange(async (value) => {
|
.onChange(async (value) => {
|
||||||
const count = parseInt(value);
|
const count = parseInt(value);
|
||||||
if (!isNaN(count) && count >= 1 && count <= 50) {
|
if (!isNaN(count) && count >= 1 && count <= 50) {
|
||||||
this.plugin.settings.staggeredCount = count;
|
this.plugin.settings.timedCount = count;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
}
|
}
|
||||||
}));
|
}))
|
||||||
|
.then(setting => {
|
||||||
|
const input = setting.controlEl.querySelector('input');
|
||||||
|
if (input) {
|
||||||
|
input.setAttribute('type', 'number');
|
||||||
|
input.setAttribute('min', '1');
|
||||||
|
input.setAttribute('max', '50');
|
||||||
|
input.setAttribute('step', '1');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Delay Between Prompts')
|
.setName('Delay between prompts')
|
||||||
.setDesc('Seconds to wait between each staggered prompt notification (1-300)')
|
.setDesc('Seconds to wait between each timed prompt notification (1-300)')
|
||||||
.addText(text => text
|
.addText(text => text
|
||||||
.setPlaceholder('6')
|
.setPlaceholder('6')
|
||||||
.setValue(this.plugin.settings.delaySeconds.toString())
|
.setValue(this.plugin.settings.delaySeconds.toString())
|
||||||
@@ -104,10 +226,19 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
this.plugin.settings.delaySeconds = delay;
|
this.plugin.settings.delaySeconds = delay;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
}
|
}
|
||||||
}));
|
}))
|
||||||
|
.then(setting => {
|
||||||
|
const input = setting.controlEl.querySelector('input');
|
||||||
|
if (input) {
|
||||||
|
input.setAttribute('type', 'number');
|
||||||
|
input.setAttribute('min', '1');
|
||||||
|
input.setAttribute('max', '300');
|
||||||
|
input.setAttribute('step', '1');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Note Prompts Count')
|
.setName('Note prompts count')
|
||||||
.setDesc('Number of prompts to append to the current note (1-20)')
|
.setDesc('Number of prompts to append to the current note (1-20)')
|
||||||
.addText(text => text
|
.addText(text => text
|
||||||
.setPlaceholder('3')
|
.setPlaceholder('3')
|
||||||
@@ -118,49 +249,60 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
this.plugin.settings.noteCount = count;
|
this.plugin.settings.noteCount = count;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
}
|
}
|
||||||
}));
|
}))
|
||||||
|
.then(setting => {
|
||||||
|
const input = setting.controlEl.querySelector('input');
|
||||||
|
if (input) {
|
||||||
|
input.setAttribute('type', 'number');
|
||||||
|
input.setAttribute('min', '1');
|
||||||
|
input.setAttribute('max', '20');
|
||||||
|
input.setAttribute('step', '1');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// MARK: - Prompt Customization
|
// MARK: - Prompt Customization
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'Prompt Customization' });
|
new Setting(containerEl)
|
||||||
|
.setName('Prompt customization')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('System Prompt')
|
.setName('System prompt')
|
||||||
.setDesc('Instructions for the AI on how to generate prompts')
|
.setDesc('Instructions for the AI on how to generate prompts')
|
||||||
.addTextArea(text => text
|
.addTextArea(text => text
|
||||||
.setPlaceholder('You are a creative writing assistant...')
|
.setPlaceholder('You are a creative writing assistant...')
|
||||||
.setValue(this.plugin.settings.systemPrompt)
|
.setValue(this.plugin.settings.systemPrompt)
|
||||||
.onChange(async (value) => {
|
.onChange((value) => {
|
||||||
this.plugin.settings.systemPrompt = value;
|
this.plugin.settings.systemPrompt = value;
|
||||||
await this.plugin.saveSettings();
|
this.debounceSaveSettings();
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '3');
|
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '3');
|
||||||
});
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Staggered Prompts Example')
|
.setName('Timed prompts example')
|
||||||
.setDesc('Example prompt to guide the style for staggered notifications')
|
.setDesc('Example prompt to guide the style for timed notifications')
|
||||||
.addTextArea(text => text
|
.addTextArea(text => text
|
||||||
.setPlaceholder('Write about a character who...')
|
.setPlaceholder('Write about a character who...')
|
||||||
.setValue(this.plugin.settings.staggeredExamplePrompt)
|
.setValue(this.plugin.settings.timedExamplePrompt)
|
||||||
.onChange(async (value) => {
|
.onChange((value) => {
|
||||||
this.plugin.settings.staggeredExamplePrompt = value;
|
this.plugin.settings.timedExamplePrompt = value;
|
||||||
await this.plugin.saveSettings();
|
this.debounceSaveSettings();
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
|
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
|
||||||
});
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Note Prompts Example')
|
.setName('Note prompts example')
|
||||||
.setDesc('Example prompt to guide the style for note prompts')
|
.setDesc('Example prompt to guide the style for note prompts')
|
||||||
.addTextArea(text => text
|
.addTextArea(text => text
|
||||||
.setPlaceholder('Describe a world where...')
|
.setPlaceholder('Describe a world where...')
|
||||||
.setValue(this.plugin.settings.freewritingExamplePrompt)
|
.setValue(this.plugin.settings.freewritingExamplePrompt)
|
||||||
.onChange(async (value) => {
|
.onChange((value) => {
|
||||||
this.plugin.settings.freewritingExamplePrompt = value;
|
this.plugin.settings.freewritingExamplePrompt = value;
|
||||||
await this.plugin.saveSettings();
|
this.debounceSaveSettings();
|
||||||
}))
|
}))
|
||||||
.then(setting => {
|
.then(setting => {
|
||||||
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
|
setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2');
|
||||||
@@ -168,25 +310,191 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// MARK: - Actions
|
// MARK: - Actions
|
||||||
|
|
||||||
containerEl.createEl('h3', { text: 'Actions' });
|
new Setting(containerEl)
|
||||||
|
.setName('Actions')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Clear Cache')
|
.setName('Clear cache')
|
||||||
.setDesc('Clear the cached prompts to force regeneration')
|
.setDesc('Clear the cached prompts to force regeneration')
|
||||||
.addButton(button => button
|
.addButton(button => button
|
||||||
.setButtonText('Clear Cache')
|
.setButtonText('Clear cache')
|
||||||
.onClick(() => {
|
.onClick(() => {
|
||||||
this.plugin.promptGenerator.clearCache();
|
this.plugin.promptGenerator.clearCache();
|
||||||
// Show a temporary notice
|
// Show a temporary notice
|
||||||
const notice = new Notice('Cache cleared');
|
const notice = new Notice('Cache cleared');
|
||||||
setTimeout(() => notice.hide(), 2000);
|
setTimeout(() => notice.hide(), 2000);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Clear model list cache')
|
||||||
|
.setDesc('Clear cached Claude model list to force a fresh fetch from the API')
|
||||||
|
.addButton(button => button
|
||||||
|
.setButtonText('Clear models cache')
|
||||||
|
.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();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Model Loading
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads available models from the API.
|
||||||
|
*
|
||||||
|
* This is the core model-fetching method that calls the ModelService.
|
||||||
|
* Errors are logged but not shown to the user here - they're shown by
|
||||||
|
* the ModelService itself via Notice popups.
|
||||||
|
*/
|
||||||
|
private async loadModels(): Promise<void> {
|
||||||
|
try {
|
||||||
|
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading models:', error);
|
||||||
|
// Error already shown by ModelService via Notice
|
||||||
|
// availableModels will be empty array, dropdown will be disabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads models asynchronously without blocking UI rendering.
|
||||||
|
*
|
||||||
|
* This method is called after the UI is displayed to avoid blocking
|
||||||
|
* the settings tab from appearing. The dropdown starts in a "Loading..."
|
||||||
|
* state and updates when models arrive.
|
||||||
|
*
|
||||||
|
* If the current model is no longer available (e.g., deprecated), falls
|
||||||
|
* back to the first available model and updates settings.
|
||||||
|
*/
|
||||||
|
private async loadModelsAsync(): Promise<void> {
|
||||||
|
await this.loadModels();
|
||||||
|
|
||||||
|
// Update dropdown after models are loaded
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.populateModelDropdown(this.modelDropdown);
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
// Fall back to first available model if current one is gone
|
||||||
|
const fallbackModel = this.availableModels[0];
|
||||||
|
if (!fallbackModel) {
|
||||||
|
// Edge case: both API and fallback returned empty
|
||||||
|
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})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Populates the model dropdown with available models.
|
||||||
|
*
|
||||||
|
* If no models are available yet, shows a "Loading models..." placeholder
|
||||||
|
* and disables the dropdown. Once models load, this is called again to
|
||||||
|
* populate the real options.
|
||||||
|
*
|
||||||
|
* @param dropdown - Dropdown component to populate
|
||||||
|
*/
|
||||||
|
private populateModelDropdown(dropdown: DropdownComponent): void {
|
||||||
|
if (this.availableModels.length === 0) {
|
||||||
|
// No models available yet, disable dropdown
|
||||||
|
dropdown.addOption('', 'Loading models...');
|
||||||
|
dropdown.setDisabled(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear existing options
|
||||||
|
dropdown.selectEl.empty();
|
||||||
|
|
||||||
|
// Add all available models
|
||||||
|
this.availableModels.forEach(model => {
|
||||||
|
dropdown.addOption(model.id, model.displayName);
|
||||||
|
});
|
||||||
|
|
||||||
|
dropdown.setDisabled(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forces a refresh of the model list from the API.
|
||||||
|
*
|
||||||
|
* This is called when the user enters a new API key to ensure they see
|
||||||
|
* models available for their specific account. Shows a "Refreshing..."
|
||||||
|
* state during the fetch.
|
||||||
|
*
|
||||||
|
* If the current model is no longer available after refresh, falls back
|
||||||
|
* to the first available model and notifies the user.
|
||||||
|
*/
|
||||||
|
private async refreshModels(): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Disable dropdown during refresh
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.modelDropdown.setDisabled(true);
|
||||||
|
this.modelDropdown.selectEl.empty();
|
||||||
|
this.modelDropdown.addOption('', 'Refreshing models...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch new models
|
||||||
|
this.availableModels = await this.plugin.modelService.refreshModels();
|
||||||
|
|
||||||
|
// Update dropdown
|
||||||
|
if (this.modelDropdown) {
|
||||||
|
this.populateModelDropdown(this.modelDropdown);
|
||||||
|
|
||||||
|
// Restore selected model if it still exists
|
||||||
|
const currentModel = this.plugin.settings.model;
|
||||||
|
const modelExists = this.availableModels.some(m => m.id === currentModel);
|
||||||
|
if (modelExists) {
|
||||||
|
this.modelDropdown.setValue(currentModel);
|
||||||
|
} 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) {
|
||||||
|
this.modelDropdown.setValue(fallbackModel.id);
|
||||||
|
this.plugin.settings.model = fallbackModel.id;
|
||||||
|
new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`);
|
||||||
|
// Save only if model actually changed
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error refreshing models:', error);
|
||||||
|
// Error already shown by ModelService via Notice
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - API Testing
|
// MARK: - API Testing
|
||||||
|
|
||||||
private async testApiKey(button: any): Promise<void> {
|
/**
|
||||||
const originalText = button.buttonEl.textContent;
|
* Tests the configured API key by making a minimal request to Claude.
|
||||||
|
*
|
||||||
|
* This provides immediate feedback about whether:
|
||||||
|
* - The API key is valid
|
||||||
|
* - The network connection works
|
||||||
|
* - The selected model is accessible
|
||||||
|
* - Performance is reasonable (response time)
|
||||||
|
*
|
||||||
|
* Shows detailed success or failure information via Notice, including
|
||||||
|
* troubleshooting guidance for common error scenarios.
|
||||||
|
*
|
||||||
|
* @param button - Button component to update with loading state
|
||||||
|
*/
|
||||||
|
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||||
|
const originalText = button.buttonEl.textContent || 'Test connection';
|
||||||
|
|
||||||
// Update button to show loading state
|
// Update button to show loading state
|
||||||
button.setButtonText('Testing...');
|
button.setButtonText('Testing...');
|
||||||
@@ -194,7 +502,7 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const client = this.plugin.promptGenerator.anthropicClient;
|
const client = this.plugin.promptGenerator.anthropicClient;
|
||||||
const result = await client.testApiKey(this.plugin.settings.model as any);
|
const result = await client.testApiKey(this.plugin.settings.model);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
// Success - show detailed information
|
// Success - show detailed information
|
||||||
|
|||||||
+9
-6
@@ -1,8 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
|
Freewriting Prompts Plugin Styles
|
||||||
This CSS file will be included with your plugin, and
|
|
||||||
available in the app when your plugin is enabled.
|
|
||||||
|
|
||||||
If your plugin does not need CSS, delete this file.
|
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/* Styling for timed prompt notifications */
|
||||||
|
.freewriting-prompt-notice {
|
||||||
|
max-width: 400px !important;
|
||||||
|
white-space: pre-wrap !important;
|
||||||
|
font-size: 14px !important;
|
||||||
|
line-height: 1.4 !important;
|
||||||
|
}
|
||||||
@@ -1,57 +1,179 @@
|
|||||||
// ABOUTME: Type definitions for the Freewriting Prompts plugin
|
// ABOUTME: Type definitions for the Freewriting Prompts plugin
|
||||||
// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration
|
// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type alias representing a Claude model identifier.
|
||||||
|
* Used to document the intent that a string should be a valid Claude model ID.
|
||||||
|
*/
|
||||||
|
export type ModelId = string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugin configuration settings that control prompt generation behavior.
|
||||||
|
* These settings are persisted to disk and can be modified through the settings UI.
|
||||||
|
*/
|
||||||
export interface FreewritingPromptsSettings {
|
export interface FreewritingPromptsSettings {
|
||||||
|
/** Anthropic API key for authenticating with Claude API */
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
model: string;
|
/** Claude model ID to use for prompt generation (e.g., 'claude-3-5-haiku-latest') */
|
||||||
staggeredCount: number;
|
model: ModelId; // Changed from AnthropicModel to string to support dynamic models
|
||||||
|
/** Number of prompts to generate for timed notifications (1-50) */
|
||||||
|
timedCount: number;
|
||||||
|
/** Delay in seconds between each timed prompt notification (1-300) */
|
||||||
delaySeconds: number;
|
delaySeconds: number;
|
||||||
|
/** Number of prompts to append to a note (1-20) */
|
||||||
noteCount: number;
|
noteCount: number;
|
||||||
|
/** System-level instructions that guide the AI's prompt generation behavior */
|
||||||
systemPrompt: string;
|
systemPrompt: string;
|
||||||
staggeredExamplePrompt: string;
|
/** Example prompt that demonstrates the desired style for timed prompts */
|
||||||
|
timedExamplePrompt: string;
|
||||||
|
/** Example prompt that demonstrates the desired style for note-inserted prompts */
|
||||||
freewritingExamplePrompt: string;
|
freewritingExamplePrompt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extended settings data that includes both user configuration and cached model information.
|
||||||
|
* This is the structure saved to and loaded from disk to persist state across sessions.
|
||||||
|
*/
|
||||||
|
export interface FreewritingPromptsData extends FreewritingPromptsSettings {
|
||||||
|
/** Optional cached model list with 24-hour TTL to reduce API calls */
|
||||||
|
modelCache?: ModelCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a single message in the conversation with Claude.
|
||||||
|
* Used to construct the messages array sent to the Anthropic API.
|
||||||
|
*/
|
||||||
export interface AnthropicMessage {
|
export interface AnthropicMessage {
|
||||||
|
/** Role identifier indicating who sent the message */
|
||||||
role: 'user' | 'assistant' | 'system';
|
role: 'user' | 'assistant' | 'system';
|
||||||
|
/** The actual content/text of the message */
|
||||||
content: string;
|
content: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request payload structure for the Anthropic Messages API.
|
||||||
|
* Defines all parameters needed to generate a completion from Claude.
|
||||||
|
*/
|
||||||
export interface AnthropicRequest {
|
export interface AnthropicRequest {
|
||||||
model: string;
|
/** Model identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
|
model: ModelId;
|
||||||
|
/** Maximum number of tokens to generate in the response */
|
||||||
max_tokens: number;
|
max_tokens: number;
|
||||||
|
/** Array of conversation messages between user and assistant */
|
||||||
messages: AnthropicMessage[];
|
messages: AnthropicMessage[];
|
||||||
|
/** Optional system prompt that provides context and instructions */
|
||||||
system?: string;
|
system?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response structure returned by the Anthropic Messages API.
|
||||||
|
* Contains the generated text, metadata, and token usage information.
|
||||||
|
*/
|
||||||
export interface AnthropicResponse {
|
export interface AnthropicResponse {
|
||||||
|
/** Array of content blocks containing the generated text */
|
||||||
content: Array<{
|
content: Array<{
|
||||||
|
/** The actual generated text */
|
||||||
text: string;
|
text: string;
|
||||||
|
/** Content type identifier */
|
||||||
type: 'text';
|
type: 'text';
|
||||||
}>;
|
}>;
|
||||||
|
/** Unique identifier for this API response */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Model that generated the response */
|
||||||
model: string;
|
model: string;
|
||||||
|
/** Role of the responder (always 'assistant' for API responses) */
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
|
/** Reason the generation stopped (e.g., 'end_turn', 'max_tokens') */
|
||||||
stop_reason: string;
|
stop_reason: string;
|
||||||
|
/** Custom stop sequence that triggered completion, if any */
|
||||||
stop_sequence: null;
|
stop_sequence: null;
|
||||||
|
/** Response type identifier */
|
||||||
type: 'message';
|
type: 'message';
|
||||||
|
/** Token usage statistics for billing and monitoring */
|
||||||
usage: {
|
usage: {
|
||||||
|
/** Number of tokens in the input prompt */
|
||||||
input_tokens: number;
|
input_tokens: number;
|
||||||
|
/** Number of tokens generated in the response */
|
||||||
output_tokens: number;
|
output_tokens: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a generated writing prompt with its creation timestamp.
|
||||||
|
* Used for caching prompts to avoid unnecessary API calls within the cache TTL.
|
||||||
|
*/
|
||||||
export interface GeneratedPrompt {
|
export interface GeneratedPrompt {
|
||||||
|
/** The actual prompt text generated by Claude */
|
||||||
text: string;
|
text: string;
|
||||||
|
/** When this prompt was generated (used for cache expiry) */
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Information about a single Claude model returned from the Models API.
|
||||||
|
* Used to populate the model selection dropdown with current available models.
|
||||||
|
*/
|
||||||
|
export interface ModelInfo {
|
||||||
|
/** Unique model identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
|
id: string;
|
||||||
|
/** Human-readable model name for display purposes */
|
||||||
|
display_name?: string;
|
||||||
|
/** ISO timestamp of when the model was created */
|
||||||
|
created_at: string;
|
||||||
|
/** Model type classification */
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response structure from the Anthropic Models List API.
|
||||||
|
* Provides paginated list of available Claude models.
|
||||||
|
*/
|
||||||
|
export interface ModelsListResponse {
|
||||||
|
/** Array of available model information */
|
||||||
|
data: ModelInfo[];
|
||||||
|
/** ID of the first model in the list (for pagination) */
|
||||||
|
first_id: string;
|
||||||
|
/** Whether more models are available on subsequent pages */
|
||||||
|
has_more: boolean;
|
||||||
|
/** ID of the last model in the list (for pagination) */
|
||||||
|
last_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cached model list with timestamp for TTL-based expiry.
|
||||||
|
* Models are cached for 24 hours to reduce API calls while staying reasonably current.
|
||||||
|
*/
|
||||||
|
export interface ModelCache {
|
||||||
|
/** Array of cached model information */
|
||||||
|
models: ModelInfo[];
|
||||||
|
/** Unix timestamp (milliseconds) when this cache was created */
|
||||||
|
fetchedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hardcoded fallback list of known Claude models.
|
||||||
|
* Used when the Models API is unavailable or the API key is not configured.
|
||||||
|
*
|
||||||
|
* TODO: Keep this list updated with current models from:
|
||||||
|
* https://docs.anthropic.com/en/docs/about-claude/models
|
||||||
|
*
|
||||||
|
* Prefer "-latest" aliases where available for automatic updates.
|
||||||
|
*/
|
||||||
export const ANTHROPIC_MODELS = [
|
export const ANTHROPIC_MODELS = [
|
||||||
'claude-3-haiku-20240307',
|
// Current generation models (use -latest aliases where available)
|
||||||
'claude-3-sonnet-20240229',
|
'claude-sonnet-4-5-20250929',
|
||||||
'claude-3-opus-20240229',
|
'claude-haiku-4-5-20251001',
|
||||||
'claude-3-5-sonnet-20241022',
|
'claude-opus-4-1-20250805',
|
||||||
'claude-3-5-haiku-20241022'
|
// Legacy models
|
||||||
|
'claude-sonnet-4-20250514',
|
||||||
|
'claude-3-7-sonnet-latest',
|
||||||
|
'claude-opus-4-20250514',
|
||||||
|
'claude-3-5-haiku-latest',
|
||||||
|
'claude-3-haiku-20240307'
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type representing one of the hardcoded fallback model identifiers.
|
||||||
|
* This is a union type of all strings in the ANTHROPIC_MODELS array.
|
||||||
|
*/
|
||||||
export type AnthropicModel = typeof ANTHROPIC_MODELS[number];
|
export type AnthropicModel = typeof ANTHROPIC_MODELS[number];
|
||||||
+3
-1
@@ -1,3 +1,5 @@
|
|||||||
{
|
{
|
||||||
"1.0.0": "0.15.0"
|
"1.0.0": "0.15.0",
|
||||||
|
"1.1.1": "1.9.12",
|
||||||
|
"1.2.0": "1.9.12"
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user