11 Commits
Author SHA1 Message Date
olivier cd054af076 chore: bump to v1.4.0 2026-10-12 16:29:02 -04:00
olivier 564e3ea8b3 feat: model prices and latency in browser, Waypoint-style settings tabs
- Model browser: per-million input/output price on every row; time to first token (p50) and tokens/s for the busiest OpenRouter provider, fetched lazily for visible rows and cached 10 minutes.
- Fix: Free badge and free-first sorting (prices are strings), and the list was empty until typing.
- Settings: text-only tabs styled like Waypoint's; drop the heading that repeated the tab name.
2026-10-12 16:28:59 -04:00
olivier b4d962047b chore: bump to v1.3.0 2026-10-12 13:32:59 -04:00
olivier f66d45db68 feat: keychain secret picker, proofreading timing and reasoning controls
- API keys: pick an existing Obsidian keychain secret per provider (SecretComponent); data.json stores only the secret name and keys are read at call time. One-time migration links the old fixed-name secrets and drops legacy fields; no more writing empty secrets on every save.
- AIService: treat max-token truncation and empty content as errors instead of crashing on null.trim() or replacing text with a truncated answer.
- Proofreading: live elapsed-time notice, then a summary with model, upstream host and prompt/output/reasoning tokens.
- Proofreading (OpenRouter): Reasoning toggle and Effort setting, default off/low.
2026-10-12 13:32:53 -04:00
olivier bf27867d20 chore: bump to v1.2.1 2026-09-14 20:06:58 -04:00
olivier e2c4a5264c fix: check API key before starting recording
Previously the API key was only validated after stopping the
recording, wasting a full take if no key was configured. Now
startRecording() checks the transcription provider's API key
up front and aborts with a notice before touching the mic.
2026-09-14 20:06:45 -04:00
olivier c6a98d4050 chore: bump to v1.2.0 2026-09-07 17:22:33 -04:00
olivier 9b7ec36828 Unify AI provider selection across all features
Every LLM-backed feature (Post-Processing, Proofreading, Title
Generation, Property Filler) now reads from one CHAT_PROVIDERS
registry instead of 5 hand-duplicated provider lists, so they always
offer the exact same providers in the exact same order.

- Add Groq as a 5th chat-completion provider (was transcription-only
  despite its OpenAI-compatible API and an already-collected key).
- Provider dropdowns disable options with no API key configured
  (shown as e.g. "Anthropic (no API key)") instead of silently
  failing at runtime when picked.
- Collapse 3 byte-for-byte duplicated resolveProvider() methods
  (Proofreader, TitleGenerator, PropertyFiller) plus AudioHandler's
  getPostProcessingApiKey() into one resolveChatProvider() helper
  (src/ProviderResolver.ts).
- Fix Custom provider: previously Proofreading/Title/Property silently
  reused Post-Processing's postProcessingUrl with no visible field to
  set it. Renamed to a shared customApiUrl field with its own UI
  (createCustomProviderFields), now exposed on every tab that offers
  Custom, plus rows on the API Keys tab. Migrates old data.json values
  automatically.
- Update README settings reference and getting-started sections to
  match.

No behavior change for existing single-provider setups; migration
handles the postProcessingUrl -> customApiUrl rename transparently.
2026-09-07 17:14:33 -04:00
olivier 3abd9d9b3b chore: bump to v1.1.0 2026-08-10 19:58:41 -04:00
olivier d1f760cd2c feat: show recording input meter 2026-08-10 19:53:55 -04:00
olivier 8caa86753b chore: bump to v1.0.1 2026-05-24 21:46:17 -04:00
17 changed files with 889 additions and 401 deletions

No files matched your search

+24 -9
View File
@@ -26,6 +26,7 @@ Fix punctuation and grammar of selected text with a single command or right-clic
- **Prompt injection resistant** — the built-in system prompt explicitly guards against prompt injection attacks in the text being proofread - **Prompt injection resistant** — the built-in system prompt explicitly guards against prompt injection attacks in the text being proofread
- **Smart quote replacement** — straight quotes → curly quotes (except in code blocks) - **Smart quote replacement** — straight quotes → curly quotes (except in code blocks)
- **Timing and token report** — a live timer runs while the model works; when done, a notice shows elapsed time, model, upstream host (OpenRouter), and prompt/output/reasoning token counts (also logged to the console)
- Works with any OpenAI-compatible provider (OpenRouter, OpenAI, etc.) - Works with any OpenAI-compatible provider (OpenRouter, OpenAI, etc.)
### 🏷️ Title Generation ### 🏷️ Title Generation
@@ -71,15 +72,19 @@ Then copy the `main.js`, `manifest.json`, and `styles.css` to your vault's plugi
## Getting Started ## Getting Started
### 1. Configure API Keys ### 1. Configure API Keys
Open **Settings** → **NibbleAI** and add at least one API key: Open **Settings** → **NibbleAI** and, for at least one provider, pick the secret holding its key from Obsidian's keychain (**Settings** → **Keychain**):
| Key | Used For | | Key | Used For |
|-----|----------| |-----|----------|
| **Transcription API Key** | Whisper transcription (OpenAI, Groq, Azure) | | **Groq API Key** | Whisper transcription, and as a chat provider for proofreading/title/property/post-processing |
| **OpenAI API Key** | Proofreading, title generation, property filling, post-processing *(recommended: OpenRouter)* | | **OpenAI API Key** | Whisper transcription, and as a chat provider for proofreading/title/property/post-processing |
| **Anthropic API Key** | Post-processing with Claude models | | **Anthropic API Key** | Claude models for proofreading/title/property/post-processing |
| **OpenRouter API Key** | Access to hundreds of models for proofreading/title/property/post-processing |
| **Custom API Key + URL** | Any OpenAI-compatible endpoint (self-hosted, Azure, etc.) |
> **Tip:** For proofreading, title generation, and property filling, an [OpenRouter](https://openrouter.ai/keys) API key with a free model like `google/gemini-2.5-flash-lite` costs nothing and works great. Every LLM-backed feature (Proofreading, Title Generation, Property Filler, Post-Processing) shows the same provider dropdown — pick any provider that has a key configured above.
> **Tip:** An [OpenRouter](https://openrouter.ai/keys) API key with a free model like `google/gemini-2.5-flash-lite` costs nothing and works great across all four AI features.
### 2. Try the Features ### 2. Try the Features
@@ -128,10 +133,12 @@ This is useful for automation tools, Stream Deck, or scripting.
## Model Selection ## Model Selection
Wherever you need to select an AI model (post-processing, proofreading, title generation), NibbleAI provides a **Browse models** button that opens a searchable dialog of available OpenRouter models: Wherever you need to select an AI model (post-processing, proofreading, title generation, property filler), NibbleAI provides a **Browse** button that opens a searchable dialog of available OpenRouter models:
- Models are fetched live from `openrouter.ai/api/v1/models` - Models are fetched live from `openrouter.ai/api/v1/models`
- Free models appear first (marked with a **Free** badge) - Free models appear first (marked with a **Free** badge)
- Each row shows the price per million input/output tokens
- With an OpenRouter key configured, each visible row also shows time to first token (p50) and output speed (tokens/s) over the last 30 minutes, for the provider that served the most requests. Loaded once you stop typing; cached for 10 minutes
- Type to filter by name, ID, or description - Type to filter by name, ID, or description
- You can still type a model ID manually if you prefer - You can still type a model ID manually if you prefer
@@ -140,7 +147,7 @@ Wherever you need to select an AI model (post-processing, proofreading, title ge
## Settings Reference ## Settings Reference
### API Keys ### API Keys
Securely stored in your system keychain via Obsidian's SecretStorage. Never written to `data.json`. Keys live in Obsidian's keychain (SecretStorage). NibbleAI stores only the name of the secret you picked for each provider in `data.json`, and reads the key at the moment it calls the API, so a key rotated in the keychain applies immediately. Upgrading from ≤ 1.2.1 links the previously used `groq-api-key`, `openai-api-key`, `anthropic-api-key`, `openrouter-api-key` and `custom-api-key` secrets automatically.
### Transcription ### Transcription
| Setting | Default | Description | | Setting | Default | Description |
@@ -172,27 +179,34 @@ Securely stored in your system keychain via Obsidian's SecretStorage. Never writ
| Setting | Default | Description | | Setting | Default | Description |
|---------|---------|-------------| |---------|---------|-------------|
| Enable | Off | Clean up transcripts with an LLM | | Enable | Off | Clean up transcripts with an LLM |
| Provider | Anthropic | Anthropic, OpenAI, or Custom | | Provider | Anthropic | Any configured provider: Anthropic, OpenAI, Groq, OpenRouter, or Custom |
| Model | `claude-sonnet-4-20250514` | LLM for cleanup | | Model | `claude-sonnet-4-20250514` | LLM for cleanup |
| Auto-generate title | Off | Create filenames from content | | Auto-generate title | Off | Create filenames from content |
### Proofreading ### Proofreading
| Setting | Default | Description | | Setting | Default | Description |
|---------|---------|-------------| |---------|---------|-------------|
| Provider | OpenRouter | Any configured provider: Anthropic, OpenAI, Groq, OpenRouter, or Custom |
| Model | `openai/gpt-4o-mini` | Model for proofreading | | Model | `openai/gpt-4o-mini` | Model for proofreading |
| Temperature | `0.2` | Lower = more consistent | | Temperature | `0.2` | Lower = more consistent |
| Max tokens | `2000` | Maximum response length | | Max tokens | `2000` | Maximum response length |
| Reasoning | Off | OpenRouter only. Let the model think before answering; slower and uses more tokens |
| Effort | Low | OpenRouter only. Output effort (`verbosity`); with reasoning on, also reasoning depth |
| System prompt | *(built-in)* | Editable with prompt injection protections | | System prompt | *(built-in)* | Editable with prompt injection protections |
### Title Generation ### Title Generation
| Setting | Default | Description | | Setting | Default | Description |
|---------|---------|-------------| |---------|---------|-------------|
| Provider | OpenRouter | Any configured provider: Anthropic, OpenAI, Groq, OpenRouter, or Custom |
| Model | `openai/gpt-4o-mini` | Model for generating titles |
| Mode | Rename file | Rename file or set frontmatter property | | Mode | Rename file | Rename file or set frontmatter property |
| Max title length | 8 words | Maximum words in generated title | | Max title length | 8 words | Maximum words in generated title |
### Property Filler ### Property Filler
| Setting | Default | Description | | Setting | Default | Description |
|---------|---------|-------------| |---------|---------|-------------|
| Provider | OpenRouter | Any configured provider: Anthropic, OpenAI, Groq, OpenRouter, or Custom |
| Model | `openai/gpt-4o-mini` | Model for generating property values |
| Custom prompt | *(built-in)* | Template with `{property}` placeholder | | Custom prompt | *(built-in)* | Template with `{property}` placeholder |
| Overwrite existing | Off | Replace existing property values | | Overwrite existing | Off | Replace existing property values |
@@ -205,7 +219,8 @@ NibbleAI/
├── main.ts # Plugin entry point, commands, events ├── main.ts # Plugin entry point, commands, events
├── src/ ├── src/
│ ├── SettingsManager.ts # Settings + SecretStorage management │ ├── SettingsManager.ts # Settings + SecretStorage management
│ ├── AIService.ts # Unified AI client (OpenAI + Anthropic) │ ├── AIService.ts # Unified AI client (OpenAI-compatible + Anthropic-native)
│ ├── ProviderResolver.ts # Shared provider → API key/endpoint resolution
│ ├── ModelBrowser.ts # OpenRouter model suggest modal │ ├── ModelBrowser.ts # OpenRouter model suggest modal
│ ├── PostProcessor.ts # LLM post-processing for transcripts │ ├── PostProcessor.ts # LLM post-processing for transcripts
│ ├── NibbleAISettingsTab.ts # Settings UI │ ├── NibbleAISettingsTab.ts # Settings UI
+7
View File
@@ -43,6 +43,9 @@ export default class NibbleAI extends Plugin {
this.recorder.setDeviceId(deviceId); this.recorder.setDeviceId(deviceId);
this.statusBar = new StatusBar(this); this.statusBar = new StatusBar(this);
this.recorder.setInputLevelCallback((level) => {
this.statusBar.updateInputLevel(level);
});
this.proofreader = new Proofreader(this); this.proofreader = new Proofreader(this);
this.titleGenerator = new TitleGenerator(this); this.titleGenerator = new TitleGenerator(this);
@@ -86,6 +89,10 @@ export default class NibbleAI extends Plugin {
new Notice("Already recording"); new Notice("Already recording");
return; return;
} }
if (!this.audioHandler.getTranscriptionApiKey()) {
new Notice("✘ Add your API key for the selected transcription provider in NibbleAI settings");
return;
}
try { try {
await this.recorder.startRecording(); await this.recorder.startRecording();
this.statusBar.updateStatus(RecordingStatus.Recording); this.statusBar.updateStatus(RecordingStatus.Recording);
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"id": "nibbleai", "id": "nibbleai",
"name": "NibbleAI", "name": "NibbleAI",
"version": "1.0.0", "version": "1.4.0",
"minAppVersion": "1.12.7", "minAppVersion": "1.12.7",
"description": "AI-powered tools for your Obsidian vault: speech-to-text, proofreading, title generation, property filling, and more.", "description": "AI-powered tools for your Obsidian vault: speech-to-text, proofreading, title generation, property filling, and more.",
"author": "Olivier", "author": "Olivier",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "nibbleai", "name": "nibbleai",
"version": "1.0.0", "version": "1.4.0",
"description": "AI-powered tools for your Obsidian vault", "description": "AI-powered tools for your Obsidian vault",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
+79 -10
View File
@@ -1,15 +1,43 @@
import axios from "axios"; import axios from "axios";
import { PostProcessingProvider } from "./SettingsManager"; import { PostProcessingProvider, ReasoningEffort } from "./SettingsManager";
export interface ChatCompletionOptions { export interface ChatCompletionOptions {
apiKey: string; apiKey: string;
model: string; model: string;
endpoint?: string; endpoint?: string;
provider?: "anthropic" | "openai" | "openrouter" | "custom"; provider?: "anthropic" | "openai" | "openrouter" | "groq" | "custom";
temperature?: number; temperature?: number;
maxTokens?: number; maxTokens?: number;
/**
* OpenRouter only: reasoning on/off plus effort. Effort maps to
* `verbosity` (Anthropic's output effort) and, when reasoning is on, to
* `reasoning.effort`. `reasoning.effort` alone would turn reasoning on.
*/
reasoning?: { enabled: boolean; effort: ReasoningEffort };
} }
export interface ChatCompletionResult {
text: string;
/** Upstream host that served the request (OpenRouter only, e.g. "CoreWeave"). */
upstream?: string;
/** Token counts as reported by the API; absent when the API omits usage. */
usage?: {
promptTokens: number;
completionTokens: number;
/** Part of `completionTokens` spent thinking, when the API reports it. */
reasoningTokens?: number;
};
}
/**
* Shown when the response stops at max_tokens. A cut-off answer is never
* usable (proofreading would replace the selection with a truncated copy),
* and reasoning models spend this budget on thinking too, which can leave
* no tokens for the answer at all.
*/
const TRUNCATED_HINT =
"Try less text, a higher Max tokens (Proofreading settings), or a non-reasoning model.";
/** /**
* Unified AI service for all NibbleAI modules. * Unified AI service for all NibbleAI modules.
* Supports OpenAI-compatible chat completions and Anthropic native API. * Supports OpenAI-compatible chat completions and Anthropic native API.
@@ -20,13 +48,13 @@ export class AIService {
* @param userMessage - The user's input text * @param userMessage - The user's input text
* @param systemPrompt - System-level instructions * @param systemPrompt - System-level instructions
* @param options - API configuration * @param options - API configuration
* @returns The model's response text * @returns The model's response text, plus token usage and upstream host
*/ */
static async callChatCompletion( static async callChatCompletion(
userMessage: string, userMessage: string,
systemPrompt: string, systemPrompt: string,
options: ChatCompletionOptions options: ChatCompletionOptions
): Promise<string> { ): Promise<ChatCompletionResult> {
const provider = options.provider || "openai"; const provider = options.provider || "openai";
const endpoint = const endpoint =
options.endpoint || "https://openrouter.ai/api/v1/chat/completions"; options.endpoint || "https://openrouter.ai/api/v1/chat/completions";
@@ -45,7 +73,8 @@ export class AIService {
userMessage: string, userMessage: string,
systemPrompt: string, systemPrompt: string,
options: ChatCompletionOptions options: ChatCompletionOptions
): Promise<string> { ): Promise<ChatCompletionResult> {
const maxTokens = options.maxTokens ?? 2000;
const response = await axios.post( const response = await axios.post(
options.endpoint || options.endpoint ||
"https://openrouter.ai/api/v1/chat/completions", "https://openrouter.ai/api/v1/chat/completions",
@@ -56,7 +85,15 @@ export class AIService {
{ role: "user", content: userMessage }, { role: "user", content: userMessage },
], ],
temperature: options.temperature ?? 0.3, temperature: options.temperature ?? 0.3,
max_tokens: options.maxTokens ?? 2000, max_tokens: maxTokens,
...(options.reasoning && options.provider === "openrouter"
? {
reasoning: options.reasoning.enabled
? { effort: options.reasoning.effort }
: { enabled: false },
verbosity: options.reasoning.effort,
}
: {}),
}, },
{ {
headers: { headers: {
@@ -71,19 +108,39 @@ export class AIService {
}, },
} }
); );
return response.data.choices[0].message.content.trim(); const choice = response.data.choices[0];
if (choice.finish_reason === "length") {
throw new Error(
`${options.model} hit its ${maxTokens}-token limit before finishing. ${TRUNCATED_HINT}`
);
}
const content: string | null = choice.message.content;
if (!content) {
throw new Error(`Model returned no text (finish reason: ${choice.finish_reason}).`);
}
const usage = response.data.usage;
return {
text: content.trim(),
upstream: response.data.provider,
usage: usage && {
promptTokens: usage.prompt_tokens,
completionTokens: usage.completion_tokens,
reasoningTokens: usage.completion_tokens_details?.reasoning_tokens,
},
};
} }
private static async callAnthropic( private static async callAnthropic(
userMessage: string, userMessage: string,
systemPrompt: string, systemPrompt: string,
options: ChatCompletionOptions options: ChatCompletionOptions
): Promise<string> { ): Promise<ChatCompletionResult> {
const maxTokens = options.maxTokens ?? 8192;
const response = await axios.post( const response = await axios.post(
options.endpoint || "https://api.anthropic.com/v1/messages", options.endpoint || "https://api.anthropic.com/v1/messages",
{ {
model: options.model, model: options.model,
max_tokens: options.maxTokens ?? 8192, max_tokens: maxTokens,
system: systemPrompt, system: systemPrompt,
messages: [{ role: "user", content: userMessage }], messages: [{ role: "user", content: userMessage }],
}, },
@@ -96,6 +153,18 @@ export class AIService {
}, },
} }
); );
return response.data.content[0].text; if (response.data.stop_reason === "max_tokens") {
throw new Error(
`${options.model} hit its ${maxTokens}-token limit before finishing. ${TRUNCATED_HINT}`
);
}
const usage = response.data.usage;
return {
text: response.data.content[0].text,
usage: usage && {
promptTokens: usage.input_tokens,
completionTokens: usage.output_tokens,
},
};
} }
} }
+150 -23
View File
@@ -4,9 +4,69 @@ interface OpenRouterModel {
id: string; id: string;
name: string; name: string;
description?: string; description?: string;
/** USD per token, as decimal strings (e.g. "0.0000001"); "-1" means variable. */
pricing?: { pricing?: {
prompt: number; prompt: string;
completion: number; completion: string;
};
}
interface Percentiles {
p50: number;
}
interface OpenRouterEndpoint {
provider_name: string;
latency_last_30m: Percentiles | null;
throughput_last_30m: Percentiles | null;
perf_last_30m_by_workload?: {
text_generation?: { request_count?: number };
};
}
interface ModelPerf {
provider: string;
/** Time to first token, p50, in ms. */
latencyMs: number;
/** Output tokens per second, p50. */
tokensPerSecond: number | null;
}
/** OpenRouter's stats cover the last 30 minutes; reuse them for a while across modal openings. */
const PERF_TTL_MS = 10 * 60 * 1000;
const PERF_DEBOUNCE_MS = 300;
const PERF_CONCURRENCY = 6;
const perfCache = new Map<string, { at: number; perf: ModelPerf | null }>();
/** "$0.10" for a per-token price string, scaled to per million tokens. */
function formatPerMillion(perToken: string): string {
const perMillion = parseFloat(perToken) * 1_000_000;
if (perMillion >= 1) return `$${perMillion.toFixed(2)}`;
return `$${perMillion.toPrecision(2)}`;
}
/**
* Picks the endpoint that served the most requests, the one OpenRouter
* most likely routes to, among those reporting latency.
*/
async function fetchPerf(modelId: string, apiKey: string): Promise<ModelPerf | null> {
const resp = await fetch(`https://openrouter.ai/api/v1/models/${modelId}/endpoints`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
if (!resp.ok) return null;
const endpoints: OpenRouterEndpoint[] = (await resp.json()).data?.endpoints ?? [];
const busiest = endpoints
.filter((e) => e.latency_last_30m)
.sort(
(a, b) =>
(b.perf_last_30m_by_workload?.text_generation?.request_count ?? 0) -
(a.perf_last_30m_by_workload?.text_generation?.request_count ?? 0)
)[0];
if (!busiest?.latency_last_30m) return null;
return {
provider: busiest.provider_name,
latencyMs: busiest.latency_last_30m.p50,
tokensPerSecond: busiest.throughput_last_30m?.p50 ?? null,
}; };
} }
@@ -14,9 +74,15 @@ export class ModelSuggestModal extends SuggestModal<OpenRouterModel> {
private allModels: OpenRouterModel[] = []; private allModels: OpenRouterModel[] = [];
private cached = false; private cached = false;
private onChoose: (modelId: string) => void; private onChoose: (modelId: string) => void;
/** Latency needs an OpenRouter key; without one, rows show price only. */
private apiKey: string;
/** Perf elements of the latest render pass, filled in once stats arrive. */
private perfEls = new Map<string, HTMLElement>();
private perfTimer: number | null = null;
constructor(app: App, onChoose: (modelId: string) => void) { constructor(app: App, apiKey: string, onChoose: (modelId: string) => void) {
super(app); super(app);
this.apiKey = apiKey;
this.onChoose = onChoose; this.onChoose = onChoose;
this.setPlaceholder("Search OpenRouter models..."); this.setPlaceholder("Search OpenRouter models...");
this.setInstructions([ this.setInstructions([
@@ -35,18 +101,34 @@ export class ModelSuggestModal extends SuggestModal<OpenRouterModel> {
this.allModels = (data.data || []) this.allModels = (data.data || [])
.filter((m: OpenRouterModel) => m.id && !m.id.includes(":")) .filter((m: OpenRouterModel) => m.id && !m.id.includes(":"))
.sort((a: OpenRouterModel, b: OpenRouterModel) => { .sort((a: OpenRouterModel, b: OpenRouterModel) => {
const aFree = a.pricing?.prompt === 0 ? 0 : 1; const aFree = this.isFree(a) ? 0 : 1;
const bFree = b.pricing?.prompt === 0 ? 0 : 1; const bFree = this.isFree(b) ? 0 : 1;
if (aFree !== bFree) return aFree - bFree; if (aFree !== bFree) return aFree - bFree;
return (a.name || a.id).localeCompare(b.name || b.id); return (a.name || a.id).localeCompare(b.name || b.id);
}); });
this.cached = true; this.cached = true;
// The modal rendered its (empty) list before the fetch finished.
this.inputEl.dispatchEvent(new Event("input"));
} catch (e) { } catch (e) {
// Silently fail — the text input still works for manual entry // Silently fail — the text input still works for manual entry
} }
} }
onClose() {
if (this.perfTimer !== null) window.clearTimeout(this.perfTimer);
this.perfEls.clear();
}
private isFree(model: OpenRouterModel): boolean {
return (
parseFloat(model.pricing?.prompt ?? "") === 0 &&
parseFloat(model.pricing?.completion ?? "") === 0
);
}
getSuggestions(query: string): OpenRouterModel[] { getSuggestions(query: string): OpenRouterModel[] {
// A new render pass starts; stats for rows no longer shown aren't needed.
this.perfEls.clear();
const q = query.toLowerCase().trim(); const q = query.toLowerCase().trim();
if (!q) return this.allModels.slice(0, 50); if (!q) return this.allModels.slice(0, 50);
return this.allModels return this.allModels
@@ -64,31 +146,76 @@ export class ModelSuggestModal extends SuggestModal<OpenRouterModel> {
const nameEl = container.createDiv({ cls: "model-suggestion-name" }); const nameEl = container.createDiv({ cls: "model-suggestion-name" });
nameEl.setText(model.name || model.id); nameEl.setText(model.name || model.id);
const idEl = container.createDiv({ cls: "model-suggestion-id" }); if (this.isFree(model)) {
idEl.setText(model.id); nameEl.createSpan({ cls: "model-suggestion-badge", text: "Free" });
idEl.style.fontSize = "0.8em"; }
idEl.style.opacity = "0.6";
if (model.pricing?.prompt === 0 && model.pricing?.completion === 0) { container.createDiv({ cls: "model-suggestion-id", text: model.id });
const badge = container.createSpan({ cls: "model-suggestion-badge" });
badge.setText("Free"); const stats = container.createDiv({ cls: "model-suggestion-stats" });
badge.style.marginLeft = "8px"; const price = model.pricing;
badge.style.padding = "0 6px"; if (price && !this.isFree(model)) {
badge.style.borderRadius = "4px"; stats.createSpan({
badge.style.backgroundColor = "var(--color-green)"; text:
badge.style.color = "var(--text-on-accent)"; parseFloat(price.prompt) < 0
badge.style.fontSize = "0.75em"; ? "Variable price"
: `${formatPerMillion(price.prompt)} in · ${formatPerMillion(price.completion)} out per M tokens`,
});
}
if (this.apiKey) {
const perfEl = stats.createSpan({ cls: "model-suggestion-perf" });
const hit = perfCache.get(model.id);
if (hit && Date.now() - hit.at < PERF_TTL_MS) {
this.showPerf(perfEl, hit.perf);
} else {
perfEl.setText("latency…");
this.perfEls.set(model.id, perfEl);
this.schedulePerfFetch();
}
} }
if (model.description) { if (model.description) {
const descEl = container.createDiv({ cls: "model-suggestion-desc" }); container.createDiv({
descEl.setText(model.description.slice(0, 120)); cls: "model-suggestion-desc",
descEl.style.fontSize = "0.75em"; text: model.description.slice(0, 120),
descEl.style.opacity = "0.5"; });
} }
} }
private showPerf(el: HTMLElement, perf: ModelPerf | null) {
if (!perf) {
el.setText("no latency data");
return;
}
const firstToken = `first token ${(perf.latencyMs / 1000).toFixed(1)} s`;
const speed = perf.tokensPerSecond ? ` · ${Math.round(perf.tokensPerSecond)} tok/s` : "";
el.setText(`${firstToken}${speed} (${perf.provider})`);
}
/** Waits for typing to pause so each keystroke doesn't fire ~50 requests. */
private schedulePerfFetch() {
if (this.perfTimer !== null) window.clearTimeout(this.perfTimer);
this.perfTimer = window.setTimeout(() => {
this.perfTimer = null;
void this.fetchVisiblePerf();
}, PERF_DEBOUNCE_MS);
}
private async fetchVisiblePerf() {
const queue = [...this.perfEls.keys()];
const worker = async () => {
for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
if (!this.perfEls.has(id)) continue;
const perf = await fetchPerf(id, this.apiKey).catch(() => null);
perfCache.set(id, { at: Date.now(), perf });
const el = this.perfEls.get(id);
if (el?.isConnected) this.showPerf(el, perf);
}
};
await Promise.all(Array.from({ length: PERF_CONCURRENCY }, worker));
}
onChooseSuggestion(model: OpenRouterModel) { onChooseSuggestion(model: OpenRouterModel) {
this.onChoose(model.id); this.onChoose(model.id);
} }
} }
+201 -126
View File
@@ -1,12 +1,13 @@
import NibbleAI from "main"; import NibbleAI from "main";
import { App, PluginSettingTab, Setting, setIcon } from "obsidian"; import { App, PluginSettingTab, SecretComponent, Setting } from "obsidian";
import { import {
SettingsManager, SettingsManager,
PostProcessingProvider, PostProcessingProvider,
AIProvider,
TranscriptionProvider, TranscriptionProvider,
PROVIDER_URLS, CHAT_PROVIDERS,
PROVIDER_DEFAULT_MODELS, PROVIDER_DEFAULT_MODELS,
ReasoningEffort,
getApiKey,
} from "./SettingsManager"; } from "./SettingsManager";
import { ModelSuggestModal } from "./ModelBrowser"; import { ModelSuggestModal } from "./ModelBrowser";
@@ -20,17 +21,16 @@ type TabId =
interface TabInfo { interface TabInfo {
id: TabId; id: TabId;
icon: string;
label: string; label: string;
} }
const TABS: TabInfo[] = [ const TABS: TabInfo[] = [
{ id: "api-keys", icon: "key", label: "API Keys" }, { id: "api-keys", label: "API Keys" },
{ id: "transcription", icon: "mic", label: "Transcription" }, { id: "transcription", label: "Transcription" },
{ id: "proofreading", icon: "wand", label: "Proofreading" }, { id: "proofreading", label: "Proofreading" },
{ id: "title-generation", icon: "heading", label: "Title Generation" }, { id: "title-generation", label: "Title Generation" },
{ id: "property-filler", icon: "pencil", label: "Property Filler" }, { id: "property-filler", label: "Property Filler" },
{ id: "advanced", icon: "settings", label: "Advanced" }, { id: "advanced", label: "Advanced" },
]; ];
export class NibbleAISettingsTab extends PluginSettingTab { export class NibbleAISettingsTab extends PluginSettingTab {
@@ -60,12 +60,9 @@ export class NibbleAISettingsTab extends PluginSettingTab {
for (const tab of TABS) { for (const tab of TABS) {
const tabBtn = tabBar.createEl("button", { const tabBtn = tabBar.createEl("button", {
cls: `nibbleai-tab ${this.currentTab === tab.id ? "nibbleai-tab-active" : ""}`, cls: `nibbleai-tab${this.currentTab === tab.id ? " is-active" : ""}`,
attr: { "data-tab": tab.id }, text: tab.label,
}); });
const iconEl = tabBtn.createSpan({ cls: "nibbleai-tab-icon" });
setIcon(iconEl, tab.icon);
tabBtn.createSpan({ cls: "nibbleai-tab-label", text: tab.label });
tabBtn.addEventListener("click", () => { tabBtn.addEventListener("click", () => {
this.currentTab = tab.id; this.currentTab = tab.id;
this.display(); this.display();
@@ -101,49 +98,67 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── API Keys Tab ── // ── API Keys Tab ──
private renderApiKeysTab(containerEl: HTMLElement): void { private renderApiKeysTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "API Keys" });
containerEl.createEl("p", { containerEl.createEl("p", {
text: "API keys are stored securely in your system keychain.", text: "Pick a secret from Obsidian's keychain (Settings → Keychain) for each provider. NibbleAI stores only the secret's name; the key itself stays in the keychain.",
cls: "setting-item-description",
});
containerEl.createEl("p", {
text: "Each AI feature below (Proofreading, Title Generation, Property Filler, Post-Processing) lets you pick which of these providers to use, provided its key is set here.",
cls: "setting-item-description", cls: "setting-item-description",
}); });
this.createApiKeySetting(containerEl, this.createApiKeySetting(containerEl,
"Groq API Key", "Groq API Key",
"For Whisper transcription via Groq (groq.com)", "For Whisper transcription and Groq chat models (groq.com)",
"gsk_...", this.plugin.settings.groqSecret,
this.plugin.settings.groqApiKey,
async (value) => { async (value) => {
this.plugin.settings.groqApiKey = value; this.plugin.settings.groqSecret = value;
await this.save(); await this.save();
} }
); );
this.createApiKeySetting(containerEl, this.createApiKeySetting(containerEl,
"OpenAI API Key", "OpenAI API Key",
"For GPT / OpenAI-compatible models", "For GPT / OpenAI-compatible models",
"sk-...xxxx", this.plugin.settings.openAiSecret,
this.plugin.settings.openAiApiKey,
async (value) => { async (value) => {
this.plugin.settings.openAiApiKey = value; this.plugin.settings.openAiSecret = value;
await this.save(); await this.save();
} }
); );
this.createApiKeySetting(containerEl, this.createApiKeySetting(containerEl,
"Anthropic API Key", "Anthropic API Key",
"For Claude models (sk-ant-...)", "For Claude models (sk-ant-...)",
"sk-ant-...xxxx", this.plugin.settings.anthropicSecret,
this.plugin.settings.anthropicApiKey,
async (value) => { async (value) => {
this.plugin.settings.anthropicApiKey = value; this.plugin.settings.anthropicSecret = value;
await this.save(); await this.save();
} }
); );
this.createApiKeySetting(containerEl, this.createApiKeySetting(containerEl,
"OpenRouter API Key", "OpenRouter API Key",
"For OpenRouter models — get one at openrouter.ai/keys. Used for proofreading, title generation, property filling, and post-processing.", "For OpenRouter models — get one at openrouter.ai/keys.",
"sk-or-v1-...", this.plugin.settings.openRouterSecret,
this.plugin.settings.openRouterApiKey,
async (value) => { async (value) => {
this.plugin.settings.openRouterApiKey = value; this.plugin.settings.openRouterSecret = value;
await this.save();
}
);
this.createApiKeySetting(containerEl,
"Custom API Key",
"For a self-hosted or OpenAI-compatible endpoint not listed above",
this.plugin.settings.customSecret,
async (value) => {
this.plugin.settings.customSecret = value;
await this.save();
}
);
this.createTextSetting(containerEl,
"Custom API URL",
"Chat completions endpoint for the custom provider",
"https://api.example.com/v1/chat/completions",
this.plugin.settings.customApiUrl,
async (value) => {
this.plugin.settings.customApiUrl = value;
await this.save(); await this.save();
} }
); );
@@ -152,8 +167,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Transcription Tab ── // ── Transcription Tab ──
private renderTranscriptionTab(containerEl: HTMLElement): void { private renderTranscriptionTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Transcription" });
new Setting(containerEl) new Setting(containerEl)
.setName("Enable transcription") .setName("Enable transcription")
.setDesc("General settings for the audio-to-text feature") .setDesc("General settings for the audio-to-text feature")
@@ -328,29 +341,22 @@ export class NibbleAISettingsTab extends PluginSettingTab {
); );
if (this.plugin.settings.postProcessing) { if (this.plugin.settings.postProcessing) {
this.createPostProcessingProviderSetting(containerEl); this.createChatProviderSetting(containerEl,
"Select the LLM provider for cleaning up transcriptions",
this.plugin.settings.postProcessingProvider,
async (provider) => {
this.plugin.settings.postProcessingProvider = provider;
if (provider !== "custom") {
this.plugin.settings.postProcessingModel =
PROVIDER_DEFAULT_MODELS[provider];
}
await this.save();
this.display();
}
);
if (this.plugin.settings.postProcessingProvider === "custom") { if (this.plugin.settings.postProcessingProvider === "custom") {
this.createTextSetting(containerEl, this.createCustomProviderFields(containerEl);
"API URL",
"Custom endpoint for chat completions",
"https://api.example.com/v1/chat/completions",
this.plugin.settings.postProcessingUrl,
async (value) => {
this.plugin.settings.postProcessingUrl = value;
await this.save();
}
);
this.createApiKeySetting(containerEl,
"API Key",
"API key for the custom endpoint",
"sk-...xxxx",
this.plugin.settings.customApiKey,
async (value) => {
this.plugin.settings.customApiKey = value;
await this.save();
}
);
} }
this.createModelSetting(containerEl, this.createModelSetting(containerEl,
@@ -418,21 +424,28 @@ export class NibbleAISettingsTab extends PluginSettingTab {
} }
private renderProofreadingTab(containerEl: HTMLElement): void { private renderProofreadingTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Proofreading" });
containerEl.createEl("p", { containerEl.createEl("p", {
text: "Proofread selected text with AI. Right-click any selection or use the command palette.", text: "Proofread selected text with AI. Right-click any selection or use the command palette.",
cls: "setting-item-description", cls: "setting-item-description",
}); });
this.createProviderSetting(containerEl, this.createChatProviderSetting(containerEl,
"Provider",
"Select the AI provider for proofreading", "Select the AI provider for proofreading",
this.plugin.settings.proofreadingProvider, this.plugin.settings.proofreadingProvider,
async (value) => { async (provider) => {
this.plugin.settings.proofreadingProvider = value as AIProvider; this.plugin.settings.proofreadingProvider = provider;
if (provider !== "custom") {
this.plugin.settings.proofreadingModel =
PROVIDER_DEFAULT_MODELS[provider];
}
await this.save(); await this.save();
this.display();
} }
); );
if (this.plugin.settings.proofreadingProvider === "custom") {
this.createCustomProviderFields(containerEl);
}
this.createModelSetting(containerEl, this.createModelSetting(containerEl,
"Model", "Model",
"Model for fixing punctuation and grammar", "Model for fixing punctuation and grammar",
@@ -474,6 +487,36 @@ export class NibbleAISettingsTab extends PluginSettingTab {
} }
); );
if (this.plugin.settings.proofreadingProvider === "openrouter") {
new Setting(containerEl)
.setName("Reasoning")
.setDesc(
"Let the model think before answering. Slower and uses more tokens; rarely needed for punctuation and grammar."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.proofreadingReasoning)
.onChange(async (value) => {
this.plugin.settings.proofreadingReasoning = value;
await this.save();
})
);
new Setting(containerEl)
.setName("Effort")
.setDesc(
"How much the model writes (OpenRouter verbosity, Anthropic output effort). With reasoning on, also sets how deeply it thinks. Models without support ignore it."
)
.addDropdown((dropdown) =>
dropdown
.addOptions({ low: "Low", medium: "Medium", high: "High" })
.setValue(this.plugin.settings.proofreadingEffort)
.onChange(async (value) => {
this.plugin.settings.proofreadingEffort = value as ReasoningEffort;
await this.save();
})
);
}
this.createPromptSetting(containerEl, this.createPromptSetting(containerEl,
"System prompt", "System prompt",
"Instructions for the AI on how to proofread. Guarded against prompt injection.", "Instructions for the AI on how to proofread. Guarded against prompt injection.",
@@ -502,21 +545,28 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Title Generation Tab ── // ── Title Generation Tab ──
private renderTitleGenTab(containerEl: HTMLElement): void { private renderTitleGenTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Title Generation" });
containerEl.createEl("p", { containerEl.createEl("p", {
text: "Generate a title for the current note \u2014 either rename the file or set a frontmatter property.", text: "Generate a title for the current note \u2014 either rename the file or set a frontmatter property.",
cls: "setting-item-description", cls: "setting-item-description",
}); });
this.createProviderSetting(containerEl, this.createChatProviderSetting(containerEl,
"Provider",
"Select the AI provider for title generation", "Select the AI provider for title generation",
this.plugin.settings.titleGenProvider, this.plugin.settings.titleGenProvider,
async (value) => { async (provider) => {
this.plugin.settings.titleGenProvider = value as AIProvider; this.plugin.settings.titleGenProvider = provider;
if (provider !== "custom") {
this.plugin.settings.titleGenModel =
PROVIDER_DEFAULT_MODELS[provider];
}
await this.save(); await this.save();
this.display();
} }
); );
if (this.plugin.settings.titleGenProvider === "custom") {
this.createCustomProviderFields(containerEl);
}
this.createModelSetting(containerEl, this.createModelSetting(containerEl,
"Model", "Model",
"Model for generating titles", "Model for generating titles",
@@ -571,21 +621,28 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Property Filler Tab ── // ── Property Filler Tab ──
private renderPropertyFillerTab(containerEl: HTMLElement): void { private renderPropertyFillerTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Property Filler" });
containerEl.createEl("p", { containerEl.createEl("p", {
text: "Fill any frontmatter property with AI-generated content.", text: "Fill any frontmatter property with AI-generated content.",
cls: "setting-item-description", cls: "setting-item-description",
}); });
this.createProviderSetting(containerEl, this.createChatProviderSetting(containerEl,
"Provider",
"Select the AI provider for property generation", "Select the AI provider for property generation",
this.plugin.settings.propertyGenProvider, this.plugin.settings.propertyGenProvider,
async (value) => { async (provider) => {
this.plugin.settings.propertyGenProvider = value as AIProvider; this.plugin.settings.propertyGenProvider = provider;
if (provider !== "custom") {
this.plugin.settings.propertyGenModel =
PROVIDER_DEFAULT_MODELS[provider];
}
await this.save(); await this.save();
this.display();
} }
); );
if (this.plugin.settings.propertyGenProvider === "custom") {
this.createCustomProviderFields(containerEl);
}
this.createModelSetting(containerEl, this.createModelSetting(containerEl,
"Model", "Model",
"Model for generating property values", "Model for generating property values",
@@ -636,8 +693,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Advanced Tab ── // ── Advanced Tab ──
private renderAdvancedTab(containerEl: HTMLElement): void { private renderAdvancedTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Advanced" });
new Setting(containerEl) new Setting(containerEl)
.setName("Debug mode") .setName("Debug mode")
.setDesc("Increase verbosity for troubleshooting") .setDesc("Increase verbosity for troubleshooting")
@@ -682,19 +737,17 @@ export class NibbleAISettingsTab extends PluginSettingTab {
containerEl: HTMLElement, containerEl: HTMLElement,
name: string, name: string,
desc: string, desc: string,
placeholder: string, secretName: string,
value: string, onChange: (secretName: string) => Promise<void>
onChange: (value: string) => Promise<void>
): void { ): void {
new Setting(containerEl) new Setting(containerEl)
.setName(name) .setName(name)
.setDesc(desc) .setDesc(desc)
.addText((text) => { .addComponent((el) =>
text.setPlaceholder(placeholder) new SecretComponent(this.app, el)
.setValue(value) .setValue(secretName)
.onChange(async (value) => await onChange(value)); .onChange(async (value) => await onChange(value))
text.inputEl.type = "password"; );
});
} }
/** /**
@@ -748,30 +801,53 @@ export class NibbleAISettingsTab extends PluginSettingTab {
infoEl.style.flex = "1 1 100%"; infoEl.style.flex = "1 1 100%";
} }
private createProviderSetting( /**
* Shared provider dropdown for every LLM-backed feature (Post-Processing,
* Proofreading, Title Generation, Property Filler). Reads from the single
* CHAT_PROVIDERS registry so all four features always offer the exact
* same providers, and disables any provider whose API key isn't set yet.
*/
private createChatProviderSetting(
containerEl: HTMLElement, containerEl: HTMLElement,
name: string,
desc: string, desc: string,
value: string, currentProvider: PostProcessingProvider,
onChange: (value: string) => Promise<void> onChange: (provider: PostProcessingProvider) => Promise<void>
): void { ): void {
const providers: Record<string, string> = { const configured = new Set(
openrouter: "OpenRouter", CHAT_PROVIDERS.filter(
openai: "OpenAI", (p) => !!getApiKey(this.app, this.plugin.settings[p.secretField])
anthropic: "Anthropic", ).map((p) => p.id)
custom: "Custom", );
};
new Setting(containerEl) new Setting(containerEl)
.setName(name) .setName("Provider")
.setDesc(desc) .setDesc(desc)
.addDropdown((dropdown) => { .addDropdown((dropdown) => {
for (const [val, label] of Object.entries(providers)) { for (const p of CHAT_PROVIDERS) {
dropdown.addOption(val, label); dropdown.addOption(
p.id,
configured.has(p.id) ? p.label : `${p.label} (no API key)`
);
}
dropdown.setValue(currentProvider || "openrouter");
dropdown.onChange(async (value) => {
await onChange(value as PostProcessingProvider);
});
for (const p of CHAT_PROVIDERS) {
if (configured.has(p.id)) continue;
const optionEl = dropdown.selectEl.querySelector(
`option[value="${p.id}"]`
) as HTMLOptionElement | null;
if (optionEl) optionEl.disabled = true;
} }
dropdown.setValue(value || "openrouter");
dropdown.onChange(async (val) => await onChange(val));
}); });
if (configured.size === 0) {
containerEl.createEl("p", {
text: "⚠️ No AI provider configured yet — add an API key in the API Keys tab.",
cls: "setting-item-description",
});
}
} }
private createModelSetting( private createModelSetting(
@@ -796,7 +872,8 @@ export class NibbleAISettingsTab extends PluginSettingTab {
.setButtonText("Browse") .setButtonText("Browse")
.setIcon("search") .setIcon("search")
.onClick(() => { .onClick(() => {
new ModelSuggestModal(this.app, (modelId: string) => { const openRouterKey = getApiKey(this.app, this.plugin.settings.openRouterSecret);
new ModelSuggestModal(this.app, openRouterKey, (modelId: string) => {
onChange(modelId); onChange(modelId);
textComponent.setValue(modelId); textComponent.setValue(modelId);
}).open(); }).open();
@@ -860,36 +937,34 @@ export class NibbleAISettingsTab extends PluginSettingTab {
); );
} }
private createPostProcessingProviderSetting(containerEl: HTMLElement): void { /**
const providers: Record<PostProcessingProvider, string> = { * Custom endpoint + key fields, shown whenever a feature's provider is
anthropic: "Anthropic", * set to "Custom". This slot is shared across all four AI features.
openai: "OpenAI", */
openrouter: "OpenRouter", private createCustomProviderFields(containerEl: HTMLElement): void {
custom: "Custom", containerEl.createEl("p", {
}; text: "Custom provider connection \u2014 shared across Post-Processing, Proofreading, Title Generation, and Property Filler.",
cls: "setting-item-description",
new Setting(containerEl) });
.setName("Provider") this.createTextSetting(containerEl,
.setDesc("Select the LLM provider") "Custom API URL",
.addDropdown((dropdown) => { "OpenAI-compatible chat completions endpoint",
for (const [value, label] of Object.entries(providers)) { "https://api.example.com/v1/chat/completions",
dropdown.addOption(value, label); this.plugin.settings.customApiUrl,
} async (value) => {
dropdown this.plugin.settings.customApiUrl = value;
.setValue(this.plugin.settings.postProcessingProvider) await this.save();
.onChange(async (value) => { }
const provider = value as PostProcessingProvider; );
this.plugin.settings.postProcessingProvider = provider; this.createApiKeySetting(containerEl,
if (provider !== "custom") { "Custom API Key",
this.plugin.settings.postProcessingUrl = "Keychain secret holding the key for the custom endpoint",
PROVIDER_URLS[provider]; this.plugin.settings.customSecret,
this.plugin.settings.postProcessingModel = async (value) => {
PROVIDER_DEFAULT_MODELS[provider]; this.plugin.settings.customSecret = value;
} await this.save();
await this.save(); }
this.display(); );
});
});
} }
private async createAudioDeviceSetting(containerEl: HTMLElement): Promise<void> { private async createAudioDeviceSetting(containerEl: HTMLElement): Promise<void> {
+2 -1
View File
@@ -20,12 +20,13 @@ export class PostProcessor {
} }
async process(text: string, prompt: string): Promise<string> { async process(text: string, prompt: string): Promise<string> {
return AIService.callChatCompletion(text, prompt, { const result = await AIService.callChatCompletion(text, prompt, {
apiKey: this.config.apiKey, apiKey: this.config.apiKey,
model: this.config.model, model: this.config.model,
endpoint: this.config.url, endpoint: this.config.url,
provider: this.config.provider, provider: this.config.provider,
maxTokens: 8192, maxTokens: 8192,
}); });
return result.text;
} }
} }
+35
View File
@@ -0,0 +1,35 @@
import { App } from "obsidian";
import {
CHAT_PROVIDERS,
PROVIDER_URLS,
PluginSettings,
PostProcessingProvider,
getApiKey,
} from "./SettingsManager";
export interface ResolvedChatProvider {
apiKey: string;
endpoint: string;
provider: PostProcessingProvider;
}
/**
* Resolves the API key + endpoint for a chat-completion provider selection.
* Shared by every AI feature that talks to an LLM (Post-Processing,
* Proofreading, Title Generation, Property Filler) so they all treat
* providers — including "no key configured" — identically.
*/
export function resolveChatProvider(
app: App,
settings: PluginSettings,
provider: PostProcessingProvider
): ResolvedChatProvider | null {
const info = CHAT_PROVIDERS.find((p) => p.id === provider);
if (!info) return null;
const apiKey = getApiKey(app, settings[info.secretField]);
const endpoint = provider === "custom" ? settings.customApiUrl : PROVIDER_URLS[provider];
if (!apiKey || !endpoint) return null;
return { apiKey, endpoint, provider };
}
+111 -55
View File
@@ -1,14 +1,18 @@
import { Plugin } from "obsidian"; import { App, Plugin } from "obsidian";
const SECRET_IDS: Record<keyof ApiKeysSettings, string> = { /**
groqApiKey: "groq-api-key", * Fixed keychain names NibbleAI ≤ 1.2.1 wrote keys under, and the plain-text
openAiApiKey: "openai-api-key", * data.json fields older versions used. Only read by the one-time migration.
anthropicApiKey: "anthropic-api-key", */
customApiKey: "custom-api-key", const LEGACY_KEYS: Record<ApiKeySecretField, { field: string; secretId: string }> = {
openRouterApiKey: "openrouter-api-key", groqSecret: { field: "groqApiKey", secretId: "groq-api-key" },
openAiSecret: { field: "openAiApiKey", secretId: "openai-api-key" },
anthropicSecret: { field: "anthropicApiKey", secretId: "anthropic-api-key" },
customSecret: { field: "customApiKey", secretId: "custom-api-key" },
openRouterSecret: { field: "openRouterApiKey", secretId: "openrouter-api-key" },
}; };
export type PostProcessingProvider = "anthropic" | "openai" | "openrouter" | "custom"; export type PostProcessingProvider = "anthropic" | "openai" | "openrouter" | "groq" | "custom";
export type AIProvider = PostProcessingProvider; export type AIProvider = PostProcessingProvider;
@@ -16,6 +20,7 @@ export const PROVIDER_URLS: Record<PostProcessingProvider, string> = {
anthropic: "https://api.anthropic.com/v1/messages", anthropic: "https://api.anthropic.com/v1/messages",
openai: "https://api.openai.com/v1/chat/completions", openai: "https://api.openai.com/v1/chat/completions",
openrouter: "https://openrouter.ai/api/v1/chat/completions", openrouter: "https://openrouter.ai/api/v1/chat/completions",
groq: "https://api.groq.com/openai/v1/chat/completions",
custom: "", custom: "",
}; };
@@ -23,9 +28,30 @@ export const PROVIDER_DEFAULT_MODELS: Record<PostProcessingProvider, string> = {
anthropic: "claude-sonnet-4-20250514", anthropic: "claude-sonnet-4-20250514",
openai: "gpt-4o-mini", openai: "gpt-4o-mini",
openrouter: "openai/gpt-4o-mini", openrouter: "openai/gpt-4o-mini",
groq: "llama-3.3-70b-versatile",
custom: "", custom: "",
}; };
export interface ChatProviderInfo {
id: PostProcessingProvider;
label: string;
secretField: ApiKeySecretField;
}
/**
* Single source of truth for which chat-completion providers exist and which
* API key each one uses. UI dropdowns and provider resolution both read from
* this list so every AI feature (Post-Processing, Proofreading, Title
* Generation, Property Filler) offers the exact same providers.
*/
export const CHAT_PROVIDERS: ChatProviderInfo[] = [
{ id: "anthropic", label: "Anthropic", secretField: "anthropicSecret" },
{ id: "openai", label: "OpenAI", secretField: "openAiSecret" },
{ id: "groq", label: "Groq", secretField: "groqSecret" },
{ id: "openrouter", label: "OpenRouter", secretField: "openRouterSecret" },
{ id: "custom", label: "Custom", secretField: "customSecret" },
];
export type TranscriptionProvider = "groq" | "openai" | "azure" | "custom"; export type TranscriptionProvider = "groq" | "openai" | "azure" | "custom";
export const TRANSCRIPTION_PROVIDER_URLS: Record<TranscriptionProvider, string> = { export const TRANSCRIPTION_PROVIDER_URLS: Record<TranscriptionProvider, string> = {
@@ -37,12 +63,25 @@ export const TRANSCRIPTION_PROVIDER_URLS: Record<TranscriptionProvider, string>
export type TitleGenMode = "rename-file" | "frontmatter-property"; export type TitleGenMode = "rename-file" | "frontmatter-property";
/**
* The `*Secret` fields hold the *name* of a secret in Obsidian's keychain
* (Settings → Keychain), never the key itself. Resolve with `getApiKey`.
*/
export interface ApiKeysSettings { export interface ApiKeysSettings {
groqApiKey: string; groqSecret: string;
openAiApiKey: string; openAiSecret: string;
anthropicApiKey: string; anthropicSecret: string;
customApiKey: string; customSecret: string;
openRouterApiKey: string; customApiUrl: string;
openRouterSecret: string;
}
export type ApiKeySecretField = Exclude<keyof ApiKeysSettings, "customApiUrl">;
/** Reads the key from the keychain at call time, so rotated keys apply immediately. */
export function getApiKey(app: App, secretName: string): string {
if (!secretName) return "";
return app.secretStorage.getSecret(secretName) ?? "";
} }
export interface TranscriptionSettings { export interface TranscriptionSettings {
@@ -74,7 +113,6 @@ export interface OutputSettings {
export interface PostProcessingSettings { export interface PostProcessingSettings {
postProcessing: boolean; postProcessing: boolean;
postProcessingProvider: PostProcessingProvider; postProcessingProvider: PostProcessingProvider;
postProcessingUrl: string;
postProcessingModel: string; postProcessingModel: string;
postProcessingPrompt: string; postProcessingPrompt: string;
autoGenerateTitle: boolean; autoGenerateTitle: boolean;
@@ -82,11 +120,17 @@ export interface PostProcessingSettings {
keepOriginalTranscription: boolean; keepOriginalTranscription: boolean;
} }
export type ReasoningEffort = "low" | "medium" | "high";
export interface ProofreadingSettings { export interface ProofreadingSettings {
proofreadingProvider: AIProvider; proofreadingProvider: AIProvider;
proofreadingModel: string; proofreadingModel: string;
proofreadingTemperature: number; proofreadingTemperature: number;
proofreadingMaxTokens: number; proofreadingMaxTokens: number;
/** OpenRouter only: let the model think before answering. */
proofreadingReasoning: boolean;
/** OpenRouter only: output effort (`verbosity`), and reasoning depth when reasoning is on. */
proofreadingEffort: ReasoningEffort;
proofreadingSystemPrompt: string; proofreadingSystemPrompt: string;
proofreadingContextMenu: boolean; proofreadingContextMenu: boolean;
} }
@@ -124,11 +168,12 @@ export type PluginSettings = ApiKeysSettings &
// ── Defaults ── // ── Defaults ──
export const DEFAULT_API_KEYS: ApiKeysSettings = { export const DEFAULT_API_KEYS: ApiKeysSettings = {
groqApiKey: "", groqSecret: "",
openAiApiKey: "", openAiSecret: "",
anthropicApiKey: "", anthropicSecret: "",
customApiKey: "", customSecret: "",
openRouterApiKey: "", customApiUrl: "",
openRouterSecret: "",
}; };
export const DEFAULT_TRANSCRIPTION: TranscriptionSettings = { export const DEFAULT_TRANSCRIPTION: TranscriptionSettings = {
@@ -160,7 +205,6 @@ export const DEFAULT_OUTPUT: OutputSettings = {
export const DEFAULT_POST_PROCESSING: PostProcessingSettings = { export const DEFAULT_POST_PROCESSING: PostProcessingSettings = {
postProcessing: false, postProcessing: false,
postProcessingProvider: "anthropic", postProcessingProvider: "anthropic",
postProcessingUrl: "https://api.anthropic.com/v1/messages",
postProcessingModel: "claude-sonnet-4-20250514", postProcessingModel: "claude-sonnet-4-20250514",
postProcessingPrompt: postProcessingPrompt:
'You are a transcription editor. Clean up the following voice transcription: fix grammar, remove filler words (um, uh, like) and repetitions, and improve readability. Format the text in markdown. If there are action items or to-dos, format them as task lists with "[ ]". Preserve the original meaning and language. Return only the polished text, nothing else.', 'You are a transcription editor. Clean up the following voice transcription: fix grammar, remove filler words (um, uh, like) and repetitions, and improve readability. Format the text in markdown. If there are action items or to-dos, format them as task lists with "[ ]". Preserve the original meaning and language. Return only the polished text, nothing else.',
@@ -192,6 +236,8 @@ export const DEFAULT_PROOFREADING: ProofreadingSettings = {
proofreadingModel: "openai/gpt-4o-mini", proofreadingModel: "openai/gpt-4o-mini",
proofreadingTemperature: 0.2, proofreadingTemperature: 0.2,
proofreadingMaxTokens: 2000, proofreadingMaxTokens: 2000,
proofreadingReasoning: false,
proofreadingEffort: "low",
proofreadingSystemPrompt: DEFAULT_PROOFREADING_SYSTEM_PROMPT, proofreadingSystemPrompt: DEFAULT_PROOFREADING_SYSTEM_PROMPT,
proofreadingContextMenu: true, proofreadingContextMenu: true,
}; };
@@ -243,50 +289,59 @@ export class SettingsManager {
return this.plugin.app.secretStorage; return this.plugin.app.secretStorage;
} }
private migrateKeysFromDataJson(settings: PluginSettings): boolean { /**
// One-time migration: move plain-text keys out of data.json into SecretStorage. * One-time migration to user-selected keychain secrets. Older versions
* either kept keys in plain text in data.json or wrote them to the keychain
* under fixed names. Point each `*Secret` field at the fixed name when it
* holds a key, then drop the legacy field. Runs only while a legacy field
* is still present in data.json, so clearing a selection later sticks.
*/
private migrateKeysToSecretNames(settings: PluginSettings): boolean {
const legacy = settings as PluginSettings & Record<string, unknown>;
let migrated = false; let migrated = false;
for (const [field, secretId] of Object.entries(SECRET_IDS)) { for (const [secretField, { field, secretId }] of Object.entries(LEGACY_KEYS)) {
const key = field as keyof ApiKeysSettings; if (!(field in legacy)) continue;
if (settings[key]) { const plainKey = legacy[field];
this.secrets.setSecret(secretId, settings[key]); const name = secretField as ApiKeySecretField;
settings[key] = ""; if (typeof plainKey === "string" && plainKey) {
migrated = true; this.secrets.setSecret(secretId, plainKey);
} }
if (!settings[name] && this.secrets.getSecret(secretId)) {
settings[name] = secretId;
}
delete legacy[field];
migrated = true;
} }
return migrated; return migrated;
} }
private syncKeysToSecretStorage(settings: PluginSettings): void {
for (const [field, secretId] of Object.entries(SECRET_IDS)) {
const key = field as keyof ApiKeysSettings;
this.secrets.setSecret(secretId, settings[key]);
settings[key] = "";
}
}
private loadKeysFromSecretStorage(settings: PluginSettings): void {
for (const [field, secretId] of Object.entries(SECRET_IDS)) {
const key = field as keyof ApiKeysSettings;
settings[key] = this.secrets.getSecret(secretId) ?? "";
}
}
private migratePostProcessingProvider(settings: PluginSettings): boolean { private migratePostProcessingProvider(settings: PluginSettings): boolean {
if (settings.postProcessingProvider) return false; if (settings.postProcessingProvider) return false;
const legacyUrl = (settings as PluginSettings & { postProcessingUrl?: string })
.postProcessingUrl;
if (!legacyUrl) return false;
for (const [provider, url] of Object.entries(PROVIDER_URLS)) { for (const [provider, url] of Object.entries(PROVIDER_URLS)) {
if (url && settings.postProcessingUrl === url) { if (url && legacyUrl === url) {
settings.postProcessingProvider = settings.postProcessingProvider = provider as PostProcessingProvider;
provider as PostProcessingProvider;
return true; return true;
} }
} }
if (settings.postProcessingUrl) { settings.postProcessingProvider = "custom";
settings.postProcessingProvider = "custom"; return true;
return true; }
}
return false; private migrateCustomApiUrl(settings: PluginSettings): boolean {
// One-time migration: the old `postProcessingUrl` field is now the
// shared `customApiUrl` used by every feature's "Custom" provider.
if (settings.customApiUrl) return false;
const legacyUrl = (settings as PluginSettings & { postProcessingUrl?: string })
.postProcessingUrl;
if (!legacyUrl) return false;
if (Object.values(PROVIDER_URLS).includes(legacyUrl)) return false;
settings.customApiUrl = legacyUrl;
return true;
} }
async loadSettings(): Promise<PluginSettings> { async loadSettings(): Promise<PluginSettings> {
@@ -300,17 +355,18 @@ export class SettingsManager {
await this.plugin.saveData(settings); await this.plugin.saveData(settings);
} }
if (this.migrateKeysFromDataJson(settings)) { if (this.migrateCustomApiUrl(settings)) {
await this.plugin.saveData(settings);
}
if (this.migrateKeysToSecretNames(settings)) {
await this.plugin.saveData(settings); await this.plugin.saveData(settings);
} }
this.loadKeysFromSecretStorage(settings);
return settings; return settings;
} }
async saveSettings(settings: PluginSettings): Promise<void> { async saveSettings(settings: PluginSettings): Promise<void> {
this.syncKeysToSecretStorage(settings);
await this.plugin.saveData(settings); await this.plugin.saveData(settings);
this.loadKeysFromSecretStorage(settings);
} }
} }
+37 -34
View File
@@ -1,6 +1,6 @@
import { Editor, Notice } from "obsidian"; import { Editor, Notice } from "obsidian";
import { AIService } from "../AIService"; import { AIService } from "../AIService";
import { AIProvider, PROVIDER_URLS } from "../SettingsManager"; import { resolveChatProvider } from "../ProviderResolver";
import NibbleAI from "main"; import NibbleAI from "main";
export class Proofreader { export class Proofreader {
@@ -10,33 +10,6 @@ export class Proofreader {
this.plugin = plugin; this.plugin = plugin;
} }
private resolveProvider(): { apiKey: string; endpoint: string; provider: AIProvider } | null {
const provider = this.plugin.settings.proofreadingProvider || "openrouter";
let apiKey = "";
let endpoint = PROVIDER_URLS[provider] || "";
switch (provider) {
case "openai":
apiKey = this.plugin.settings.openAiApiKey;
break;
case "anthropic":
apiKey = this.plugin.settings.anthropicApiKey;
break;
case "openrouter":
apiKey = this.plugin.settings.openRouterApiKey;
break;
case "custom":
apiKey = this.plugin.settings.customApiKey;
endpoint = this.plugin.settings.postProcessingUrl || "";
break;
}
if (!apiKey) return null;
if (!endpoint) return null;
return { apiKey, endpoint, provider };
}
async fixSelection(editor: Editor): Promise<void> { async fixSelection(editor: Editor): Promise<void> {
const selection = editor.getSelection(); const selection = editor.getSelection();
if (!selection || selection.trim().length === 0) { if (!selection || selection.trim().length === 0) {
@@ -44,7 +17,11 @@ export class Proofreader {
return; return;
} }
const config = this.resolveProvider(); const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.proofreadingProvider || "openrouter"
);
if (!config) { if (!config) {
new Notice( new Notice(
"⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys." "⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys."
@@ -52,23 +29,34 @@ export class Proofreader {
return; return;
} }
new Notice("🤖 Fixing punctuation and grammar..."); const model = this.plugin.settings.proofreadingModel;
const startedAt = performance.now();
const elapsed = () => `${((performance.now() - startedAt) / 1000).toFixed(1)} s`;
const progress = new Notice(`🤖 Proofreading with ${model}… 0.0 s`, 0);
const ticker = window.setInterval(
() => progress.setMessage(`🤖 Proofreading with ${model}… ${elapsed()}`),
100
);
try { try {
const systemPrompt = const systemPrompt =
this.plugin.settings.proofreadingSystemPrompt || this.plugin.settings.proofreadingSystemPrompt ||
"You are a text proofreading tool. Fix punctuation and grammar in the text below. Return only the corrected text, nothing else."; "You are a text proofreading tool. Fix punctuation and grammar in the text below. Return only the corrected text, nothing else.";
const corrected = await AIService.callChatCompletion( const { text: corrected, upstream, usage } = await AIService.callChatCompletion(
selection, selection,
systemPrompt, systemPrompt,
{ {
apiKey: config.apiKey, apiKey: config.apiKey,
model: this.plugin.settings.proofreadingModel, model,
endpoint: config.endpoint, endpoint: config.endpoint,
provider: config.provider, provider: config.provider,
temperature: this.plugin.settings.proofreadingTemperature, temperature: this.plugin.settings.proofreadingTemperature,
maxTokens: this.plugin.settings.proofreadingMaxTokens, maxTokens: this.plugin.settings.proofreadingMaxTokens,
reasoning: {
enabled: this.plugin.settings.proofreadingReasoning,
effort: this.plugin.settings.proofreadingEffort,
},
} }
); );
@@ -78,12 +66,27 @@ export class Proofreader {
} }
editor.replaceSelection(corrected); editor.replaceSelection(corrected);
new Notice("✅ Punctuation and grammar fixed."); // Prompt tokens = system prompt + selection. Reasoning tokens are part
// of the output count and are usually what makes a short fix slow.
const tokens = usage
? `Prompt ${usage.promptTokens} tok · output ${usage.completionTokens} tok` +
(usage.reasoningTokens ? ` (${usage.reasoningTokens} reasoning)` : "")
: "Token usage not reported";
const knobs =
config.provider === "openrouter"
? ` · reasoning ${this.plugin.settings.proofreadingReasoning ? "on" : "off"} · effort ${this.plugin.settings.proofreadingEffort}`
: "";
const summary = `✅ Fixed in ${elapsed()}\n${model}${upstream ? ` via ${upstream}` : ""}${knobs}\n${tokens}`;
console.info(`NibbleAI proofread: ${summary.replace(/\n/g, " | ")}`);
new Notice(summary, 10000);
} catch (error) { } catch (error) {
console.error("Proofreading error:", error); console.error("Proofreading error:", error);
new Notice( new Notice(
`❌ Fix failed: ${error instanceof Error ? error.message : String(error)}` `❌ Fix failed after ${elapsed()} (${model}): ${error instanceof Error ? error.message : String(error)}`
); );
} finally {
window.clearInterval(ticker);
progress.hide();
} }
} }
} }
+7 -28
View File
@@ -1,6 +1,6 @@
import { Notice, MarkdownView, Modal, App, Setting, TFile } from "obsidian"; import { Notice, MarkdownView, Modal, App, Setting, TFile } from "obsidian";
import { AIService } from "../AIService"; import { AIService } from "../AIService";
import { AIProvider, PROVIDER_URLS } from "../SettingsManager"; import { resolveChatProvider } from "../ProviderResolver";
import NibbleAI from "main"; import NibbleAI from "main";
class PropertyPromptModal extends Modal { class PropertyPromptModal extends Modal {
@@ -80,31 +80,6 @@ export class PropertyFiller {
this.plugin = plugin; this.plugin = plugin;
} }
private resolveProvider(): { apiKey: string; endpoint: string; provider: AIProvider } | null {
const provider = this.plugin.settings.propertyGenProvider || "openrouter";
let apiKey = "";
let endpoint = PROVIDER_URLS[provider] || "";
switch (provider) {
case "openai":
apiKey = this.plugin.settings.openAiApiKey;
break;
case "anthropic":
apiKey = this.plugin.settings.anthropicApiKey;
break;
case "openrouter":
apiKey = this.plugin.settings.openRouterApiKey;
break;
case "custom":
apiKey = this.plugin.settings.customApiKey;
endpoint = this.plugin.settings.postProcessingUrl || "";
break;
}
if (!apiKey || !endpoint) return null;
return { apiKey, endpoint, provider };
}
async fillProperty(): Promise<void> { async fillProperty(): Promise<void> {
new PropertyPromptModal( new PropertyPromptModal(
this.plugin.app, this.plugin.app,
@@ -139,7 +114,11 @@ export class PropertyFiller {
return; return;
} }
const config = this.resolveProvider(); const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.propertyGenProvider || "openrouter"
);
if (!config) { if (!config) {
new Notice( new Notice(
"⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys." "⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys."
@@ -168,7 +147,7 @@ export class PropertyFiller {
"Based on the following note content, generate a value for the property '{property}'. Return only the value, nothing else."; "Based on the following note content, generate a value for the property '{property}'. Return only the value, nothing else.";
const prompt = promptTemplate.replace(/\{property\}/g, propertyName); const prompt = promptTemplate.replace(/\{property\}/g, propertyName);
const generated = await AIService.callChatCompletion( const { text: generated } = await AIService.callChatCompletion(
content, content,
prompt, prompt,
{ {
+64
View File
@@ -33,6 +33,12 @@ export class NativeAudioRecorder implements AudioRecorder {
private recorder: MediaRecorder | null = null; private recorder: MediaRecorder | null = null;
private mimeType: string | undefined; private mimeType: string | undefined;
private deviceId: string | null = null; private deviceId: string | null = null;
private audioContext: AudioContext | null = null;
private analyser: AnalyserNode | null = null;
private inputSource: MediaStreamAudioSourceNode | null = null;
private inputSamples: Uint8Array | null = null;
private animationFrameId: number | null = null;
private onInputLevel: ((level: number) => void) | null = null;
getRecordingState(): "inactive" | "recording" | "paused" | undefined { getRecordingState(): "inactive" | "recording" | "paused" | undefined {
return this.recorder?.state; return this.recorder?.state;
@@ -46,6 +52,10 @@ export class NativeAudioRecorder implements AudioRecorder {
this.deviceId = deviceId; this.deviceId = deviceId;
} }
setInputLevelCallback(callback: ((level: number) => void) | null): void {
this.onInputLevel = callback;
}
async startRecording(): Promise<void> { async startRecording(): Promise<void> {
if (!this.recorder) { if (!this.recorder) {
try { try {
@@ -70,6 +80,7 @@ export class NativeAudioRecorder implements AudioRecorder {
}); });
this.recorder = recorder; this.recorder = recorder;
this.startInputMeter(stream);
} catch (err) { } catch (err) {
new Notice("✘ Couldn't access microphone"); new Notice("✘ Couldn't access microphone");
console.error("Error initializing recorder:", err); console.error("Error initializing recorder:", err);
@@ -87,6 +98,7 @@ export class NativeAudioRecorder implements AudioRecorder {
if (this.recorder.state === "recording") { if (this.recorder.state === "recording") {
this.recorder.pause(); this.recorder.pause();
this.onInputLevel?.(0);
} else if (this.recorder.state === "paused") { } else if (this.recorder.state === "paused") {
this.recorder.resume(); this.recorder.resume();
} }
@@ -97,6 +109,7 @@ export class NativeAudioRecorder implements AudioRecorder {
if (!this.recorder || this.recorder.state === "inactive") { if (!this.recorder || this.recorder.state === "inactive") {
const blob = new Blob(this.chunks, { type: this.mimeType }); const blob = new Blob(this.chunks, { type: this.mimeType });
this.chunks.length = 0; this.chunks.length = 0;
this.stopInputMeter();
resolve(blob); resolve(blob);
} else { } else {
this.recorder.addEventListener( this.recorder.addEventListener(
@@ -113,6 +126,7 @@ export class NativeAudioRecorder implements AudioRecorder {
.forEach((track) => track.stop()); .forEach((track) => track.stop());
this.recorder = null; this.recorder = null;
} }
this.stopInputMeter();
resolve(blob); resolve(blob);
}, },
@@ -123,4 +137,54 @@ export class NativeAudioRecorder implements AudioRecorder {
} }
}); });
} }
private startInputMeter(stream: MediaStream): void {
this.stopInputMeter();
this.audioContext = new AudioContext();
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 256;
this.inputSamples = new Uint8Array(this.analyser.fftSize);
this.inputSource = this.audioContext.createMediaStreamSource(stream);
this.inputSource.connect(this.analyser);
this.tickInputMeter();
}
private tickInputMeter(): void {
if (!this.analyser || !this.inputSamples) return;
if (this.recorder?.state === "recording") {
this.analyser.getByteTimeDomainData(this.inputSamples);
let sum = 0;
for (let i = 0; i < this.inputSamples.length; i++) {
const centeredSample = (this.inputSamples[i] - 128) / 128;
sum += centeredSample * centeredSample;
}
const rms = Math.sqrt(sum / this.inputSamples.length);
this.onInputLevel?.(Math.min(1, rms * 6));
} else {
this.onInputLevel?.(0);
}
this.animationFrameId = requestAnimationFrame(() =>
this.tickInputMeter()
);
}
private stopInputMeter(): void {
if (this.animationFrameId !== null) {
cancelAnimationFrame(this.animationFrameId);
this.animationFrameId = null;
}
void this.audioContext?.close();
this.audioContext = null;
this.analyser = null;
this.inputSource = null;
this.inputSamples = null;
this.onInputLevel?.(0);
}
} }
+55 -20
View File
@@ -12,6 +12,7 @@ export class StatusBar {
statusBarItem: HTMLElement | null = null; statusBarItem: HTMLElement | null = null;
status: RecordingStatus = RecordingStatus.Idle; status: RecordingStatus = RecordingStatus.Idle;
private listeners: Array<(status: RecordingStatus) => void> = []; private listeners: Array<(status: RecordingStatus) => void> = [];
private meterBars: HTMLElement[] = [];
constructor(plugin: Plugin) { constructor(plugin: Plugin) {
this.plugin = plugin; this.plugin = plugin;
@@ -33,27 +34,61 @@ export class StatusBar {
this.listeners.forEach((fn) => fn(status)); this.listeners.forEach((fn) => fn(status));
} }
updateInputLevel(level: number): void {
if (this.status !== RecordingStatus.Recording) return;
const clampedLevel = Math.max(0, Math.min(1, level));
const activeBars = Math.round(clampedLevel * this.meterBars.length);
this.meterBars.forEach((bar, index) => {
bar.toggleClass("nibbleai-meter-bar-active", index < activeBars);
});
}
updateStatusBarItem() { updateStatusBarItem() {
if (this.statusBarItem) { if (!this.statusBarItem) return;
switch (this.status) {
case RecordingStatus.Recording: this.statusBarItem.empty();
this.statusBarItem.textContent = "NibbleAI Recording..."; this.statusBarItem.removeClass("nibbleai-status-recording");
this.statusBarItem.style.color = "red"; this.statusBarItem.removeClass("nibbleai-status-paused");
break; this.statusBarItem.removeClass("nibbleai-status-processing");
case RecordingStatus.Paused: this.statusBarItem.removeClass("nibbleai-status-idle");
this.statusBarItem.textContent = "NibbleAI Paused"; this.meterBars = [];
this.statusBarItem.style.color = "yellow";
break; switch (this.status) {
case RecordingStatus.Processing: case RecordingStatus.Recording:
this.statusBarItem.textContent = "NibbleAI Processing..."; this.statusBarItem.addClass("nibbleai-status-recording");
this.statusBarItem.style.color = "gray"; this.statusBarItem.createSpan({ text: "NibbleAI " });
break; this.createInputMeter();
case RecordingStatus.Idle: break;
default: case RecordingStatus.Paused:
this.statusBarItem.textContent = "NibbleAI Idle"; this.statusBarItem.addClass("nibbleai-status-paused");
this.statusBarItem.style.color = "green"; this.statusBarItem.setText("NibbleAI Paused");
break; break;
} case RecordingStatus.Processing:
this.statusBarItem.addClass("nibbleai-status-processing");
this.statusBarItem.setText("NibbleAI Processing...");
break;
case RecordingStatus.Idle:
default:
this.statusBarItem.addClass("nibbleai-status-idle");
this.statusBarItem.setText("NibbleAI Idle");
break;
}
}
private createInputMeter(): void {
if (!this.statusBarItem) return;
const meter = this.statusBarItem.createSpan({
cls: "nibbleai-input-meter",
attr: { "aria-label": "Recording input level" },
});
for (let i = 0; i < 8; i++) {
this.meterBars.push(
meter.createSpan({ cls: "nibbleai-meter-bar" })
);
} }
} }
+7 -28
View File
@@ -1,6 +1,6 @@
import { Notice, TFile, MarkdownView } from "obsidian"; import { Notice, TFile, MarkdownView } from "obsidian";
import { AIService } from "../AIService"; import { AIService } from "../AIService";
import { AIProvider, PROVIDER_URLS } from "../SettingsManager"; import { resolveChatProvider } from "../ProviderResolver";
import NibbleAI from "main"; import NibbleAI from "main";
export class TitleGenerator { export class TitleGenerator {
@@ -10,31 +10,6 @@ export class TitleGenerator {
this.plugin = plugin; this.plugin = plugin;
} }
private resolveProvider(): { apiKey: string; endpoint: string; provider: AIProvider } | null {
const provider = this.plugin.settings.titleGenProvider || "openrouter";
let apiKey = "";
let endpoint = PROVIDER_URLS[provider] || "";
switch (provider) {
case "openai":
apiKey = this.plugin.settings.openAiApiKey;
break;
case "anthropic":
apiKey = this.plugin.settings.anthropicApiKey;
break;
case "openrouter":
apiKey = this.plugin.settings.openRouterApiKey;
break;
case "custom":
apiKey = this.plugin.settings.customApiKey;
endpoint = this.plugin.settings.postProcessingUrl || "";
break;
}
if (!apiKey || !endpoint) return null;
return { apiKey, endpoint, provider };
}
async generateTitle(): Promise<void> { async generateTitle(): Promise<void> {
const activeView = const activeView =
this.plugin.app.workspace.getActiveViewOfType(MarkdownView); this.plugin.app.workspace.getActiveViewOfType(MarkdownView);
@@ -55,7 +30,11 @@ export class TitleGenerator {
return; return;
} }
const config = this.resolveProvider(); const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.titleGenProvider || "openrouter"
);
if (!config) { if (!config) {
new Notice( new Notice(
"⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys." "⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys."
@@ -70,7 +49,7 @@ export class TitleGenerator {
this.plugin.settings.titleGenPrompt || this.plugin.settings.titleGenPrompt ||
"Generate a short, descriptive title (1-8 words) for the following note content. Return only the title, nothing else."; "Generate a short, descriptive title (1-8 words) for the following note content. Return only the title, nothing else.";
const generated = await AIService.callChatCompletion( const { text: generated } = await AIService.callChatCompletion(
content, content,
prompt, prompt,
{ {
+26 -28
View File
@@ -8,6 +8,8 @@ import {
resolveTemplate, resolveTemplate,
} from "./utils"; } from "./utils";
import { PostProcessor } from "../PostProcessor"; import { PostProcessor } from "../PostProcessor";
import { resolveChatProvider } from "../ProviderResolver";
import { getApiKey } from "../SettingsManager";
export class AudioHandler { export class AudioHandler {
private plugin: NibbleAI; private plugin: NibbleAI;
@@ -16,19 +18,6 @@ export class AudioHandler {
this.plugin = plugin; this.plugin = plugin;
} }
private getPostProcessingApiKey(): string {
switch (this.plugin.settings.postProcessingProvider) {
case "anthropic":
return this.plugin.settings.anthropicApiKey;
case "openai":
return this.plugin.settings.openAiApiKey;
case "openrouter":
return this.plugin.settings.openRouterApiKey;
case "custom":
return this.plugin.settings.customApiKey;
}
}
private getTranscriptionUrl(): string { private getTranscriptionUrl(): string {
switch (this.plugin.settings.transcriptionProvider) { switch (this.plugin.settings.transcriptionProvider) {
case "groq": case "groq":
@@ -42,15 +31,16 @@ export class AudioHandler {
} }
} }
private getTranscriptionApiKey(): string { getTranscriptionApiKey(): string {
switch (this.plugin.settings.transcriptionProvider) { const { app, settings } = this.plugin;
switch (settings.transcriptionProvider) {
case "groq": case "groq":
return this.plugin.settings.groqApiKey; return getApiKey(app, settings.groqSecret);
case "openai": case "openai":
case "azure": case "azure":
return this.plugin.settings.openAiApiKey; return getApiKey(app, settings.openAiSecret);
case "custom": case "custom":
return this.plugin.settings.groqApiKey || this.plugin.settings.openAiApiKey; return getApiKey(app, settings.groqSecret) || getApiKey(app, settings.openAiSecret);
} }
} }
@@ -173,8 +163,12 @@ export class AudioHandler {
// Post-process with LLM if enabled // Post-process with LLM if enabled
if (this.plugin.settings.postProcessing) { if (this.plugin.settings.postProcessing) {
const ppApiKey = this.getPostProcessingApiKey(); const resolved = resolveChatProvider(
if (!ppApiKey) { this.plugin.app,
this.plugin.settings,
this.plugin.settings.postProcessingProvider
);
if (!resolved) {
new Notice( new Notice(
"✘ Add your post-processing API key in settings" "✘ Add your post-processing API key in settings"
); );
@@ -185,10 +179,10 @@ export class AudioHandler {
new Notice("Post-processing..."); new Notice("Post-processing...");
} }
const processor = new PostProcessor({ const processor = new PostProcessor({
apiKey: ppApiKey, apiKey: resolved.apiKey,
model: this.plugin.settings.postProcessingModel, model: this.plugin.settings.postProcessingModel,
url: this.plugin.settings.postProcessingUrl, url: resolved.endpoint,
provider: this.plugin.settings.postProcessingProvider, provider: resolved.provider,
}); });
finalText = await processor.process( finalText = await processor.process(
originalText, originalText,
@@ -209,14 +203,18 @@ export class AudioHandler {
this.plugin.settings.autoGenerateTitle && this.plugin.settings.autoGenerateTitle &&
this.plugin.settings.createNoteFile this.plugin.settings.createNoteFile
) { ) {
const ppApiKey = this.getPostProcessingApiKey(); const resolved = resolveChatProvider(
if (ppApiKey) { this.plugin.app,
this.plugin.settings,
this.plugin.settings.postProcessingProvider
);
if (resolved) {
try { try {
const processor = new PostProcessor({ const processor = new PostProcessor({
apiKey: ppApiKey, apiKey: resolved.apiKey,
model: this.plugin.settings.postProcessingModel, model: this.plugin.settings.postProcessingModel,
url: this.plugin.settings.postProcessingUrl, url: resolved.endpoint,
provider: this.plugin.settings.postProcessingProvider, provider: resolved.provider,
}); });
const title = await processor.process( const title = await processor.process(
finalText, finalText,
+82 -37
View File
@@ -35,6 +35,65 @@
height: 14px; height: 14px;
} }
/* ── Recording Status Meter ── */
.nibbleai-status-recording {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--text-error);
}
.nibbleai-status-paused {
color: var(--text-warning);
}
.nibbleai-status-processing {
color: var(--text-muted);
}
.nibbleai-status-idle {
color: var(--text-success);
}
.nibbleai-input-meter {
display: inline-flex;
align-items: center;
gap: 2px;
height: 12px;
}
.nibbleai-meter-bar {
width: 2px;
height: 4px;
border-radius: 999px;
background-color: currentColor;
opacity: 0.25;
transition: height 70ms ease-out, opacity 70ms ease-out;
}
.nibbleai-meter-bar-active {
height: 12px;
opacity: 1;
animation: nibbleai-meter-pulse 360ms ease-in-out infinite alternate;
}
.nibbleai-meter-bar:nth-child(2n).nibbleai-meter-bar-active {
animation-delay: 80ms;
}
.nibbleai-meter-bar:nth-child(3n).nibbleai-meter-bar-active {
animation-delay: 160ms;
}
@keyframes nibbleai-meter-pulse {
from {
transform: scaleY(0.55);
}
to {
transform: scaleY(1);
}
}
/* ── Model Browser Suggestion ── */ /* ── Model Browser Suggestion ── */
.model-suggestion { .model-suggestion {
padding: 4px 0; padding: 4px 0;
@@ -54,6 +113,14 @@
color: var(--text-on-accent); color: var(--text-on-accent);
font-size: 0.75em; font-size: 0.75em;
} }
.model-suggestion-stats {
display: flex;
flex-wrap: wrap;
gap: 0 12px;
font-size: 0.8em;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.model-suggestion-desc { .model-suggestion-desc {
font-size: 0.75em; font-size: 0.75em;
opacity: 0.5; opacity: 0.5;
@@ -79,62 +146,40 @@
font-size: 14px; font-size: 14px;
} }
/* ── Settings Tab Bar ── */ /* ── Settings Tab Bar (matches Waypoint's settings tabs) ── */
.nibbleai-tab-bar { .nibbleai-tab-bar {
display: flex; display: flex;
flex-wrap: wrap;
gap: 4px; gap: 4px;
padding: 4px 0 12px 0; margin-bottom: 20px;
border-bottom: 1px solid var(--background-modifier-border); border-bottom: 1px solid var(--background-modifier-border);
margin-bottom: 16px; padding-bottom: 8px;
} }
.nibbleai-tab { .nibbleai-tab {
display: inline-flex; background: none;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: 6px;
border: none; border: none;
background: transparent; cursor: var(--cursor-link, pointer);
color: var(--text-muted); color: var(--text-muted);
cursor: pointer; padding: 6px 14px;
border-radius: 6px 6px 0 0;
font-size: var(--font-ui-small); font-size: var(--font-ui-small);
transition: background 0.15s, color 0.15s; font-weight: var(--font-medium);
white-space: nowrap; transition: color 100ms, background 100ms;
user-select: none;
} }
.nibbleai-tab:hover { .nibbleai-tab:hover {
background: var(--background-modifier-hover);
color: var(--text-normal); color: var(--text-normal);
background: var(--background-modifier-hover);
} }
.nibbleai-tab-active { .nibbleai-tab.is-active {
background: var(--interactive-accent); color: var(--text-accent);
color: var(--text-on-accent); background: var(--background-modifier-active-hover);
} border-bottom: 2px solid var(--text-accent);
margin-bottom: -9px;
.nibbleai-tab-active:hover {
background: var(--interactive-accent-hover);
color: var(--text-on-accent);
}
.nibbleai-tab-icon svg {
width: 16px;
height: 16px;
display: block;
} }
/* ── Tab Content ── */ /* ── Tab Content ── */
.nibbleai-tab-content h2 {
margin-top: 0;
margin-bottom: 16px;
font-size: var(--font-ui-large);
font-weight: 700;
color: var(--text-normal);
}
.nibbleai-tab-content h3 { .nibbleai-tab-content h3 {
margin-top: 28px; margin-top: 28px;
margin-bottom: 10px; margin-bottom: 10px;