Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
chore: remove dead TS variants of local reasoning stack
Gabriel Steinb63047a651c6
diff --git a/src/helpers/ModelManager.ts b/src/helpers/ModelManager.tsdeleted file mode 100644index 20125e11f..000000000--- a/src/helpers/ModelManager.ts+++ /dev/null@@ -1,285 +0,0 @@-import path from "path";-import { spawn } from "child_process";-import fs from "fs";-import { promises as fsPromises } from "fs";-import { app } from "electron";-import { modelRegistry } from "../models/ModelRegistry";-import { inferenceConfig } from "../config/InferenceConfig";-import { MODEL_CONSTRAINTS } from "../config/constants";-import { parseLlamaCppOutput } from "../utils/llamaOutputParser";-const { downloadFile: runtimeDownloadFile } = require("./downloadUtils");--// Error types-export class ModelError extends Error {- constructor(- message: string,- public code: string,- public details: Record<string, any> = {}- ) {- super(message);- this.name = "ModelError";- }-}--export class ModelNotFoundError extends ModelError {- constructor(modelId: string) {- super(`Model ${modelId} not found`, "MODEL_NOT_FOUND", { modelId });- }-}--export interface DownloadProgress {- modelId: string;- progress: number;- downloadedSize: number;- totalSize: number;-}--class ModelManager {- private modelsDir: string;- private llamaCppPath: string | null = null;- private downloadProgress = new Map<string, DownloadProgress>();- private activeDownloads = new Map<string, boolean>();-- constructor() {- this.modelsDir = this.getModelsDir();- }-- private getModelsDir(): string {- const homeDir = app.getPath("home");- return path.join(homeDir, ".cache", "openwhispr", "models");- }-- async ensureModelsDir(): Promise<void> {- await fsPromises.mkdir(this.modelsDir, { recursive: true });- }-- async isModelDownloaded(modelId: string): Promise<boolean> {- const modelInfo = modelRegistry.getModel(modelId);- if (!modelInfo) return false;-- const modelPath = path.join(this.modelsDir, modelInfo.model.fileName);- try {- const stats = await fsPromises.stat(modelPath);- return stats.size > MODEL_CONSTRAINTS.MIN_FILE_SIZE;- } catch {- return false;- }- }-- async downloadModel(- modelId: string,- onProgress?: (progress: number, downloaded: number, total: number) => void- ): Promise<string> {- if (this.activeDownloads.has(modelId)) {- throw new ModelError("Download already in progress", "DOWNLOAD_IN_PROGRESS", { modelId });- }-- await this.ensureModelsDir();-- const modelInfo = modelRegistry.getModel(modelId);- if (!modelInfo) {- throw new ModelNotFoundError(modelId);- }-- const { model, provider } = modelInfo;- const modelPath = path.join(this.modelsDir, model.fileName);-- if (await this.isModelDownloaded(modelId)) {- return modelPath;- }-- const downloadUrl = provider.getDownloadUrl(model);- this.activeDownloads.set(modelId, true);-- try {- await runtimeDownloadFile(downloadUrl, modelPath, {- onProgress: (downloadedSize: number, totalSize: number) => {- const progress = totalSize > 0 ? (downloadedSize / totalSize) * 100 : 0;- this.downloadProgress.set(modelId, {- modelId,- progress,- downloadedSize,- totalSize,- });- onProgress?.(progress, downloadedSize, totalSize);- },- });-- const stats = await fsPromises.stat(modelPath);- if (stats.size < MODEL_CONSTRAINTS.MIN_FILE_SIZE) {- await fsPromises.unlink(modelPath).catch(() => {});- throw new ModelError("Downloaded file appears to be corrupted", "DOWNLOAD_CORRUPTED", {- size: stats.size,- });- }-- return modelPath;- } finally {- this.downloadProgress.delete(modelId);- this.activeDownloads.delete(modelId);- }- }-- async deleteModel(modelId: string): Promise<void> {- const modelInfo = modelRegistry.getModel(modelId);- if (!modelInfo) return;-- const modelPath = path.join(this.modelsDir, modelInfo.model.fileName);- try {- await fsPromises.unlink(modelPath);- } catch (error: any) {- if (error.code !== "ENOENT") {- throw new ModelError(`Failed to delete model`, "DELETE_ERROR", {- modelId,- error: error.message,- });- }- }- }-- async deleteAllModels(): Promise<void> {- try {- await fsPromises.rm(this.modelsDir, { recursive: true, force: true });- } catch (error: any) {- throw new ModelError(- `Failed to delete models directory: ${error.message}`,- "DELETE_ALL_ERROR",- { error: error.message }- );- } finally {- await this.ensureModelsDir();- }- }-- getDownloadProgress(modelId: string): DownloadProgress | undefined {- return this.downloadProgress.get(modelId);- }-- async ensureLlamaCpp(): Promise<boolean> {- if (this.llamaCppPath) return true;-- // Dynamic import to avoid loading in frontend- const llamaCppInstaller = require("./llamaCppInstaller").default;-- if (await llamaCppInstaller.isInstalled()) {- this.llamaCppPath = llamaCppInstaller.getInstalledBinaryPath();- return true;- }-- const paths = [- "llama-cli",- "/usr/local/bin/llama-cli",- "/opt/homebrew/bin/llama-cli",- path.join(app.getPath("home"), ".local", "bin", "llama-cli"),- ];-- for (const p of paths) {- try {- if (p === "llama-cli") {- await new Promise((resolve, reject) => {- spawn("which", ["llama-cli"]).on("close", (code) =>- code === 0 ? resolve(p) : reject()- );- });- this.llamaCppPath = p;- return true;- } else {- await fsPromises.access(p, fs.constants.X_OK);- this.llamaCppPath = p;- return true;- }- } catch {- // Continue to next path- }- }-- throw new ModelError(- "llama.cpp not found. Please install it from the Local AI Models settings.",- "LLAMA_CPP_NOT_FOUND"- );- }-- async runInference(modelId: string, prompt: string, options: any = {}): Promise<string> {- await this.ensureLlamaCpp();-- const modelInfo = modelRegistry.getModel(modelId);- if (!modelInfo) {- throw new ModelNotFoundError(modelId);- }-- const { model, provider } = modelInfo;- const modelPath = path.join(this.modelsDir, model.fileName);-- if (!(await this.isModelDownloaded(modelId))) {- throw new ModelError(`Model ${modelId} is not downloaded`, "MODEL_NOT_DOWNLOADED");- }-- const config = inferenceConfig.getConfig();- const finalOptions = { ...config, ...options };- const formattedPrompt = provider.formatPrompt(prompt, "");-- const args = [- "-m",- modelPath,- "-p",- formattedPrompt,- "-n",- finalOptions.maxTokens.toString(),- "--temp",- finalOptions.temperature.toString(),- "--top-k",- finalOptions.topK.toString(),- "--top-p",- finalOptions.topP.toString(),- "--repeat-penalty",- finalOptions.repeatPenalty.toString(),- "--ctx-size",- finalOptions.contextSize.toString(),- "--no-display-prompt",- "-t",- finalOptions.threads.toString(),- ];-- return new Promise((resolve, reject) => {- const llamaProcess = spawn(this.llamaCppPath!, args);- let output = "";- let error = "";-- llamaProcess.stdout.on("data", (data) => {- output += data.toString();- });-- llamaProcess.stderr.on("data", (data) => {- error += data.toString();- });-- llamaProcess.on("close", (code) => {- if (code === 0) {- resolve(parseLlamaCppOutput(output));- } else {- reject(new ModelError(`Inference failed: ${error}`, "INFERENCE_ERROR"));- }- });-- setTimeout(() => {- llamaProcess.kill();- reject(new ModelError("Inference timeout", "INFERENCE_TIMEOUT"));- }, finalOptions.timeout);- });- }-- async getModelsWithStatus() {- const allModels = modelRegistry.getAllModels();-- return Promise.all(- allModels.map(async (model) => ({- ...model,- isDownloaded: await this.isModelDownloaded(model.id),- downloadProgress: this.downloadProgress.get(model.id)?.progress || 0,- isDownloading: this.activeDownloads.has(model.id),- }))- );- }-}--export default new ModelManager();diff --git a/src/helpers/llamaCppInstaller.ts b/src/helpers/llamaCppInstaller.tsdeleted file mode 100644index aa35bc846..000000000--- a/src/helpers/llamaCppInstaller.ts+++ /dev/null@@ -1,218 +0,0 @@-import { spawn } from "child_process";-import { app } from "electron";-import path from "path";-import fs from "fs";-import { promises as fsPromises } from "fs";-import https from "https";-import { createWriteStream } from "fs";-import * as tar from "tar";-import os from "os";--// Only import unzipper in main process-let unzipper: any;-if (typeof window === "undefined") {- unzipper = require("unzipper");-}--class LlamaCppInstaller {- private installDir: string;- private binPath: string | null = null;- private platform: string;- private arch: string;-- constructor() {- this.installDir = path.join(app.getPath("userData"), "llama-cpp");- this.platform = process.platform;- this.arch = process.arch;- }-- async ensureInstallDir(): Promise<void> {- await fsPromises.mkdir(this.installDir, { recursive: true });- }-- getBinaryName(): string {- return this.platform === "win32" ? "llama-cli.exe" : "llama-cli";- }-- getInstalledBinaryPath(): string {- return path.join(this.installDir, this.getBinaryName());- }-- async isInstalled(): Promise<boolean> {- try {- const binaryPath = this.getInstalledBinaryPath();- await fsPromises.access(binaryPath, fs.constants.X_OK);- this.binPath = binaryPath;- return true;- } catch {- return false;- }- }-- async checkSystemInstallation(): Promise<boolean> {- return new Promise((resolve) => {- const checkCommand = this.platform === "win32" ? "where" : "which";- spawn(checkCommand, ["llama-cli"])- .on("close", (code) => {- resolve(code === 0);- })- .on("error", () => {- resolve(false);- });- });- }-- async getVersion(): Promise<string | null> {- if (!(await this.isInstalled())) {- return null;- }-- return new Promise((resolve) => {- const proc = spawn(this.binPath!, ["--version"]);- let output = "";-- proc.stdout.on("data", (data) => {- output += data.toString();- });-- proc.on("close", () => {- const match = output.match(/version:\s*([^\s]+)/i);- resolve(match ? match[1] : "unknown");- });-- proc.on("error", () => {- resolve(null);- });- });- }-- getDownloadUrl(): string {- const baseUrl = "https://github.com/ggerganov/llama.cpp/releases/latest/download";-- if (this.platform === "darwin") {- return `${baseUrl}/llama-${this.arch === "arm64" ? "arm64" : "x64"}-apple-darwin.zip`;- } else if (this.platform === "linux") {- return `${baseUrl}/llama-x64-linux.tar.gz`;- } else if (this.platform === "win32") {- return `${baseUrl}/llama-x64-windows.zip`;- }-- throw new Error(`Unsupported platform: ${this.platform}`);- }-- async download(url: string, destPath: string): Promise<void> {- return new Promise((resolve, reject) => {- const file = createWriteStream(destPath);-- https- .get(url, (response) => {- if (response.statusCode === 302 || response.statusCode === 301) {- const redirectUrl = response.headers.location;- if (redirectUrl) {- this.download(redirectUrl, destPath).then(resolve).catch(reject);- return;- }- }-- if (response.statusCode !== 200) {- reject(new Error(`Download failed with status: ${response.statusCode}`));- return;- }-- response.pipe(file);-- file.on("finish", () => {- file.close();- resolve();- });-- file.on("error", (err) => {- fs.unlink(destPath, () => {});- reject(err);- });- })- .on("error", reject);- });- }-- async extract(archivePath: string): Promise<void> {- await this.ensureInstallDir();-- if (archivePath.endsWith(".tar.gz")) {- await tar.x({- file: archivePath,- cwd: this.installDir,- });- } else if (archivePath.endsWith(".zip")) {- await fs- .createReadStream(archivePath)- .pipe(unzipper.Extract({ path: this.installDir }))- .promise();- } else {- throw new Error("Unsupported archive format");- }- }-- async install(): Promise<{ success: boolean; error?: string }> {- try {- // Check if already installed- if (await this.isInstalled()) {- return { success: true };- }-- // Create install directory- await this.ensureInstallDir();-- // Download- const url = this.getDownloadUrl();- const archivePath = path.join(- this.installDir,- url.endsWith(".zip") ? "llama.zip" : "llama.tar.gz"- );-- console.log(`Downloading llama.cpp from ${url}...`);- await this.download(url, archivePath);-- // Extract- console.log("Extracting archive...");- await this.extract(archivePath);-- // Clean up archive- await fsPromises.unlink(archivePath);-- // Make binary executable on Unix- if (this.platform !== "win32") {- const binaryPath = this.getInstalledBinaryPath();- await fsPromises.chmod(binaryPath, 0o755);- }-- // Verify installation- if (await this.isInstalled()) {- return { success: true };- } else {- throw new Error("Installation verification failed");- }- } catch (error: any) {- console.error("llama.cpp installation error:", error);- return {- success: false,- error: error.message || "Installation failed",- };- }- }-- async uninstall(): Promise<{ success: boolean; error?: string }> {- try {- await fsPromises.rm(this.installDir, { recursive: true, force: true });- this.binPath = null;- return { success: true };- } catch (error: any) {- return {- success: false,- error: error.message || "Uninstall failed",- };- }- }-}--export default new LlamaCppInstaller();diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.tsdeleted file mode 100644index 91cea5a1e..000000000--- a/src/services/LocalReasoningService.ts+++ /dev/null@@ -1,126 +0,0 @@-import modelManager from "../helpers/ModelManager";-import { inferenceConfig } from "../config/InferenceConfig";-import { BaseReasoningService } from "./BaseReasoningService";-import { TOKEN_LIMITS } from "../config/constants";-import logger from "../utils/logger";--interface LocalReasoningConfig {- maxTokens?: number;- temperature?: number;- contextSize?: number;-}--class LocalReasoningService extends BaseReasoningService {- async processText(- text: string,- modelId: string = "qwen2.5-7b-instruct-q5_k_m",- agentName: string | null = null,- config: LocalReasoningConfig = {}- ): Promise<string> {- logger.logReasoning("LOCAL_MODEL_START", {- modelId,- agentName,- textLength: text.length,- configKeys: Object.keys(config),- });-- if (this.isProcessing) {- throw new Error("Already processing a request");- }-- this.isProcessing = true;- const startTime = Date.now();-- try {- logger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {- promptLength: text.length,- hasAgentName: !!agentName,- });-- // Get optimized config for reasoning use case- const inferenceOptions = inferenceConfig.getConfigForUseCase("reasoning");-- // Calculate max tokens with configurable limits- const maxTokens =- config.maxTokens ||- this.calculateMaxTokens(- text.length,- TOKEN_LIMITS.MIN_TOKENS,- TOKEN_LIMITS.MAX_TOKENS,- TOKEN_LIMITS.TOKEN_MULTIPLIER- );-- logger.logReasoning("LOCAL_MODEL_INFERENCE_CONFIG", {- modelId,- maxTokens,- temperature: config.temperature || inferenceOptions.temperature,- contextSize: config.contextSize || TOKEN_LIMITS.REASONING_CONTEXT_SIZE,- });-- // Run inference- const result = await modelManager.runInference(modelId, text, {- ...inferenceOptions,- maxTokens,- temperature: config.temperature || inferenceOptions.temperature,- contextSize: config.contextSize || TOKEN_LIMITS.REASONING_CONTEXT_SIZE,- });-- const processingTime = Date.now() - startTime;-- logger.logReasoning("LOCAL_MODEL_SUCCESS", {- modelId,- processingTimeMs: processingTime,- resultLength: result.length,- resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),- });-- return result;- } catch (error) {- const processingTime = Date.now() - startTime;-- logger.logReasoning("LOCAL_MODEL_ERROR", {- modelId,- processingTimeMs: processingTime,- error: (error as Error).message,- stack: (error as Error).stack,- });-- logger.error("LocalReasoningService error", { error: (error as Error).message }, "reasoning");- throw error;- } finally {- this.isProcessing = false;- }- }-- // Check if local reasoning is available- async isAvailable(): Promise<boolean> {- try {- await modelManager.ensureLlamaCpp();- return true;- } catch (error) {- logger.warn(- "Local reasoning not available",- { error: (error as Error).message },- "reasoning"- );- return false;- }- }-- // Get list of downloaded models- async getDownloadedModels() {- try {- const modelsWithStatus = await modelManager.getModelsWithStatus();- return modelsWithStatus.filter((model) => model.isDownloaded);- } catch (error) {- logger.error(- "Failed to get downloaded models",- { error: (error as Error).message },- "reasoning"- );- return [];- }- }-}--export default new LocalReasoningService();