4 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
14 changed files with 451 additions and 191 deletions

No files matched your search

+8 -3
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
- **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.)
### 🏷️ Title Generation
@@ -71,7 +72,7 @@ Then copy the `main.js`, `manifest.json`, and `styles.css` to your vault's plugi
## Getting Started
### 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 |
|-----|----------|
@@ -132,10 +133,12 @@ This is useful for automation tools, Stream Deck, or scripting.
## 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`
- 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
- You can still type a model ID manually if you prefer
@@ -144,7 +147,7 @@ Wherever you need to select an AI model (post-processing, proofreading, title ge
## Settings Reference
### 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
| Setting | Default | Description |
@@ -187,6 +190,8 @@ Securely stored in your system keychain via Obsidian's SecretStorage. Never writ
| Model | `openai/gpt-4o-mini` | Model for proofreading |
| Temperature | `0.2` | Lower = more consistent |
| 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 |
### Title Generation
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "nibbleai",
"name": "NibbleAI",
"version": "1.2.1",
"version": "1.4.0",
"minAppVersion": "1.12.7",
"description": "AI-powered tools for your Obsidian vault: speech-to-text, proofreading, title generation, property filling, and more.",
"author": "Olivier",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "nibbleai",
"version": "1.2.1",
"version": "1.4.0",
"description": "AI-powered tools for your Obsidian vault",
"main": "main.js",
"scripts": {
+78 -9
View File
@@ -1,5 +1,5 @@
import axios from "axios";
import { PostProcessingProvider } from "./SettingsManager";
import { PostProcessingProvider, ReasoningEffort } from "./SettingsManager";
export interface ChatCompletionOptions {
apiKey: string;
@@ -8,8 +8,36 @@ export interface ChatCompletionOptions {
provider?: "anthropic" | "openai" | "openrouter" | "groq" | "custom";
temperature?: 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.
* Supports OpenAI-compatible chat completions and Anthropic native API.
@@ -20,13 +48,13 @@ export class AIService {
* @param userMessage - The user's input text
* @param systemPrompt - System-level instructions
* @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(
userMessage: string,
systemPrompt: string,
options: ChatCompletionOptions
): Promise<string> {
): Promise<ChatCompletionResult> {
const provider = options.provider || "openai";
const endpoint =
options.endpoint || "https://openrouter.ai/api/v1/chat/completions";
@@ -45,7 +73,8 @@ export class AIService {
userMessage: string,
systemPrompt: string,
options: ChatCompletionOptions
): Promise<string> {
): Promise<ChatCompletionResult> {
const maxTokens = options.maxTokens ?? 2000;
const response = await axios.post(
options.endpoint ||
"https://openrouter.ai/api/v1/chat/completions",
@@ -56,7 +85,15 @@ export class AIService {
{ role: "user", content: userMessage },
],
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: {
@@ -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(
userMessage: string,
systemPrompt: string,
options: ChatCompletionOptions
): Promise<string> {
): Promise<ChatCompletionResult> {
const maxTokens = options.maxTokens ?? 8192;
const response = await axios.post(
options.endpoint || "https://api.anthropic.com/v1/messages",
{
model: options.model,
max_tokens: options.maxTokens ?? 8192,
max_tokens: maxTokens,
system: systemPrompt,
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,
},
};
}
}
+149 -22
View File
@@ -4,9 +4,69 @@ interface OpenRouterModel {
id: string;
name: string;
description?: string;
/** USD per token, as decimal strings (e.g. "0.0000001"); "-1" means variable. */
pricing?: {
prompt: number;
completion: number;
prompt: string;
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 cached = false;
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);
this.apiKey = apiKey;
this.onChoose = onChoose;
this.setPlaceholder("Search OpenRouter models...");
this.setInstructions([
@@ -35,18 +101,34 @@ export class ModelSuggestModal extends SuggestModal<OpenRouterModel> {
this.allModels = (data.data || [])
.filter((m: OpenRouterModel) => m.id && !m.id.includes(":"))
.sort((a: OpenRouterModel, b: OpenRouterModel) => {
const aFree = a.pricing?.prompt === 0 ? 0 : 1;
const bFree = b.pricing?.prompt === 0 ? 0 : 1;
const aFree = this.isFree(a) ? 0 : 1;
const bFree = this.isFree(b) ? 0 : 1;
if (aFree !== bFree) return aFree - bFree;
return (a.name || a.id).localeCompare(b.name || b.id);
});
this.cached = true;
// The modal rendered its (empty) list before the fetch finished.
this.inputEl.dispatchEvent(new Event("input"));
} catch (e) {
// 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[] {
// A new render pass starts; stats for rows no longer shown aren't needed.
this.perfEls.clear();
const q = query.toLowerCase().trim();
if (!q) return this.allModels.slice(0, 50);
return this.allModels
@@ -64,30 +146,75 @@ export class ModelSuggestModal extends SuggestModal<OpenRouterModel> {
const nameEl = container.createDiv({ cls: "model-suggestion-name" });
nameEl.setText(model.name || model.id);
const idEl = container.createDiv({ cls: "model-suggestion-id" });
idEl.setText(model.id);
idEl.style.fontSize = "0.8em";
idEl.style.opacity = "0.6";
if (this.isFree(model)) {
nameEl.createSpan({ cls: "model-suggestion-badge", text: "Free" });
}
if (model.pricing?.prompt === 0 && model.pricing?.completion === 0) {
const badge = container.createSpan({ cls: "model-suggestion-badge" });
badge.setText("Free");
badge.style.marginLeft = "8px";
badge.style.padding = "0 6px";
badge.style.borderRadius = "4px";
badge.style.backgroundColor = "var(--color-green)";
badge.style.color = "var(--text-on-accent)";
badge.style.fontSize = "0.75em";
container.createDiv({ cls: "model-suggestion-id", text: model.id });
const stats = container.createDiv({ cls: "model-suggestion-stats" });
const price = model.pricing;
if (price && !this.isFree(model)) {
stats.createSpan({
text:
parseFloat(price.prompt) < 0
? "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) {
const descEl = container.createDiv({ cls: "model-suggestion-desc" });
descEl.setText(model.description.slice(0, 120));
descEl.style.fontSize = "0.75em";
descEl.style.opacity = "0.5";
container.createDiv({
cls: "model-suggestion-desc",
text: model.description.slice(0, 120),
});
}
}
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) {
this.onChoose(model.id);
}
+67 -54
View File
@@ -1,11 +1,13 @@
import NibbleAI from "main";
import { App, PluginSettingTab, Setting, setIcon } from "obsidian";
import { App, PluginSettingTab, SecretComponent, Setting } from "obsidian";
import {
SettingsManager,
PostProcessingProvider,
TranscriptionProvider,
CHAT_PROVIDERS,
PROVIDER_DEFAULT_MODELS,
ReasoningEffort,
getApiKey,
} from "./SettingsManager";
import { ModelSuggestModal } from "./ModelBrowser";
@@ -19,17 +21,16 @@ type TabId =
interface TabInfo {
id: TabId;
icon: string;
label: string;
}
const TABS: TabInfo[] = [
{ id: "api-keys", icon: "key", label: "API Keys" },
{ id: "transcription", icon: "mic", label: "Transcription" },
{ id: "proofreading", icon: "wand", label: "Proofreading" },
{ id: "title-generation", icon: "heading", label: "Title Generation" },
{ id: "property-filler", icon: "pencil", label: "Property Filler" },
{ id: "advanced", icon: "settings", label: "Advanced" },
{ id: "api-keys", label: "API Keys" },
{ id: "transcription", label: "Transcription" },
{ id: "proofreading", label: "Proofreading" },
{ id: "title-generation", label: "Title Generation" },
{ id: "property-filler", label: "Property Filler" },
{ id: "advanced", label: "Advanced" },
];
export class NibbleAISettingsTab extends PluginSettingTab {
@@ -59,12 +60,9 @@ export class NibbleAISettingsTab extends PluginSettingTab {
for (const tab of TABS) {
const tabBtn = tabBar.createEl("button", {
cls: `nibbleai-tab ${this.currentTab === tab.id ? "nibbleai-tab-active" : ""}`,
attr: { "data-tab": tab.id },
cls: `nibbleai-tab${this.currentTab === tab.id ? " is-active" : ""}`,
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", () => {
this.currentTab = tab.id;
this.display();
@@ -100,9 +98,8 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── API Keys Tab ──
private renderApiKeysTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "API Keys" });
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", {
@@ -113,50 +110,45 @@ export class NibbleAISettingsTab extends PluginSettingTab {
this.createApiKeySetting(containerEl,
"Groq API Key",
"For Whisper transcription and Groq chat models (groq.com)",
"gsk_...",
this.plugin.settings.groqApiKey,
this.plugin.settings.groqSecret,
async (value) => {
this.plugin.settings.groqApiKey = value;
this.plugin.settings.groqSecret = value;
await this.save();
}
);
this.createApiKeySetting(containerEl,
"OpenAI API Key",
"For GPT / OpenAI-compatible models",
"sk-...xxxx",
this.plugin.settings.openAiApiKey,
this.plugin.settings.openAiSecret,
async (value) => {
this.plugin.settings.openAiApiKey = value;
this.plugin.settings.openAiSecret = value;
await this.save();
}
);
this.createApiKeySetting(containerEl,
"Anthropic API Key",
"For Claude models (sk-ant-...)",
"sk-ant-...xxxx",
this.plugin.settings.anthropicApiKey,
this.plugin.settings.anthropicSecret,
async (value) => {
this.plugin.settings.anthropicApiKey = value;
this.plugin.settings.anthropicSecret = value;
await this.save();
}
);
this.createApiKeySetting(containerEl,
"OpenRouter API Key",
"For OpenRouter models — get one at openrouter.ai/keys.",
"sk-or-v1-...",
this.plugin.settings.openRouterApiKey,
this.plugin.settings.openRouterSecret,
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",
"sk-...xxxx",
this.plugin.settings.customApiKey,
this.plugin.settings.customSecret,
async (value) => {
this.plugin.settings.customApiKey = value;
this.plugin.settings.customSecret = value;
await this.save();
}
);
@@ -175,8 +167,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Transcription Tab ──
private renderTranscriptionTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Transcription" });
new Setting(containerEl)
.setName("Enable transcription")
.setDesc("General settings for the audio-to-text feature")
@@ -434,7 +424,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
}
private renderProofreadingTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Proofreading" });
containerEl.createEl("p", {
text: "Proofread selected text with AI. Right-click any selection or use the command palette.",
cls: "setting-item-description",
@@ -498,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,
"System prompt",
"Instructions for the AI on how to proofread. Guarded against prompt injection.",
@@ -526,7 +545,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Title Generation Tab ──
private renderTitleGenTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Title Generation" });
containerEl.createEl("p", {
text: "Generate a title for the current note \u2014 either rename the file or set a frontmatter property.",
cls: "setting-item-description",
@@ -603,7 +621,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Property Filler Tab ──
private renderPropertyFillerTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Property Filler" });
containerEl.createEl("p", {
text: "Fill any frontmatter property with AI-generated content.",
cls: "setting-item-description",
@@ -676,8 +693,6 @@ export class NibbleAISettingsTab extends PluginSettingTab {
// ── Advanced Tab ──
private renderAdvancedTab(containerEl: HTMLElement): void {
containerEl.createEl("h2", { text: "Advanced" });
new Setting(containerEl)
.setName("Debug mode")
.setDesc("Increase verbosity for troubleshooting")
@@ -722,19 +737,17 @@ export class NibbleAISettingsTab extends PluginSettingTab {
containerEl: HTMLElement,
name: string,
desc: string,
placeholder: string,
value: string,
onChange: (value: string) => Promise<void>
secretName: string,
onChange: (secretName: string) => Promise<void>
): void {
new Setting(containerEl)
.setName(name)
.setDesc(desc)
.addText((text) => {
text.setPlaceholder(placeholder)
.setValue(value)
.onChange(async (value) => await onChange(value));
text.inputEl.type = "password";
});
.addComponent((el) =>
new SecretComponent(this.app, el)
.setValue(secretName)
.onChange(async (value) => await onChange(value))
);
}
/**
@@ -801,9 +814,9 @@ export class NibbleAISettingsTab extends PluginSettingTab {
onChange: (provider: PostProcessingProvider) => Promise<void>
): void {
const configured = new Set(
CHAT_PROVIDERS.filter((p) => !!this.plugin.settings[p.apiKeyField]).map(
(p) => p.id
)
CHAT_PROVIDERS.filter(
(p) => !!getApiKey(this.app, this.plugin.settings[p.secretField])
).map((p) => p.id)
);
new Setting(containerEl)
@@ -859,7 +872,8 @@ export class NibbleAISettingsTab extends PluginSettingTab {
.setButtonText("Browse")
.setIcon("search")
.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);
textComponent.setValue(modelId);
}).open();
@@ -944,11 +958,10 @@ export class NibbleAISettingsTab extends PluginSettingTab {
);
this.createApiKeySetting(containerEl,
"Custom API Key",
"API key for the custom endpoint",
"sk-...xxxx",
this.plugin.settings.customApiKey,
"Keychain secret holding the key for the custom endpoint",
this.plugin.settings.customSecret,
async (value) => {
this.plugin.settings.customApiKey = value;
this.plugin.settings.customSecret = value;
await this.save();
}
);
+2 -1
View File
@@ -20,12 +20,13 @@ export class PostProcessor {
}
async process(text: string, prompt: string): Promise<string> {
return AIService.callChatCompletion(text, prompt, {
const result = await AIService.callChatCompletion(text, prompt, {
apiKey: this.config.apiKey,
model: this.config.model,
endpoint: this.config.url,
provider: this.config.provider,
maxTokens: 8192,
});
return result.text;
}
}
+10 -2
View File
@@ -1,4 +1,11 @@
import { CHAT_PROVIDERS, PROVIDER_URLS, PluginSettings, PostProcessingProvider } from "./SettingsManager";
import { App } from "obsidian";
import {
CHAT_PROVIDERS,
PROVIDER_URLS,
PluginSettings,
PostProcessingProvider,
getApiKey,
} from "./SettingsManager";
export interface ResolvedChatProvider {
apiKey: string;
@@ -13,13 +20,14 @@ export interface ResolvedChatProvider {
* 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 = settings[info.apiKeyField];
const apiKey = getApiKey(app, settings[info.secretField]);
const endpoint = provider === "custom" ? settings.customApiUrl : PROVIDER_URLS[provider];
if (!apiKey || !endpoint) return null;
+68 -50
View File
@@ -1,11 +1,15 @@
import { Plugin } from "obsidian";
import { App, Plugin } from "obsidian";
const SECRET_IDS: Partial<Record<keyof ApiKeysSettings, string>> = {
groqApiKey: "groq-api-key",
openAiApiKey: "openai-api-key",
anthropicApiKey: "anthropic-api-key",
customApiKey: "custom-api-key",
openRouterApiKey: "openrouter-api-key",
/**
* Fixed keychain names NibbleAI ≤ 1.2.1 wrote keys under, and the plain-text
* data.json fields older versions used. Only read by the one-time migration.
*/
const LEGACY_KEYS: Record<ApiKeySecretField, { field: string; secretId: string }> = {
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" | "groq" | "custom";
@@ -31,7 +35,7 @@ export const PROVIDER_DEFAULT_MODELS: Record<PostProcessingProvider, string> = {
export interface ChatProviderInfo {
id: PostProcessingProvider;
label: string;
apiKeyField: keyof ApiKeysSettings;
secretField: ApiKeySecretField;
}
/**
@@ -41,11 +45,11 @@ export interface ChatProviderInfo {
* Generation, Property Filler) offers the exact same providers.
*/
export const CHAT_PROVIDERS: ChatProviderInfo[] = [
{ id: "anthropic", label: "Anthropic", apiKeyField: "anthropicApiKey" },
{ id: "openai", label: "OpenAI", apiKeyField: "openAiApiKey" },
{ id: "groq", label: "Groq", apiKeyField: "groqApiKey" },
{ id: "openrouter", label: "OpenRouter", apiKeyField: "openRouterApiKey" },
{ id: "custom", label: "Custom", apiKeyField: "customApiKey" },
{ 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";
@@ -59,13 +63,25 @@ export const TRANSCRIPTION_PROVIDER_URLS: Record<TranscriptionProvider, string>
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 {
groqApiKey: string;
openAiApiKey: string;
anthropicApiKey: string;
customApiKey: string;
groqSecret: string;
openAiSecret: string;
anthropicSecret: string;
customSecret: string;
customApiUrl: string;
openRouterApiKey: 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 {
@@ -104,11 +120,17 @@ export interface PostProcessingSettings {
keepOriginalTranscription: boolean;
}
export type ReasoningEffort = "low" | "medium" | "high";
export interface ProofreadingSettings {
proofreadingProvider: AIProvider;
proofreadingModel: string;
proofreadingTemperature: 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;
proofreadingContextMenu: boolean;
}
@@ -146,12 +168,12 @@ export type PluginSettings = ApiKeysSettings &
// ── Defaults ──
export const DEFAULT_API_KEYS: ApiKeysSettings = {
groqApiKey: "",
openAiApiKey: "",
anthropicApiKey: "",
customApiKey: "",
groqSecret: "",
openAiSecret: "",
anthropicSecret: "",
customSecret: "",
customApiUrl: "",
openRouterApiKey: "",
openRouterSecret: "",
};
export const DEFAULT_TRANSCRIPTION: TranscriptionSettings = {
@@ -214,6 +236,8 @@ export const DEFAULT_PROOFREADING: ProofreadingSettings = {
proofreadingModel: "openai/gpt-4o-mini",
proofreadingTemperature: 0.2,
proofreadingMaxTokens: 2000,
proofreadingReasoning: false,
proofreadingEffort: "low",
proofreadingSystemPrompt: DEFAULT_PROOFREADING_SYSTEM_PROMPT,
proofreadingContextMenu: true,
};
@@ -265,35 +289,32 @@ export class SettingsManager {
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;
for (const [field, secretId] of Object.entries(SECRET_IDS)) {
const key = field as keyof ApiKeysSettings;
if (settings[key]) {
this.secrets.setSecret(secretId, settings[key]);
settings[key] = "";
for (const [secretField, { field, secretId }] of Object.entries(LEGACY_KEYS)) {
if (!(field in legacy)) continue;
const plainKey = legacy[field];
const name = secretField as ApiKeySecretField;
if (typeof plainKey === "string" && plainKey) {
this.secrets.setSecret(secretId, plainKey);
}
if (!settings[name] && this.secrets.getSecret(secretId)) {
settings[name] = secretId;
}
delete legacy[field];
migrated = true;
}
}
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 {
if (settings.postProcessingProvider) return false;
const legacyUrl = (settings as PluginSettings & { postProcessingUrl?: string })
@@ -338,17 +359,14 @@ export class SettingsManager {
await this.plugin.saveData(settings);
}
if (this.migrateKeysFromDataJson(settings)) {
if (this.migrateKeysToSecretNames(settings)) {
await this.plugin.saveData(settings);
}
this.loadKeysFromSecretStorage(settings);
return settings;
}
async saveSettings(settings: PluginSettings): Promise<void> {
this.syncKeysToSecretStorage(settings);
await this.plugin.saveData(settings);
this.loadKeysFromSecretStorage(settings);
}
}
+32 -5
View File
@@ -18,6 +18,7 @@ export class Proofreader {
}
const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.proofreadingProvider || "openrouter"
);
@@ -28,23 +29,34 @@ export class Proofreader {
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 {
const systemPrompt =
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.";
const corrected = await AIService.callChatCompletion(
const { text: corrected, upstream, usage } = await AIService.callChatCompletion(
selection,
systemPrompt,
{
apiKey: config.apiKey,
model: this.plugin.settings.proofreadingModel,
model,
endpoint: config.endpoint,
provider: config.provider,
temperature: this.plugin.settings.proofreadingTemperature,
maxTokens: this.plugin.settings.proofreadingMaxTokens,
reasoning: {
enabled: this.plugin.settings.proofreadingReasoning,
effort: this.plugin.settings.proofreadingEffort,
},
}
);
@@ -54,12 +66,27 @@ export class Proofreader {
}
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) {
console.error("Proofreading error:", error);
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();
}
}
}
+2 -1
View File
@@ -115,6 +115,7 @@ export class PropertyFiller {
}
const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.propertyGenProvider || "openrouter"
);
@@ -146,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.";
const prompt = promptTemplate.replace(/\{property\}/g, propertyName);
const generated = await AIService.callChatCompletion(
const { text: generated } = await AIService.callChatCompletion(
content,
prompt,
{
+2 -1
View File
@@ -31,6 +31,7 @@ export class TitleGenerator {
}
const config = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.titleGenProvider || "openrouter"
);
@@ -48,7 +49,7 @@ export class TitleGenerator {
this.plugin.settings.titleGenPrompt ||
"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,
prompt,
{
+8 -4
View File
@@ -9,6 +9,7 @@ import {
} from "./utils";
import { PostProcessor } from "../PostProcessor";
import { resolveChatProvider } from "../ProviderResolver";
import { getApiKey } from "../SettingsManager";
export class AudioHandler {
private plugin: NibbleAI;
@@ -31,14 +32,15 @@ export class AudioHandler {
}
getTranscriptionApiKey(): string {
switch (this.plugin.settings.transcriptionProvider) {
const { app, settings } = this.plugin;
switch (settings.transcriptionProvider) {
case "groq":
return this.plugin.settings.groqApiKey;
return getApiKey(app, settings.groqSecret);
case "openai":
case "azure":
return this.plugin.settings.openAiApiKey;
return getApiKey(app, settings.openAiSecret);
case "custom":
return this.plugin.settings.groqApiKey || this.plugin.settings.openAiApiKey;
return getApiKey(app, settings.groqSecret) || getApiKey(app, settings.openAiSecret);
}
}
@@ -162,6 +164,7 @@ export class AudioHandler {
// Post-process with LLM if enabled
if (this.plugin.settings.postProcessing) {
const resolved = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.postProcessingProvider
);
@@ -201,6 +204,7 @@ export class AudioHandler {
this.plugin.settings.createNoteFile
) {
const resolved = resolveChatProvider(
this.plugin.app,
this.plugin.settings,
this.plugin.settings.postProcessingProvider
);
+23 -37
View File
@@ -113,6 +113,14 @@
color: var(--text-on-accent);
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 {
font-size: 0.75em;
opacity: 0.5;
@@ -138,62 +146,40 @@
font-size: 14px;
}
/* ── Settings Tab Bar ── */
/* ── Settings Tab Bar (matches Waypoint's settings tabs) ── */
.nibbleai-tab-bar {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 4px 0 12px 0;
margin-bottom: 20px;
border-bottom: 1px solid var(--background-modifier-border);
margin-bottom: 16px;
padding-bottom: 8px;
}
.nibbleai-tab {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: 6px;
background: none;
border: none;
background: transparent;
cursor: var(--cursor-link, pointer);
color: var(--text-muted);
cursor: pointer;
padding: 6px 14px;
border-radius: 6px 6px 0 0;
font-size: var(--font-ui-small);
transition: background 0.15s, color 0.15s;
white-space: nowrap;
user-select: none;
font-weight: var(--font-medium);
transition: color 100ms, background 100ms;
}
.nibbleai-tab:hover {
background: var(--background-modifier-hover);
color: var(--text-normal);
background: var(--background-modifier-hover);
}
.nibbleai-tab-active {
background: var(--interactive-accent);
color: var(--text-on-accent);
}
.nibbleai-tab-active:hover {
background: var(--interactive-accent-hover);
color: var(--text-on-accent);
}
.nibbleai-tab-icon svg {
width: 16px;
height: 16px;
display: block;
.nibbleai-tab.is-active {
color: var(--text-accent);
background: var(--background-modifier-active-hover);
border-bottom: 2px solid var(--text-accent);
margin-bottom: -9px;
}
/* ── 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 {
margin-top: 28px;
margin-bottom: 10px;