Adds dynamic Claude model fetching and management #1
No files matched your search
@@ -4,20 +4,66 @@
|
|||||||
import { requestUrl } from 'obsidian';
|
import { requestUrl } from 'obsidian';
|
||||||
import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types';
|
import { AnthropicRequest, AnthropicResponse, 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;
|
||||||
|
/** Base URL for the Anthropic Messages API endpoint */
|
||||||
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
private messagesUrl = 'https://api.anthropic.com/v1/messages';
|
||||||
|
/** Base URL for the Anthropic Models API endpoint */
|
||||||
private modelsUrl = 'https://api.anthropic.com/v1/models';
|
private modelsUrl = 'https://api.anthropic.com/v1/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.)';
|
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';
|
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: string,
|
model: string,
|
||||||
@@ -60,6 +106,16 @@ export class AnthropicClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the list of available Claude models from the Anthropic API.
|
||||||
|
*
|
||||||
|
* This is used to populate the model selection dropdown in settings with
|
||||||
|
* current available models rather than relying solely on hardcoded lists.
|
||||||
|
* The response is cached by ModelService with a 24-hour TTL.
|
||||||
|
*
|
||||||
|
* @returns Response containing array of available models with metadata
|
||||||
|
* @throws Error if API key is missing, request fails, or response is malformed
|
||||||
|
*/
|
||||||
async fetchModels(): Promise<ModelsListResponse> {
|
async fetchModels(): Promise<ModelsListResponse> {
|
||||||
if (!this.apiKey) {
|
if (!this.apiKey) {
|
||||||
throw new Error('API key is required');
|
throw new Error('API key is required');
|
||||||
@@ -96,6 +152,16 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
// MARK: - Private Methods
|
// 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 {
|
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.`;
|
const baseMessage = `Generate exactly ${count} creative writing prompts. Return ONLY the numbered prompts with no additional text or commentary.`;
|
||||||
|
|
||||||
@@ -106,6 +172,16 @@ export class AnthropicClient {
|
|||||||
return `${baseMessage}\n\nProvide ${count} diverse writing 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({
|
||||||
@@ -132,6 +208,18 @@ 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');
|
||||||
@@ -161,14 +249,39 @@ export class AnthropicClient {
|
|||||||
|
|
||||||
// MARK: - Configuration Methods
|
// MARK: - Configuration Methods
|
||||||
|
|
||||||
|
/**
|
||||||
|
⚠️ Potential issue | 🔴 Critical 🧩 Analysis chainCritical: Pagination uses Anthropic’s models pagination uses Apply this diff: Please confirm param naming against current docs: 🌐 Web query: 💡 Result: Yes — the List Models endpoint uses the query parameter after_id (not after) for pagination. [1][2] Sources:
🏁 Script executed: Length of output: 0 🏁 Script executed: Length of output: 22 🏁 Script executed: Length of output: 976 🏁 Script executed: Length of output: 2700 Critical: Fix pagination parameter from Anthropic's List Models endpoint uses the query parameter 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🔴 Critical_
<details>
<summary>🧩 Analysis chain</summary>
**Critical: Pagination uses `after` instead of `after_id` — can cause infinite loop/duplicate pages.**
Anthropic’s models pagination uses `before_id`/`after_id`. Using `after` likely re-fetches the first page forever if `has_more` is true, looping and duplicating results.
Apply this diff:
```diff
- if (afterId) {
- params.set('after', afterId);
- }
+ if (afterId) {
+ params.set('after_id', afterId);
+ }
```
Please confirm param naming against current docs:
---
🌐 Web query:
```web
Does Anthropic's List Models endpoint use the query param name `after_id` (not `after`) for pagination?
```
💡 Result:
Yes — the List Models endpoint uses the query parameter after_id (not after) for pagination. [1][2]
Sources:
- Anthropic API — List Models documentation. [1]
- Claude (Anthropic) localized docs — List Models (shows after_id). [2]
---
🏁 Script executed:
```shell
#!/bin/bash
# Verify the pagination bug in api/anthropicClient.ts
fd api/anthropicClient.ts --exec cat {}
```
Length of output: 0
---
🏁 Script executed:
```shell
#!/bin/bash
# Search for anthropicClient file with broader pattern
fd -e ts anthropicClient
```
Length of output: 22
---
🏁 Script executed:
```shell
#!/bin/bash
# View the anthropicClient.ts file with line numbers, focusing on pagination section
cat -n api/anthropicClient.ts | sed -n '130,150p'
```
Length of output: 976
---
🏁 Script executed:
```shell
#!/bin/bash
# View complete pagination loop
cat -n api/anthropicClient.ts | sed -n '135,190p'
```
Length of output: 2700
---
</details>
**Critical: Fix pagination parameter from `after` to `after_id` at line 141.**
Anthropic's List Models endpoint uses the query parameter `after_id` (not `after`) for pagination. The current code at line 141 uses the incorrect parameter name, which will cause the API to ignore the pagination cursor and potentially loop indefinitely or return duplicate results.
```diff
if (afterId) {
- params.set('after', afterId);
+ params.set('after_id', afterId);
}
```
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
// Build URL with pagination parameters
// Use limit=1000 (Anthropic's max) to minimize round trips
const params = new URLSearchParams();
params.set('limit', '1000');
if (afterId) {
params.set('after_id', afterId);
}
const url = `${this.modelsUrl}?${params.toString()}`;
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In api/anthropicClient.ts around lines 136 to 144, the code sets the pagination
query parameter as 'after' which is incorrect for Anthropic's List Models
endpoint; change the parameter key to 'after_id' when afterId is present (i.e.,
params.set('after_id', afterId)) so the pagination cursor is passed correctly,
leaving the rest of the URL construction and limit=1000 logic unchanged.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits afa725d to 3f53bb5
|
|||||||
|
* 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<{
|
async testApiKey(model: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -218,6 +331,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;
|
||||||
|
|||||||
@@ -5,11 +5,46 @@ 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,
|
||||||
@@ -42,6 +77,20 @@ 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:
|
||||||
|
* - Adds newline before if cursor is on a line with content
|
||||||
|
* - Adds newline after if cursor is not at end of document
|
||||||
|
* - 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();
|
const cursor = editor.getCursor();
|
||||||
const currentLine = editor.getLine(cursor.line);
|
const currentLine = editor.getLine(cursor.line);
|
||||||
@@ -78,6 +127,24 @@ export class NotePromptsCommand {
|
|||||||
editor.setCursor(newCursorLine, newCursorCh);
|
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', {
|
const timestamp = new Date().toLocaleDateString('en-US', {
|
||||||
year: 'numeric',
|
year: 'numeric',
|
||||||
@@ -98,10 +165,31 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 } {
|
static getExecutionContext(app: App): { editor: Editor | null; view: MarkdownView | null } {
|
||||||
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
|
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
|
||||||
|
|
||||||
|
|||||||
@@ -5,16 +5,57 @@ import { Notice } from 'obsidian';
|
|||||||
import { PromptGeneratorService } from '../services/promptGenerator';
|
import { PromptGeneratorService } from '../services/promptGenerator';
|
||||||
|
⚠️ Potential issue | 🔴 Critical Fix inProgress lifecycle to avoid races (stop() resets it). execute() sets inProgress=true, then stop() immediately flips it back to false. A second execute can slip in while prompts are still generating. Reorder and remove the flag mutation from stop() so inProgress reliably guards concurrent runs. Also applies to: 101-116 🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🔴 Critical_
**Fix inProgress lifecycle to avoid races (stop() resets it).**
execute() sets inProgress=true, then stop() immediately flips it back to false. A second execute can slip in while prompts are still generating. Reorder and remove the flag mutation from stop() so inProgress reliably guards concurrent runs.
```diff
@@
- // Check if already in progress to prevent race conditions
+ // Check if already in progress to prevent race conditions
if (this.inProgress) {
new Notice('Timed prompts are already being generated. Please wait.');
return;
}
-
- this.inProgress = true;
-
- // Stop any existing timed sequence
- this.stop();
+ // Stop any existing timed sequence
+ this.stop();
+ // Mark as in-progress only after cleanup to prevent re-entry
+ this.inProgress = true;
@@
stop(): void {
if (this.activeInterval !== null) {
clearInterval(this.activeInterval);
this.activeInterval = null;
}
this.promptQueue = [];
this.currentIndex = 0;
- this.inProgress = false;
}
```
Also applies to: 101-116
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In commands/timedPrompts.ts around lines 60-67 (and similarly lines 101-116),
execute() sets this.inProgress = true but stop() immediately resets it to false,
allowing a second execute() to slip in during generation; remove the mutation of
this.inProgress from stop(), ensure execute() sets this.inProgress = true before
starting async work, and only reset this.inProgress = false after all generation
and cleanup have completed (use a finally block or end-of-flow path to guarantee
reset) so the flag reliably prevents concurrent runs.
```
</details>
<!-- fingerprinting:phantom:medusa:chinchilla -->
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits da6056b to 893aae5
|
|||||||
import { FreewritingPromptsSettings } from '../types';
|
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 {
|
export class TimedPromptsCommand {
|
||||||
|
/** Active interval ID from window.setInterval, null when not running */
|
||||||
private activeInterval: number | null = null;
|
private activeInterval: number | null = null;
|
||||||
|
/** Queue of prompts to display, loaded at command start */
|
||||||
private promptQueue: string[] = [];
|
private promptQueue: string[] = [];
|
||||||
|
/** Index of the currently displayed or next-to-display prompt */
|
||||||
private currentIndex = 0;
|
private currentIndex = 0;
|
||||||
|
/** Flag preventing concurrent command execution */
|
||||||
private inProgress = false;
|
private inProgress = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new timed 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 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 issues if the user triggers the command
|
||||||
|
* multiple times quickly while prompt generation is in progress.
|
||||||
|
*
|
||||||
|
* @param settings - Current plugin settings for generation parameters
|
||||||
|
*/
|
||||||
async execute(settings: FreewritingPromptsSettings): Promise<void> {
|
async execute(settings: FreewritingPromptsSettings): Promise<void> {
|
||||||
// Check if already in progress to prevent race conditions
|
// Check if already in progress to prevent race conditions
|
||||||
if (this.inProgress) {
|
if (this.inProgress) {
|
||||||
@@ -57,6 +98,13 @@ export class TimedPromptsCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
stop(): void {
|
stop(): void {
|
||||||
if (this.activeInterval !== null) {
|
if (this.activeInterval !== null) {
|
||||||
clearInterval(this.activeInterval);
|
clearInterval(this.activeInterval);
|
||||||
@@ -67,12 +115,26 @@ export class TimedPromptsCommand {
|
|||||||
this.inProgress = false;
|
this.inProgress = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a timed prompts sequence is currently running.
|
||||||
|
*
|
||||||
|
* @returns true if prompts are being displayed on an interval, false otherwise
|
||||||
|
*/
|
||||||
isRunning(): boolean {
|
isRunning(): boolean {
|
||||||
return this.activeInterval !== null;
|
return this.activeInterval !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
// 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 {
|
private startInterval(delaySeconds: number): void {
|
||||||
this.activeInterval = window.setInterval(() => {
|
this.activeInterval = window.setInterval(() => {
|
||||||
this.currentIndex++;
|
this.currentIndex++;
|
||||||
@@ -87,6 +149,19 @@ export class TimedPromptsCommand {
|
|||||||
}, delaySeconds * 1000);
|
}, delaySeconds * 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the current prompt as an Obsidian notice.
|
||||||
|
*
|
||||||
|
* The notification includes:
|
||||||
|
* - Current position in sequence (e.g., "3/10")
|
||||||
|
* - The prompt text
|
||||||
|
⚠️ Potential issue | 🟡 Minor Smoothen notification duration transition at 1-second boundary. The condition
Consider using Apply this diff: With this change:
📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟡 Minor_
**Smoothen notification duration transition at 1-second boundary.**
The condition `delayMs > 1000` creates a discontinuity:
- At 1000ms delay → 900ms notification
- At 1001ms delay → 501ms notification (~400ms jump)
Consider using `>=` instead to create a smoother transition:
Apply this diff:
```diff
- const notificationDuration =
- delayMs > 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
+ const notificationDuration =
+ delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
```
With this change:
- At 1000ms: 500ms notification (smooth)
- At 999ms: 899ms notification (capped)
- At 1001ms: 501ms notification (smooth)
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
// For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller)
// Clamp to minimum 300ms to prevent flicker/invisible notices
const delayMs = Math.max(0, delaySeconds * 1000);
const notificationDuration =
delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100));
```
</details>
<!-- suggestion_end -->
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In commands/timedPrompts.ts around lines 180 to 184, the ternary uses `delayMs >
1000` which creates a discontinuity at exactly 1000ms; change the condition to
`delayMs >= 1000` so the branch that computes the shorter notification duration
runs at 1000ms and smooths the transition, and update the adjacent comment to
reflect the new boundary behavior.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits d5af2a0 to 9b8ff31
|
|||||||
|
* - 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 {
|
private showCurrentPrompt(delaySeconds: number): void {
|
||||||
if (this.currentIndex < this.promptQueue.length) {
|
if (this.currentIndex < this.promptQueue.length) {
|
||||||
const prompt = this.promptQueue[this.currentIndex];
|
const prompt = this.promptQueue[this.currentIndex];
|
||||||
@@ -112,6 +187,14 @@ export class TimedPromptsCommand {
|
|||||||
|
|
||||||
// MARK: - Status Methods
|
// 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 } {
|
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
||||||
const totalPrompts = this.promptQueue.length;
|
const totalPrompts = this.promptQueue.length;
|
||||||
const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts);
|
const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts);
|
||||||
@@ -123,6 +206,13 @@ export class TimedPromptsCommand {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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[] {
|
getRemainingPrompts(): string[] {
|
||||||
if (this.currentIndex >= this.promptQueue.length) {
|
if (this.currentIndex >= this.promptQueue.length) {
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@@ -9,13 +9,43 @@ import { ModelService } from './services/modelService';
|
|||||||
import { TimedPromptsCommand } from './commands/timedPrompts';
|
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;
|
||||||
|
/** Service for managing available Claude models */
|
||||||
modelService: ModelService;
|
modelService: ModelService;
|
||||||
|
/** Command handler for timed prompt notifications */
|
||||||
timedCommand: TimedPromptsCommand;
|
timedCommand: TimedPromptsCommand;
|
||||||
|
/** Command handler for note prompt insertion */
|
||||||
noteCommand: NotePromptsCommand;
|
noteCommand: NotePromptsCommand;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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() {
|
||||||
// Load data once and use it for both settings and model cache
|
// Load data once and use it for both settings and model cache
|
||||||
const data = await this.loadData() as FreewritingPromptsData | null;
|
const data = await this.loadData() as FreewritingPromptsData | null;
|
||||||
@@ -39,6 +69,16 @@ 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 timed prompts
|
// Stop any running timed prompts
|
||||||
if (this.timedCommand) {
|
if (this.timedCommand) {
|
||||||
@@ -53,10 +93,23 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Settings Management
|
// MARK: - Settings Management
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads plugin settings from disk.
|
||||||
|
*
|
||||||
|
* Merges saved settings with defaults to ensure any new settings added
|
||||||
|
* in plugin updates have sensible default values.
|
||||||
|
*/
|
||||||
async loadSettings() {
|
async loadSettings() {
|
||||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
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() {
|
||||||
// Save settings with model cache
|
// Save settings with model cache
|
||||||
const data: FreewritingPromptsData = {
|
const data: FreewritingPromptsData = {
|
||||||
@@ -73,6 +126,16 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
|
|
||||||
// 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() {
|
||||||
// Timed prompts command
|
// Timed prompts command
|
||||||
this.addCommand({
|
this.addCommand({
|
||||||
@@ -104,6 +167,17 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Command Implementations
|
// MARK: - Command Implementations
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the timed prompts command.
|
||||||
|
*
|
||||||
|
* 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> {
|
private async executeTimedPrompts(): Promise<void> {
|
||||||
// Check if timed prompts are already running
|
// Check if timed prompts are already running
|
||||||
if (this.timedCommand.isRunning()) {
|
if (this.timedCommand.isRunning()) {
|
||||||
@@ -126,6 +200,20 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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)) {
|
||||||
@@ -148,6 +236,12 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the currently running timed prompts sequence.
|
||||||
|
*
|
||||||
|
* Checks if prompts are actually running before attempting to stop
|
||||||
|
* to provide appropriate feedback messages.
|
||||||
|
*/
|
||||||
private stopTimedPrompts(): void {
|
private stopTimedPrompts(): void {
|
||||||
if (this.timedCommand.isRunning()) {
|
if (this.timedCommand.isRunning()) {
|
||||||
this.timedCommand.stop();
|
this.timedCommand.stop();
|
||||||
@@ -159,6 +253,13 @@ export default class FreewritingPromptsPlugin extends Plugin {
|
|||||||
|
|
||||||
// MARK: - Public API for Settings
|
// MARK: - Public API for Settings
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 } {
|
getTimedStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
|
||||||
return this.timedCommand.getStatus();
|
return this.timedCommand.getStatus();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,41 @@ import { Notice } from 'obsidian';
|
|||||||
import { AnthropicClient } from '../api/anthropicClient';
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simplified model representation for UI display purposes.
|
||||||
|
* Used to populate dropdown menus with user-friendly model names.
|
||||||
|
*/
|
||||||
export interface ModelOption {
|
export interface ModelOption {
|
||||||
|
/** Model identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Human-readable display name for the UI */
|
||||||
displayName: string;
|
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 {
|
export class ModelService {
|
||||||
private anthropicClient: AnthropicClient;
|
private anthropicClient: AnthropicClient;
|
||||||
private modelCache: ModelCache | null = null;
|
private modelCache: ModelCache | null = null;
|
||||||
|
/** Cache time-to-live in milliseconds (24 hours) */
|
||||||
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new model service instance.
|
||||||
|
*
|
||||||
|
* @param anthropicClient - Client for making API requests to Anthropic
|
||||||
|
*/
|
||||||
constructor(anthropicClient: AnthropicClient) {
|
constructor(anthropicClient: AnthropicClient) {
|
||||||
this.anthropicClient = anthropicClient;
|
this.anthropicClient = anthropicClient;
|
||||||
}
|
}
|
||||||
@@ -22,9 +47,17 @@ export class ModelService {
|
|||||||
// MARK: - Public Methods
|
// MARK: - Public Methods
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get available models with caching and fallback logic
|
* Retrieves available Claude models with intelligent caching and fallback.
|
||||||
* Returns models from cache if valid, otherwise fetches from API
|
*
|
||||||
* Falls back to hardcoded list if API fails
|
* 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[]> {
|
async getAvailableModels(): Promise<ModelOption[]> {
|
||||||
// Check if we have a valid cache
|
// Check if we have a valid cache
|
||||||
@@ -50,8 +83,13 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Force refresh the model list from API
|
* Forces a refresh of the model list from the API, bypassing cache.
|
||||||
* Used when user changes API key
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @returns Array of current available models
|
||||||
*/
|
*/
|
||||||
async refreshModels(): Promise<ModelOption[]> {
|
async refreshModels(): Promise<ModelOption[]> {
|
||||||
// If no API key, quietly return fallback
|
// If no API key, quietly return fallback
|
||||||
@@ -71,21 +109,33 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load cache from plugin data
|
* 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 {
|
loadCache(cache: ModelCache | null): void {
|
||||||
this.modelCache = cache;
|
this.modelCache = cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current cache for saving to plugin data
|
* 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 {
|
getCache(): ModelCache | null {
|
||||||
return this.modelCache;
|
return this.modelCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear the cache (for testing or manual refresh)
|
* Clears the cached model list, forcing a fresh fetch on next access.
|
||||||
|
*
|
||||||
|
* Useful for testing or troubleshooting cache-related issues.
|
||||||
*/
|
*/
|
||||||
clearCache(): void {
|
clearCache(): void {
|
||||||
this.modelCache = null;
|
this.modelCache = null;
|
||||||
@@ -94,7 +144,13 @@ export class ModelService {
|
|||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the current cache is still valid (within TTL)
|
* 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 {
|
private isCacheValid(): boolean {
|
||||||
if (!this.modelCache) {
|
if (!this.modelCache) {
|
||||||
@@ -107,7 +163,11 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update cache with new model data
|
* Updates the cache with freshly fetched model data.
|
||||||
|
*
|
||||||
|
* 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 {
|
private updateCache(models: ModelInfo[]): void {
|
||||||
this.modelCache = {
|
this.modelCache = {
|
||||||
@@ -117,8 +177,14 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format ModelInfo array to ModelOption array for dropdown
|
* Transforms API model data into UI-friendly format.
|
||||||
* Uses display_name if available, otherwise falls back to id
|
*
|
||||||
|
* 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[] {
|
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||||
return models.map(model => ({
|
return models.map(model => ({
|
||||||
@@ -128,7 +194,13 @@ export class ModelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get fallback models from hardcoded list
|
* 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[] {
|
private getFallbackModels(): ModelOption[] {
|
||||||
return ANTHROPIC_MODELS.map(id => ({
|
return ANTHROPIC_MODELS.map(id => ({
|
||||||
|
|||||||
@@ -5,22 +5,58 @@ import { Notice } from 'obsidian';
|
|||||||
import { AnthropicClient } from '../api/anthropicClient';
|
import { AnthropicClient } from '../api/anthropicClient';
|
||||||
import { FreewritingPromptsSettings, GeneratedPrompt } 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();
|
||||||
|
/** 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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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[]> {
|
async generateTimedPrompts(settings: FreewritingPromptsSettings): Promise<string[]> {
|
||||||
return this.generatePrompts(
|
return this.generatePrompts(
|
||||||
settings.timedCount,
|
settings.timedCount,
|
||||||
@@ -31,6 +67,17 @@ export class PromptGeneratorService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,
|
||||||
@@ -41,17 +88,52 @@ export class PromptGeneratorService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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: string,
|
model: string,
|
||||||
@@ -95,6 +177,20 @@ export class PromptGeneratorService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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: string,
|
model: string,
|
||||||
@@ -112,6 +208,19 @@ 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) {
|
||||||
@@ -137,6 +246,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[] = [];
|
||||||
|
|
||||||
|
|||||||
@@ -6,27 +6,75 @@ import FreewritingPromptsPlugin from './main';
|
|||||||
import { FreewritingPromptsSettings } from './types';
|
import { FreewritingPromptsSettings } from './types';
|
||||||
import { ModelOption } from './services/modelService';
|
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: '',
|
||||||
|
/** Haiku is the fastest and most cost-effective model for prompt generation */
|
||||||
model: 'claude-3-5-haiku-latest' as const,
|
model: 'claude-3-5-haiku-latest' as const,
|
||||||
|
/** 10 prompts provides a good freewriting session length */
|
||||||
timedCount: 10,
|
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.',
|
||||||
|
/** Example demonstrating short, immediate style for timed prompts */
|
||||||
timedExamplePrompt: 'The interesting thing about a rose is…',
|
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
|
||||||
|
⚠️ Potential issue | 🟡 Minor Consider debouncing or using blur event for model refresh. Refreshing models on every keystroke while the user types their API key will trigger multiple unnecessary API calls (likely to fail with incomplete keys), degrading UX and potentially hitting rate limits. Consider one of these approaches: Option 1: Trigger on blur event Option 2: Debounce the refresh (requires a debounce utility function)
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟡 Minor_
**Consider debouncing or using blur event for model refresh.**
Refreshing models on every keystroke while the user types their API key will trigger multiple unnecessary API calls (likely to fail with incomplete keys), degrading UX and potentially hitting rate limits.
Consider one of these approaches:
**Option 1: Trigger on blur event**
```diff
.addText(text => text
.setPlaceholder('sk-ant-...')
.setValue(this.plugin.settings.apiKey)
.onChange(async (value) => {
this.plugin.settings.apiKey = value;
await this.plugin.saveSettings();
this.plugin.promptGenerator.updateApiKey(value);
-
- // Trigger model refresh when API key is entered
- if (value.trim().length > 0) {
- await this.refreshModels();
- }
}))
.then(setting => {
// Make it a password field
- setting.controlEl.querySelector('input')?.setAttribute('type', 'password');
+ const inputEl = setting.controlEl.querySelector('input');
+ inputEl?.setAttribute('type', 'password');
+ // Refresh models when user finishes entering API key
+ inputEl?.addEventListener('blur', async () => {
+ if (this.plugin.settings.apiKey.trim().length > 0) {
+ await this.refreshModels();
+ }
+ });
});
```
**Option 2: Debounce the refresh** (requires a debounce utility function)
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In settings.ts around lines 51-54, the current code calls refreshModels on every
keystroke which causes unnecessary API calls; change this to either trigger
refreshModels on the input's blur event (call once when the field loses focus if
the trimmed value is non-empty) or implement a debounce around refreshModels
(wrap it with a debounce utility, e.g., 300–500ms, call the debounced function
from the input change handler, and clear the timeout on component unmount).
Ensure the check for value.trim().length > 0 remains before calling the refresh
and that any existing timers are cleaned up to avoid leaks.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits e96ef65 to ee7faef
|
|||||||
|
* - 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;
|
private modelDropdown: DropdownComponent | null = null;
|
||||||
|
/** Cached list of available models for the dropdown */
|
||||||
private availableModels: ModelOption[] = [];
|
private availableModels: ModelOption[] = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
async display(): Promise<void> {
|
async display(): Promise<void> {
|
||||||
const { containerEl } = this;
|
const { containerEl } = this;
|
||||||
containerEl.empty();
|
containerEl.empty();
|
||||||
@@ -195,6 +243,13 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// MARK: - Model Loading
|
// 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> {
|
private async loadModels(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
this.availableModels = await this.plugin.modelService.getAvailableModels();
|
||||||
@@ -206,8 +261,14 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load models asynchronously without blocking UI rendering
|
* Loads models asynchronously without blocking UI rendering.
|
||||||
* Updates dropdown when models are fetched
|
*
|
||||||
|
* 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> {
|
private async loadModelsAsync(): Promise<void> {
|
||||||
await this.loadModels();
|
await this.loadModels();
|
||||||
@@ -233,6 +294,15 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
private populateModelDropdown(dropdown: DropdownComponent): void {
|
||||||
if (this.availableModels.length === 0) {
|
if (this.availableModels.length === 0) {
|
||||||
// No models available yet, disable dropdown
|
// No models available yet, disable dropdown
|
||||||
@@ -252,6 +322,16 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
dropdown.setDisabled(false);
|
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> {
|
private async refreshModels(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// Disable dropdown during refresh
|
// Disable dropdown during refresh
|
||||||
@@ -294,6 +374,20 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab {
|
|||||||
|
|
||||||
// MARK: - API Testing
|
// MARK: - API Testing
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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> {
|
private async testApiKey(button: ButtonComponent): Promise<void> {
|
||||||
const originalText = button.buttonEl.textContent || 'Test Connection';
|
const originalText = button.buttonEl.textContent || 'Test Connection';
|
||||||
|
|
||||||
|
|||||||
@@ -1,77 +1,160 @@
|
|||||||
// 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 to document intent that this should be a Claude model ID
|
/**
|
||||||
|
* 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;
|
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;
|
||||||
|
/** Claude model ID to use for prompt generation (e.g., 'claude-3-5-haiku-latest') */
|
||||||
model: ModelId; // Changed from AnthropicModel to string to support dynamic models
|
model: ModelId; // Changed from AnthropicModel to string to support dynamic models
|
||||||
|
/** Number of prompts to generate for timed notifications (1-50) */
|
||||||
timedCount: number;
|
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;
|
||||||
|
/** Example prompt that demonstrates the desired style for timed prompts */
|
||||||
timedExamplePrompt: string;
|
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 {
|
export interface FreewritingPromptsData extends FreewritingPromptsSettings {
|
||||||
|
/** Optional cached model list with 24-hour TTL to reduce API calls */
|
||||||
modelCache?: ModelCache;
|
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 identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
model: string;
|
model: string;
|
||||||
|
/** 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 {
|
export interface ModelInfo {
|
||||||
|
/** Unique model identifier (e.g., 'claude-3-5-haiku-latest') */
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Human-readable model name for display purposes */
|
||||||
display_name?: string;
|
display_name?: string;
|
||||||
|
/** ISO timestamp of when the model was created */
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
/** Model type classification */
|
||||||
type: string;
|
type: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response structure from the Anthropic Models List API.
|
||||||
|
* Provides paginated list of available Claude models.
|
||||||
|
*/
|
||||||
export interface ModelsListResponse {
|
export interface ModelsListResponse {
|
||||||
|
/** Array of available model information */
|
||||||
data: ModelInfo[];
|
data: ModelInfo[];
|
||||||
|
/** ID of the first model in the list (for pagination) */
|
||||||
first_id: string;
|
first_id: string;
|
||||||
|
/** Whether more models are available on subsequent pages */
|
||||||
has_more: boolean;
|
has_more: boolean;
|
||||||
|
/** ID of the last model in the list (for pagination) */
|
||||||
last_id: string;
|
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 {
|
export interface ModelCache {
|
||||||
|
/** Array of cached model information */
|
||||||
models: ModelInfo[];
|
models: ModelInfo[];
|
||||||
|
/** Unix timestamp (milliseconds) when this cache was created */
|
||||||
fetchedAt: number;
|
fetchedAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hardcoded fallback list of known Claude models.
|
||||||
|
* Used when the Models API is unavailable or the API key is not configured.
|
||||||
|
* This list should be updated periodically as new models are released.
|
||||||
|
*/
|
||||||
export const ANTHROPIC_MODELS = [
|
export const ANTHROPIC_MODELS = [
|
||||||
'claude-opus-4-1-20250805',
|
'claude-opus-4-1-20250805',
|
||||||
'claude-opus-4-20250514',
|
'claude-opus-4-20250514',
|
||||||
@@ -81,4 +164,8 @@ export const ANTHROPIC_MODELS = [
|
|||||||
'claude-3-haiku-20240307'
|
'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];
|
||||||
⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Pagination is not handled for model listing.
The
ModelsListResponseinterface includeshas_more,first_id, andlast_idfields that indicate pagination support, butfetchModels()only retrieves the first page of results. If Anthropic returns more than one page of models, subsequent pages are silently ignored.Verify whether pagination is needed:
If pagination is required, consider implementing it or documenting the limitation. Otherwise, if all Claude models fit in a single page, add a comment explaining why pagination isn't needed.
🏁 Script executed:
Length of output: 128
I'll verify whether pagination is actually used or documented elsewhere in the codebase.
Length of output: 1321
🏁 Script executed:
Length of output: 2163
🌐 Web query:
💡 Result:
By default the List Models endpoint returns 20 models per page. You can set the query param limit to any integer 1–1000 to change this. Pagination uses before_id / after_id with has_more, first_id and last_id in the response. [1]
Implement pagination in
fetchModels()or document why it's not needed.Verification confirms the issue: The
ModelsListResponseinterface includes pagination fields, but the implementation only retrieves the first page. Anthropic's models API endpoint returns 20 models per page by default, and pagination fields are never used anywhere in the codebase. If Anthropic returns more than 20 models, subsequent pages are silently ignored.Either:
has_more,last_id)🤖 Prompt for AI Agents
✅ Addressed in commits
e96ef65toee7faef