import { Editor, Notice } from "obsidian"; import { AIService } from "../AIService"; import { resolveChatProvider } from "../ProviderResolver"; import NibbleAI from "main"; export class Proofreader { private plugin: NibbleAI; constructor(plugin: NibbleAI) { this.plugin = plugin; } async fixSelection(editor: Editor): Promise { const selection = editor.getSelection(); if (!selection || selection.trim().length === 0) { new Notice("No text selected."); return; } const config = resolveChatProvider( this.plugin.app, this.plugin.settings, this.plugin.settings.proofreadingProvider || "openrouter" ); if (!config) { new Notice( "⚠️ No API key for selected provider. Check Settings \u2192 NibbleAI \u2192 API Keys." ); return; } 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 { text: corrected, upstream, usage } = await AIService.callChatCompletion( selection, systemPrompt, { apiKey: config.apiKey, 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, }, } ); if (!corrected || corrected.trim().length === 0) { new Notice("⚠️ AI returned empty result. No changes made."); return; } editor.replaceSelection(corrected); // 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 after ${elapsed()} (${model}): ${error instanceof Error ? error.message : String(error)}` ); } finally { window.clearInterval(ticker); progress.hide(); } } }