Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

chore: formatting setup+ run

Gabriel Steinf04f9677b4b3
diff --git a/eslint.config.js b/eslint.config.js
index 67042d284..c433559c5 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -1,7 +1,7 @@
-import js from "@eslint/js";
-import globals from "globals";
+const js = require("@eslint/js");
+const globals = require("globals");
-export default [
+module.exports = [
{
ignores: [
"dist/**",
@@ -9,11 +9,12 @@ export default [
"src/dist/**",
"*.min.js",
"build/**",
+ "src/**", // src has its own config
],
},
// Main process files (CommonJS)
{
- files: ["*.js", "src/helpers/**/*.js", "src/utils/**/*.js", "scripts/**/*.js"],
+ files: ["**/*.js"],
languageOptions: {
ecmaVersion: 2022,
sourceType: "commonjs",
@@ -25,10 +26,13 @@ export default [
rules: {
...js.configs.recommended.rules,
// Relaxed rules - catch syntax errors but don't be too strict
- "no-unused-vars": ["warn", { varsIgnorePattern: "^_", argsIgnorePattern: "^_" }],
+ "no-unused-vars": ["warn", { varsIgnorePattern: "^_", argsIgnorePattern: "^_|^event|^err|^error" }],
"no-console": "off",
"no-empty": ["error", { allowEmptyCatch: true }],
"no-constant-condition": ["error", { checkLoops: false }],
+ "no-control-regex": "off",
+ "no-useless-catch": "off",
+ "no-async-promise-executor": "off",
"prefer-const": "off",
"no-var": "off",
},
diff --git a/package-lock.json b/package-lock.json
index b8f05e19e..3e266c04a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -51,6 +51,7 @@
"postcss": "^8.5.6",
"prettier": "^3.4.2",
"tailwindcss": "^4.1.10",
+ "typescript-eslint": "^8.20.0",
"vite": "^6.3.5"
}
},
@@ -1129,9 +1130,9 @@
}
},
"node_modules/@eslint-community/eslint-utils": {
- "version": "4.7.0",
- "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
- "integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==",
+ "version": "4.9.1",
+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
+ "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1161,9 +1162,9 @@
}
},
"node_modules/@eslint-community/regexpp": {
- "version": "4.12.1",
- "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz",
- "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==",
+ "version": "4.12.2",
+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",
+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",
"dev": true,
"license": "MIT",
"engines": {
@@ -3174,6 +3175,252 @@
"@types/node": "*"
}
},
+ "node_modules/@typescript-eslint/eslint-plugin": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.52.0.tgz",
+ "integrity": "sha512-okqtOgqu2qmZJ5iN4TWlgfF171dZmx2FzdOv2K/ixL2LZWDStL8+JgQerI2sa8eAEfoydG9+0V96m7V+P8yE1Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@eslint-community/regexpp": "^4.12.2",
+ "@typescript-eslint/scope-manager": "8.52.0",
+ "@typescript-eslint/type-utils": "8.52.0",
+ "@typescript-eslint/utils": "8.52.0",
+ "@typescript-eslint/visitor-keys": "8.52.0",
+ "ignore": "^7.0.5",
+ "natural-compare": "^1.4.0",
+ "ts-api-utils": "^2.4.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "@typescript-eslint/parser": "^8.52.0",
+ "eslint": "^8.57.0 || ^9.0.0",
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
+ "version": "7.0.5",
+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
+ "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/@typescript-eslint/parser": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.52.0.tgz",
+ "integrity": "sha512-iIACsx8pxRnguSYhHiMn2PvhvfpopO9FXHyn1mG5txZIsAaB6F0KwbFnUQN3KCiG3Jcuad/Cao2FAs1Wp7vAyg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/scope-manager": "8.52.0",
+ "@typescript-eslint/types": "8.52.0",
+ "@typescript-eslint/typescript-estree": "8.52.0",
+ "@typescript-eslint/visitor-keys": "8.52.0",
+ "debug": "^4.4.3"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0",
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/project-service": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.52.0.tgz",
+ "integrity": "sha512-xD0MfdSdEmeFa3OmVqonHi+Cciab96ls1UhIF/qX/O/gPu5KXD0bY9lu33jj04fjzrXHcuvjBcBC+D3SNSadaw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/tsconfig-utils": "^8.52.0",
+ "@typescript-eslint/types": "^8.52.0",
+ "debug": "^4.4.3"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/scope-manager": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.52.0.tgz",
+ "integrity": "sha512-ixxqmmCcc1Nf8S0mS0TkJ/3LKcC8mruYJPOU6Ia2F/zUUR4pApW7LzrpU3JmtePbRUTes9bEqRc1Gg4iyRnDzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.52.0",
+ "@typescript-eslint/visitor-keys": "8.52.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/tsconfig-utils": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.52.0.tgz",
+ "integrity": "sha512-jl+8fzr/SdzdxWJznq5nvoI7qn2tNYV/ZBAEcaFMVXf+K6jmXvAFrgo/+5rxgnL152f//pDEAYAhhBAZGrVfwg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/type-utils": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.52.0.tgz",
+ "integrity": "sha512-JD3wKBRWglYRQkAtsyGz1AewDu3mTc7NtRjR/ceTyGoPqmdS5oCdx/oZMWD5Zuqmo6/MpsYs0wp6axNt88/2EQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.52.0",
+ "@typescript-eslint/typescript-estree": "8.52.0",
+ "@typescript-eslint/utils": "8.52.0",
+ "debug": "^4.4.3",
+ "ts-api-utils": "^2.4.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0",
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/types": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.52.0.tgz",
+ "integrity": "sha512-LWQV1V4q9V4cT4H5JCIx3481iIFxH1UkVk+ZkGGAV1ZGcjGI9IoFOfg3O6ywz8QqCDEp7Inlg6kovMofsNRaGg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.52.0.tgz",
+ "integrity": "sha512-XP3LClsCc0FsTK5/frGjolyADTh3QmsLp6nKd476xNI9CsSsLnmn4f0jrzNoAulmxlmNIpeXuHYeEQv61Q6qeQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/project-service": "8.52.0",
+ "@typescript-eslint/tsconfig-utils": "8.52.0",
+ "@typescript-eslint/types": "8.52.0",
+ "@typescript-eslint/visitor-keys": "8.52.0",
+ "debug": "^4.4.3",
+ "minimatch": "^9.0.5",
+ "semver": "^7.7.3",
+ "tinyglobby": "^0.2.15",
+ "ts-api-utils": "^2.4.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
+ "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/@typescript-eslint/utils": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.52.0.tgz",
+ "integrity": "sha512-wYndVMWkweqHpEpwPhwqE2lnD2DxC6WVLupU/DOt/0/v+/+iQbbzO3jOHjmBMnhu0DgLULvOaU4h4pwHYi2oRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@eslint-community/eslint-utils": "^4.9.1",
+ "@typescript-eslint/scope-manager": "8.52.0",
+ "@typescript-eslint/types": "8.52.0",
+ "@typescript-eslint/typescript-estree": "8.52.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0",
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/visitor-keys": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.52.0.tgz",
+ "integrity": "sha512-ink3/Zofus34nmBsPjow63FP5M7IGff0RKAgqR6+CFpdk22M7aLwC9gOcLGYqr7MczLPzZVERW9hRog3O4n1sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "8.52.0",
+ "eslint-visitor-keys": "^4.2.1"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
"node_modules/@vitejs/plugin-react": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.6.0.tgz",
@@ -4442,9 +4689,9 @@
}
},
"node_modules/debug": {
- "version": "4.4.1",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
- "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==",
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -5503,11 +5750,14 @@
}
},
"node_modules/fdir": {
- "version": "6.4.6",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
- "integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
"peerDependencies": {
"picomatch": "^3 || ^4"
},
@@ -7868,9 +8118,9 @@
"license": "MIT"
},
"node_modules/semver": {
- "version": "7.7.2",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
- "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
+ "version": "7.7.3",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -8354,14 +8604,14 @@
"license": "MIT"
},
"node_modules/tinyglobby": {
- "version": "0.2.14",
- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
- "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "fdir": "^6.4.4",
- "picomatch": "^4.0.2"
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
},
"engines": {
"node": ">=12.0.0"
@@ -8410,6 +8660,19 @@
"utf8-byte-length": "^1.0.1"
}
},
+ "node_modules/ts-api-utils": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz",
+ "integrity": "sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.12"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.8.4"
+ }
+ },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -8484,6 +8747,30 @@
"node": ">=14.17"
}
},
+ "node_modules/typescript-eslint": {
+ "version": "8.52.0",
+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.52.0.tgz",
+ "integrity": "sha512-atlQQJ2YkO4pfTVQmQ+wvYQwexPDOIgo+RaVcD7gHgzy/IQA+XTyuxNM9M9TVXvttkF7koBHmcwisKdOAf2EcA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/eslint-plugin": "8.52.0",
+ "@typescript-eslint/parser": "8.52.0",
+ "@typescript-eslint/typescript-estree": "8.52.0",
+ "@typescript-eslint/utils": "8.52.0"
+ },
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^8.57.0 || ^9.0.0",
+ "typescript": ">=4.8.4 <6.0.0"
+ }
+ },
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
diff --git a/package.json b/package.json
index fa7c4616e..af67ee389 100644
--- a/package.json
+++ b/package.json
@@ -64,6 +64,7 @@
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
+ "typescript-eslint": "^8.20.0",
"prettier": "^3.4.2",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.10",
diff --git a/src/App.jsx b/src/App.jsx
index 676778bb4..6a510ec84 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -15,10 +15,7 @@ const SoundWaveIcon = ({ size = 16 }) => {
className={`bg-white rounded-full`}
style={{ width: size * 0.25, height: size * 0.6 }}
></div>
- <div
- className={`bg-white rounded-full`}
- style={{ width: size * 0.25, height: size }}
- ></div>
+ <div className={`bg-white rounded-full`} style={{ width: size * 0.25, height: size }}></div>
<div
className={`bg-white rounded-full`}
style={{ width: size * 0.25, height: size * 0.6 }}
@@ -53,10 +50,7 @@ const Tooltip = ({ children, content, emoji }) => {
return (
<div className="relative inline-block">
- <div
- onMouseEnter={() => setIsVisible(true)}
- onMouseLeave={() => setIsVisible(false)}
- >
+ <div onMouseEnter={() => setIsVisible(true)} onMouseLeave={() => setIsVisible(false)}>
{children}
</div>
{isVisible && (
@@ -80,8 +74,7 @@ export default function App() {
const buttonRef = useRef(null);
const { toast } = useToast();
const { hotkey } = useHotkey();
- const { isDragging, handleMouseDown, handleMouseUp } =
- useWindowDrag();
+ const { isDragging, handleMouseDown, handleMouseUp } = useWindowDrag();
const [dragStartPos, setDragStartPos] = useState(null);
const [hasDragged, setHasDragged] = useState(false);
@@ -107,12 +100,9 @@ export default function App() {
setWindowInteractivity(false);
}, [setWindowInteractivity]);
- const { isRecording, isProcessing, toggleListening, cancelRecording } = useAudioRecording(
- toast,
- {
- onToggle: handleDictationToggle,
- }
- );
+ const { isRecording, isProcessing, toggleListening, cancelRecording } = useAudioRecording(toast, {
+ onToggle: handleDictationToggle,
+ });
const handleClose = () => {
window.electronAPI.hideWindow();
@@ -279,8 +269,8 @@ export default function App() {
micState === "processing"
? "not-allowed !important"
: isDragging
- ? "grabbing !important"
- : "pointer !important",
+ ? "grabbing !important"
+ : "pointer !important",
transition:
"transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.25s ease-out",
}}
@@ -293,8 +283,7 @@ export default function App() {
<div
className="absolute inset-0 transition-colors duration-150"
style={{
- backgroundColor:
- micState === "hover" ? "rgba(0,0,0,0.1)" : "transparent",
+ backgroundColor: micState === "hover" ? "rgba(0,0,0,0.1)" : "transparent",
}}
></div>
@@ -343,10 +332,10 @@ export default function App() {
<button
className="w-full px-3 py-2 text-left text-sm hover:bg-white/10 focus:bg-white/10 focus:outline-none"
onClick={() => {
- setIsCommandMenuOpen(false);
- setWindowInteractivity(false);
- handleClose();
- }}
+ setIsCommandMenuOpen(false);
+ setWindowInteractivity(false);
+ handleClose();
+ }}
>
Hide this for now
</button>
diff --git a/src/assets/README.md b/src/assets/README.md
index b9c455bbc..0e242980e 100644
--- a/src/assets/README.md
+++ b/src/assets/README.md
@@ -7,7 +7,7 @@ This directory contains app icons and other assets for OpenWhispr.
For proper app packaging, you'll need the following icon files:
- `icon.icns` - macOS icon (1024x1024 recommended)
-- `icon.ico` - Windows icon (256x256 recommended)
+- `icon.ico` - Windows icon (256x256 recommended)
- `icon.png` - Linux icon (512x512 recommended)
## Icon Specifications
@@ -19,10 +19,11 @@ For proper app packaging, you'll need the following icon files:
## Creating Icons
You can create these icons using:
+
- Online converters like https://convertio.co/
- Design tools like Figma, Sketch, or Photoshop
- Command line tools like ImageMagick
## Placeholder
-Until you add your own icons, the app will use system default icons during development.
\ No newline at end of file
+Until you add your own icons, the app will use system default icons during development.
diff --git a/src/components.json b/src/components.json
index 80f297dfa..ff7556f76 100644
--- a/src/components.json
+++ b/src/components.json
@@ -18,4 +18,4 @@
"hooks": "@/components/hooks"
},
"iconLibrary": "lucide"
-}
\ No newline at end of file
+}
diff --git a/src/components/AIModelSelectorEnhanced.tsx b/src/components/AIModelSelectorEnhanced.tsx
index d9b8bdb1f..7b8576c19 100644
--- a/src/components/AIModelSelectorEnhanced.tsx
+++ b/src/components/AIModelSelectorEnhanced.tsx
@@ -1,12 +1,12 @@
-import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { Button } from './ui/button';
-import { Input } from './ui/input';
-import { Cloud, Lock, Brain, Zap, Globe, Cpu, Download, Check, Wrench } from 'lucide-react';
-import ApiKeyInput from './ui/ApiKeyInput';
-import { UnifiedModelPickerCompact } from './UnifiedModelPicker';
-import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from '../config/constants';
-import { REASONING_PROVIDERS } from '../utils/languages';
-import { modelRegistry } from '../models/ModelRegistry';
+import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { Cloud, Lock, Brain, Zap, Globe, Cpu, Download, Check, Wrench } from "lucide-react";
+import ApiKeyInput from "./ui/ApiKeyInput";
+import { UnifiedModelPickerCompact } from "./UnifiedModelPicker";
+import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
+import { REASONING_PROVIDERS } from "../utils/languages";
+import { modelRegistry } from "../models/ModelRegistry";
type CloudModelOption = {
value: string;
@@ -16,32 +16,32 @@ type CloudModelOption = {
ownedBy?: string;
};
-const ICON_BASE_PATH = '/assets/icons/providers';
+const ICON_BASE_PATH = "/assets/icons/providers";
const PROVIDER_ICON_MAP: Record<string, string> = {
- openai: 'openai',
- anthropic: 'anthropic',
- gemini: 'gemini',
- groq: 'groq',
- llama: 'llama',
- mistral: 'mistral',
- qwen: 'qwen',
- 'openai-oss': 'openai-oss',
+ openai: "openai",
+ anthropic: "anthropic",
+ gemini: "gemini",
+ groq: "groq",
+ llama: "llama",
+ mistral: "mistral",
+ qwen: "qwen",
+ "openai-oss": "openai-oss",
};
const OWNED_BY_ICON_RULES: Array<{ match: RegExp; icon: string }> = [
- { match: /(openai|system|default|gpt|davinci)/, icon: 'openai' },
- { match: /(azure)/, icon: 'openai' },
- { match: /(anthropic|claude)/, icon: 'anthropic' },
- { match: /(google|gemini)/, icon: 'gemini' },
- { match: /(meta|llama)/, icon: 'llama' },
- { match: /(mistral)/, icon: 'mistral' },
- { match: /(qwen|ali|tongyi)/, icon: 'qwen' },
- { match: /(openrouter|oss)/, icon: 'openai-oss' },
+ { match: /(openai|system|default|gpt|davinci)/, icon: "openai" },
+ { match: /(azure)/, icon: "openai" },
+ { match: /(anthropic|claude)/, icon: "anthropic" },
+ { match: /(google|gemini)/, icon: "gemini" },
+ { match: /(meta|llama)/, icon: "llama" },
+ { match: /(mistral)/, icon: "mistral" },
+ { match: /(qwen|ali|tongyi)/, icon: "qwen" },
+ { match: /(openrouter|oss)/, icon: "openai-oss" },
];
const getProviderIconPath = (providerId: string): string => {
- const iconId = PROVIDER_ICON_MAP[providerId] || 'openai';
+ const iconId = PROVIDER_ICON_MAP[providerId] || "openai";
return `${ICON_BASE_PATH}/${iconId}.svg`;
};
@@ -76,12 +76,12 @@ interface AIModelSelectorEnhancedProps {
showAlertDialog: (dialog: { title: string; description: string }) => void;
}
-// Provider Icon Component
+// Provider Icon Component
const ProviderIcon = ({ provider }: { provider: string }) => {
const iconClass = "w-5 h-5";
const [svgError, setSvgError] = React.useState(false);
- if (provider === 'custom') {
+ if (provider === "custom") {
return <Wrench className={iconClass} />;
}
@@ -89,36 +89,46 @@ const ProviderIcon = ({ provider }: { provider: string }) => {
const getFallbackIcon = () => {
switch (provider) {
// Cloud providers
- case 'openai': return <Brain className={iconClass} />;
- case 'anthropic': return <Zap className={iconClass} />;
- case 'gemini': return <Globe className={iconClass} />;
- case 'groq': return <Zap className={iconClass} />; // Lightning fast inference
+ case "openai":
+ return <Brain className={iconClass} />;
+ case "anthropic":
+ return <Zap className={iconClass} />;
+ case "gemini":
+ return <Globe className={iconClass} />;
+ case "groq":
+ return <Zap className={iconClass} />; // Lightning fast inference
// Local providers
- case 'qwen': return <Brain className={iconClass} />;
- case 'mistral': return <Zap className={iconClass} />;
- case 'llama': return <Cpu className={iconClass} />;
- case 'openai-oss': return <Globe className={iconClass} />;
- case 'custom': return <Wrench className={iconClass} />;
- default: return <Brain className={iconClass} />;
+ case "qwen":
+ return <Brain className={iconClass} />;
+ case "mistral":
+ return <Zap className={iconClass} />;
+ case "llama":
+ return <Cpu className={iconClass} />;
+ case "openai-oss":
+ return <Globe className={iconClass} />;
+ case "custom":
+ return <Wrench className={iconClass} />;
+ default:
+ return <Brain className={iconClass} />;
}
};
-
+
// Try to load SVG if it exists and we haven't had an error
if (!svgError) {
return (
<>
- <img
+ <img
src={`/assets/icons/providers/${provider}.svg`}
alt={`${provider} icon`}
className={iconClass}
onError={() => setSvgError(true)}
- style={{ display: svgError ? 'none' : 'block' }}
+ style={{ display: svgError ? "none" : "block" }}
/>
{svgError && getFallbackIcon()}
</>
);
}
-
+
return getFallbackIcon();
};
@@ -142,9 +152,9 @@ export default function AIModelSelectorEnhanced({
pasteFromClipboard,
showAlertDialog,
}: AIModelSelectorEnhancedProps) {
- const [selectedMode, setSelectedMode] = useState<'cloud' | 'local'>('cloud');
- const [selectedCloudProvider, setSelectedCloudProvider] = useState('openai');
- const [selectedLocalProvider, setSelectedLocalProvider] = useState('qwen');
+ const [selectedMode, setSelectedMode] = useState<"cloud" | "local">("cloud");
+ const [selectedCloudProvider, setSelectedCloudProvider] = useState("openai");
+ const [selectedLocalProvider, setSelectedLocalProvider] = useState("qwen");
const [downloadedModels, setDownloadedModels] = useState<Set<string>>(new Set());
const [downloadingModel, setDownloadingModel] = useState<string | null>(null);
const [customModelOptions, setCustomModelOptions] = useState<CloudModelOption[]>([]);
@@ -174,14 +184,12 @@ export default function AIModelSelectorEnhanced({
latestReasoningBaseRef.current = normalizedCustomReasoningBase;
}, [normalizedCustomReasoningBase]);
- const hasCustomBase = normalizedCustomReasoningBase !== '';
- const effectiveReasoningBase = hasCustomBase
- ? normalizedCustomReasoningBase
- : defaultOpenAIBase;
+ const hasCustomBase = normalizedCustomReasoningBase !== "";
+ const effectiveReasoningBase = hasCustomBase ? normalizedCustomReasoningBase : defaultOpenAIBase;
const loadRemoteModels = useCallback(
async (baseOverride?: string, force = false) => {
- const rawBase = (baseOverride ?? cloudReasoningBaseUrl) || '';
+ const rawBase = (baseOverride ?? cloudReasoningBaseUrl) || "";
const normalizedBase = normalizeBaseUrl(rawBase);
if (!normalizedBase) {
@@ -222,19 +230,24 @@ export default function AIModelSelectorEnhanced({
? keyFromState
: await window.electronAPI?.getOpenAIKey?.();
- if (!normalizedBase.includes('://')) {
+ if (!normalizedBase.includes("://")) {
if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
- setCustomModelsError('Enter a full base URL including protocol (e.g. https://server/v1).');
+ setCustomModelsError(
+ "Enter a full base URL including protocol (e.g. https://server/v1)."
+ );
setCustomModelsLoading(false);
}
return;
}
// Security: Only allow HTTPS endpoints (except localhost for development)
- const isLocalhost = normalizedBase.includes('://localhost') || normalizedBase.includes('://127.0.0.1');
- if (!normalizedBase.startsWith('https://') && !isLocalhost) {
+ const isLocalhost =
+ normalizedBase.includes("://localhost") || normalizedBase.includes("://127.0.0.1");
+ if (!normalizedBase.startsWith("https://") && !isLocalhost) {
if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
- setCustomModelsError('Only HTTPS endpoints are allowed (except localhost for testing).');
+ setCustomModelsError(
+ "Only HTTPS endpoints are allowed (except localhost for testing)."
+ );
setCustomModelsLoading(false);
}
return;
@@ -245,15 +258,15 @@ export default function AIModelSelectorEnhanced({
headers.Authorization = `Bearer ${apiKey}`;
}
- const modelsUrl = buildApiUrl(normalizedBase, '/models');
+ const modelsUrl = buildApiUrl(normalizedBase, "/models");
const response = await fetch(modelsUrl, {
- method: 'GET',
+ method: "GET",
headers,
});
if (!response.ok) {
- const errorText = await response.text().catch(() => '');
+ const errorText = await response.text().catch(() => "");
const summary = errorText
? `${response.status} ${errorText.slice(0, 200)}`
: `${response.status} ${response.statusText}`;
@@ -265,8 +278,8 @@ export default function AIModelSelectorEnhanced({
const rawModels = Array.isArray(payload?.data)
? payload.data
: Array.isArray(payload?.models)
- ? payload.models
- : [];
+ ? payload.models
+ : [];
const mappedModels = (rawModels as Array<any>)
.map((item) => {
@@ -274,13 +287,12 @@ export default function AIModelSelectorEnhanced({
if (!value) {
return null;
}
- const ownedBy = typeof item?.owned_by === 'string' ? item.owned_by : undefined;
+ const ownedBy = typeof item?.owned_by === "string" ? item.owned_by : undefined;
const icon = resolveOwnedByIcon(ownedBy);
return {
value,
label: item?.id || item?.name || value,
- description:
- item?.description || (ownedBy ? `Owner: ${ownedBy}` : undefined),
+ description: item?.description || (ownedBy ? `Owner: ${ownedBy}` : undefined),
icon,
ownedBy,
} as CloudModelOption;
@@ -300,12 +312,11 @@ export default function AIModelSelectorEnhanced({
}
} catch (error) {
if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
- const message =
- (error as Error).message || 'Unable to load models from endpoint.';
+ const message = (error as Error).message || "Unable to load models from endpoint.";
const unauthorized = /\b(401|403)\b/.test(message);
if (unauthorized && !apiKey) {
setCustomModelsError(
- 'Endpoint rejected the request (401/403). Add an API key or adjust server auth settings.'
+ "Endpoint rejected the request (401/403). Add an API key or adjust server auth settings."
);
} else {
setCustomModelsError(message);
@@ -324,9 +335,8 @@ export default function AIModelSelectorEnhanced({
[cloudReasoningBaseUrl, openaiApiKey, reasoningModel, setReasoningModel]
);
const trimmedCustomBase = customBaseInput.trim();
- const hasSavedCustomBase = Boolean((cloudReasoningBaseUrl || '').trim());
- const isCustomBaseDirty =
- trimmedCustomBase !== (cloudReasoningBaseUrl || '').trim();
+ const hasSavedCustomBase = Boolean((cloudReasoningBaseUrl || "").trim());
+ const isCustomBaseDirty = trimmedCustomBase !== (cloudReasoningBaseUrl || "").trim();
const displayedCustomModels = useMemo<CloudModelOption[]>(() => {
if (isCustomBaseDirty) {
return [];
@@ -334,11 +344,11 @@ export default function AIModelSelectorEnhanced({
return customModelOptions;
}, [isCustomBaseDirty, customModelOptions]);
- const cloudProviders = ['openai', 'anthropic', 'gemini', 'groq', 'custom'];
+ const cloudProviders = ["openai", "anthropic", "gemini", "groq", "custom"];
const localProviders = modelRegistry.getAllProviders().map((p) => p.id);
const openaiModelOptions = useMemo<CloudModelOption[]>(() => {
- const iconPath = getProviderIconPath('openai');
+ const iconPath = getProviderIconPath("openai");
return REASONING_PROVIDERS.openai.models.map((model) => ({
...model,
icon: iconPath,
@@ -346,11 +356,11 @@ export default function AIModelSelectorEnhanced({
}, []);
const selectedCloudModels = useMemo<CloudModelOption[]>(() => {
- if (selectedCloudProvider === 'openai') {
+ if (selectedCloudProvider === "openai") {
return openaiModelOptions;
}
- if (selectedCloudProvider === 'custom') {
+ if (selectedCloudProvider === "custom") {
return displayedCustomModels;
}
@@ -398,19 +408,19 @@ export default function AIModelSelectorEnhanced({
// Initialize based on current provider
useEffect(() => {
if (localProviders.includes(localReasoningProvider)) {
- setSelectedMode('local');
+ setSelectedMode("local");
setSelectedLocalProvider(localReasoningProvider);
} else if (cloudProviders.includes(localReasoningProvider)) {
- setSelectedMode('cloud');
+ setSelectedMode("cloud");
setSelectedCloudProvider(localReasoningProvider);
}
-
+
// Check downloaded models
checkDownloadedModels();
}, []);
-
+
useEffect(() => {
- if (selectedCloudProvider !== 'custom') {
+ if (selectedCloudProvider !== "custom") {
return;
}
@@ -439,36 +449,36 @@ export default function AIModelSelectorEnhanced({
try {
const result = await window.electronAPI?.modelGetAll?.();
if (result && Array.isArray(result)) {
- const downloaded = new Set(result.filter(m => m.isDownloaded).map(m => m.id));
+ const downloaded = new Set(result.filter((m) => m.isDownloaded).map((m) => m.id));
setDownloadedModels(downloaded);
}
} catch (error) {
- console.error('Failed to check downloaded models:', error);
+ console.error("Failed to check downloaded models:", error);
}
};
-
+
// Handle model download with minimal code
const downloadModel = async (modelId: string) => {
setDownloadingModel(modelId);
try {
await window.electronAPI?.modelDownload?.(modelId);
- setDownloadedModels(prev => new Set([...prev, modelId]));
+ setDownloadedModels((prev) => new Set([...prev, modelId]));
if (!reasoningModel) setReasoningModel(modelId);
} catch (error) {
- console.error('Download failed:', error);
+ console.error("Download failed:", error);
} finally {
setDownloadingModel(null);
}
};
- const handleModeChange = async (newMode: 'cloud' | 'local') => {
+ const handleModeChange = async (newMode: "cloud" | "local") => {
setSelectedMode(newMode);
-
- if (newMode === 'cloud') {
+
+ if (newMode === "cloud") {
// Switch to cloud mode
setLocalReasoningProvider(selectedCloudProvider);
- if (selectedCloudProvider === 'custom') {
+ if (selectedCloudProvider === "custom") {
setCustomBaseInput(cloudReasoningBaseUrl);
lastLoadedBaseRef.current = null;
pendingBaseRef.current = null;
@@ -481,7 +491,8 @@ export default function AIModelSelectorEnhanced({
return;
}
- const provider = REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS];
+ const provider =
+ REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS];
if (provider?.models?.length > 0) {
setReasoningModel(provider.models[0].value);
}
@@ -498,9 +509,9 @@ export default function AIModelSelectorEnhanced({
const handleCloudProviderChange = (provider: string) => {
setSelectedCloudProvider(provider);
setLocalReasoningProvider(provider);
-
+
// Update model to first available
- if (provider === 'custom') {
+ if (provider === "custom") {
setCustomBaseInput(cloudReasoningBaseUrl);
lastLoadedBaseRef.current = null;
pendingBaseRef.current = null;
@@ -531,17 +542,17 @@ export default function AIModelSelectorEnhanced({
const getProviderColor = (provider: string) => {
const colors: Record<string, string> = {
- 'openai': 'green',
- 'anthropic': 'purple',
- 'gemini': 'blue',
- 'groq': 'orange', // Fast and fiery like Groq
- 'qwen': 'indigo',
- 'mistral': 'orange',
- 'llama': 'blue',
- 'openai-oss': 'teal',
- 'custom': 'cyan'
+ openai: "green",
+ anthropic: "purple",
+ gemini: "blue",
+ groq: "orange", // Fast and fiery like Groq
+ qwen: "indigo",
+ mistral: "orange",
+ llama: "blue",
+ "openai-oss": "teal",
+ custom: "cyan",
};
- return colors[provider] || 'gray';
+ return colors[provider] || "gray";
};
return (
@@ -549,9 +560,7 @@ export default function AIModelSelectorEnhanced({
{/* Enable/Disable Toggle */}
<div className="flex items-center justify-between p-4 bg-green-50 border border-green-200 rounded-xl">
<div>
- <label className="text-sm font-medium text-green-800">
- Enable AI Text Enhancement
- </label>
+ <label className="text-sm font-medium text-green-800">Enable AI Text Enhancement</label>
<p className="text-xs text-green-700">
Use AI to automatically improve transcription quality
</p>
@@ -563,12 +572,16 @@ export default function AIModelSelectorEnhanced({
checked={useReasoningModel}
onChange={(e) => setUseReasoningModel(e.target.checked)}
/>
- <div className={`w-11 h-6 bg-gray-200 rounded-full transition-colors duration-200 ${
- useReasoningModel ? "bg-green-600" : "bg-gray-300"
- }`}>
- <div className={`absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition-transform duration-200 ${
- useReasoningModel ? "translate-x-5" : "translate-x-0"
- }`} />
+ <div
+ className={`w-11 h-6 bg-gray-200 rounded-full transition-colors duration-200 ${
+ useReasoningModel ? "bg-green-600" : "bg-gray-300"
+ }`}
+ >
+ <div
+ className={`absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition-transform duration-200 ${
+ useReasoningModel ? "translate-x-5" : "translate-x-0"
+ }`}
+ />
</div>
</label>
</div>
@@ -578,9 +591,9 @@ export default function AIModelSelectorEnhanced({
{/* Cloud vs Local Selection */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<button
- onClick={() => handleModeChange('cloud')}
+ onClick={() => handleModeChange("cloud")}
className={`p-4 border-2 rounded-xl text-left transition-all cursor-pointer ${
- selectedMode === 'cloud'
+ selectedMode === "cloud"
? "border-indigo-500 bg-indigo-50"
: "border-neutral-200 bg-white hover:border-neutral-300"
}`}
@@ -600,9 +613,9 @@ export default function AIModelSelectorEnhanced({
</button>
<button
- onClick={() => handleModeChange('local')}
+ onClick={() => handleModeChange("local")}
className={`p-4 border-2 rounded-xl text-left transition-all cursor-pointer ${
- selectedMode === 'local'
+ selectedMode === "local"
? "border-indigo-500 bg-indigo-50"
: "border-neutral-200 bg-white hover:border-neutral-300"
}`}
@@ -623,7 +636,7 @@ export default function AIModelSelectorEnhanced({
</div>
{/* Provider Content */}
- {selectedMode === 'cloud' ? (
+ {selectedMode === "cloud" ? (
<div className="space-y-4">
{/* Cloud Provider Tabs */}
<div className="border border-gray-200 rounded-xl overflow-hidden">
@@ -632,9 +645,10 @@ export default function AIModelSelectorEnhanced({
const isSelected = selectedCloudProvider === provider;
const color = getProviderColor(provider);
const providerDisplayName =
- provider === 'custom'
- ? 'Custom'
- : REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS]?.name || provider;
+ provider === "custom"
+ ? "Custom"
+ : REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS]?.name ||
+ provider;
return (
<button
key={provider}
@@ -642,12 +656,16 @@ export default function AIModelSelectorEnhanced({
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 font-medium transition-all ${
isSelected
? `text-${color}-700 border-b-2`
- : 'text-gray-600 hover:bg-gray-100'
+ : "text-gray-600 hover:bg-gray-100"
}`}
- style={isSelected ? {
- borderBottomColor: `rgb(99 102 241)`,
- backgroundColor: 'rgb(238 242 255)'
- } : {}}
+ style={
+ isSelected
+ ? {
+ borderBottomColor: `rgb(99 102 241)`,
+ backgroundColor: "rgb(238 242 255)",
+ }
+ : {}
+ }
>
<ProviderIcon provider={provider} />
<span>{providerDisplayName}</span>
@@ -658,7 +676,7 @@ export default function AIModelSelectorEnhanced({
<div className="p-4">
{/* Use UnifiedModelPickerCompact for cloud models */}
- {selectedCloudProvider === 'custom' ? (
+ {selectedCloudProvider === "custom" ? (
<>
<div className="space-y-3">
<h4 className="font-medium text-gray-900">Endpoint Settings</h4>
@@ -682,16 +700,30 @@ export default function AIModelSelectorEnhanced({
size="sm"
variant="outline"
onClick={handleRefreshCustomModels}
- disabled={customModelsLoading || (!trimmedCustomBase && !hasSavedCustomBase)}
+ disabled={
+ customModelsLoading || (!trimmedCustomBase && !hasSavedCustomBase)
+ }
>
- {customModelsLoading ? 'Loading models...' : isCustomBaseDirty ? 'Apply & Refresh' : 'Refresh Models'}
+ {customModelsLoading
+ ? "Loading models..."
+ : isCustomBaseDirty
+ ? "Apply & Refresh"
+ : "Refresh Models"}
</Button>
</div>
{isCustomBaseDirty && (
- <p className="text-xs text-amber-600">Apply the new base URL to refresh models.</p>
+ <p className="text-xs text-amber-600">
+ Apply the new base URL to refresh models.
+ </p>
)}
<p className="text-xs text-gray-600">
- We'll query <code>{hasCustomBase ? `${effectiveReasoningBase}/models` : `${defaultOpenAIBase}/models`}</code> for available models.
+ We'll query{" "}
+ <code>
+ {hasCustomBase
+ ? `${effectiveReasoningBase}/models`
+ : `${defaultOpenAIBase}/models`}
+ </code>{" "}
+ for available models.
</p>
</div>
@@ -707,9 +739,7 @@ export default function AIModelSelectorEnhanced({
<div className="space-y-3 pt-4 border-t border-gray-200">
<h4 className="text-sm font-medium text-gray-700">Available Models</h4>
{!hasCustomBase && (
- <p className="text-xs text-amber-600">
- Enter a base URL to load models.
- </p>
+ <p className="text-xs text-amber-600">Enter a base URL to load models.</p>
)}
{hasCustomBase && (
<>
@@ -719,11 +749,13 @@ export default function AIModelSelectorEnhanced({
{customModelsError && (
<p className="text-xs text-red-600">{customModelsError}</p>
)}
- {!customModelsLoading && !customModelsError && customModelOptions.length === 0 && (
- <p className="text-xs text-amber-600">
- No models returned by this endpoint.
- </p>
- )}
+ {!customModelsLoading &&
+ !customModelsError &&
+ customModelOptions.length === 0 && (
+ <p className="text-xs text-amber-600">
+ No models returned by this endpoint.
+ </p>
+ )}
</>
)}
<UnifiedModelPickerCompact
@@ -744,9 +776,9 @@ export default function AIModelSelectorEnhanced({
/>
</div>
- {/* API Key Configuration */}
+ {/* API Key Configuration */}
<div className="mt-4 pt-4 border-t border-gray-200">
- {selectedCloudProvider === 'openai' && (
+ {selectedCloudProvider === "openai" && (
<div className="space-y-3">
<h4 className="font-medium text-gray-900">API Configuration</h4>
<ApiKeyInput
@@ -769,7 +801,7 @@ export default function AIModelSelectorEnhanced({
</div>
)}
- {selectedCloudProvider === 'anthropic' && (
+ {selectedCloudProvider === "anthropic" && (
<div className="space-y-3">
<h4 className="font-medium text-gray-900">API Configuration</h4>
<div className="flex gap-2">
@@ -794,7 +826,7 @@ export default function AIModelSelectorEnhanced({
</div>
)}
- {selectedCloudProvider === 'gemini' && (
+ {selectedCloudProvider === "gemini" && (
<div className="space-y-3">
<h4 className="font-medium text-gray-900">API Configuration</h4>
<div className="flex gap-2">
@@ -819,7 +851,7 @@ export default function AIModelSelectorEnhanced({
</div>
)}
- {selectedCloudProvider === 'groq' && (
+ {selectedCloudProvider === "groq" && (
<div className="space-y-3">
<h4 className="font-medium text-gray-900">API Configuration</h4>
<div className="flex gap-2">
@@ -863,13 +895,17 @@ export default function AIModelSelectorEnhanced({
onClick={() => handleLocalProviderChange(provider)}
className={`flex items-center justify-center gap-2 px-4 py-3 font-medium transition-all whitespace-nowrap ${
isSelected
- ? 'text-purple-700 border-b-2'
- : 'text-gray-600 hover:bg-gray-100'
+ ? "text-purple-700 border-b-2"
+ : "text-gray-600 hover:bg-gray-100"
}`}
- style={isSelected ? {
- borderBottomColor: 'rgb(147 51 234)',
- backgroundColor: 'rgb(250 245 255)'
- } : {}}
+ style={
+ isSelected
+ ? {
+ borderBottomColor: "rgb(147 51 234)",
+ backgroundColor: "rgb(250 245 255)",
+ }
+ : {}
+ }
>
<ProviderIcon provider={provider} />
<span>{providerData?.name}</span>
@@ -885,31 +921,39 @@ export default function AIModelSelectorEnhanced({
{(() => {
const provider = modelRegistry.getProvider(selectedLocalProvider);
if (!provider || !provider.models) {
- return <p className="text-sm text-gray-500">No models available for this provider</p>;
+ return (
+ <p className="text-sm text-gray-500">
+ No models available for this provider
+ </p>
+ );
}
-
+
return (
<div className="space-y-2">
{provider.models.map((model) => {
const isDownloaded = downloadedModels.has(model.id);
const isDownloading = downloadingModel === model.id;
const isSelected = reasoningModel === model.id;
-
+
return (
<div
key={model.id}
className={`p-3 rounded-lg border-2 transition-all ${
isSelected
- ? 'border-purple-500 bg-purple-50'
- : 'border-gray-200 bg-white hover:border-gray-300'
+ ? "border-purple-500 bg-purple-50"
+ : "border-gray-200 bg-white hover:border-gray-300"
}`}
>
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="font-medium text-gray-900">{model.name}</div>
- <div className="text-xs text-gray-600 mt-1">{model.description}</div>
+ <div className="text-xs text-gray-600 mt-1">
+ {model.description}
+ </div>
<div className="flex items-center gap-2 mt-1">
- <span className="text-xs text-gray-500">Size: {model.size}</span>
+ <span className="text-xs text-gray-500">
+ Size: {model.size}
+ </span>
{isDownloaded && (
<span className="text-xs text-green-600 bg-green-100 px-2 py-0.5 rounded">
<Check className="inline w-3 h-3 mr-1" />
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 5cd7d9857..a897aea54 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -137,8 +137,7 @@ export default function ControlPanel() {
const deleteTranscription = async (id: number) => {
showConfirmDialog({
title: "Delete Transcription",
- description:
- "Are you certain you wish to remove this inscription from your records?",
+ description: "Are you certain you wish to remove this inscription from your records?",
onConfirm: async () => {
try {
const result = await window.electronAPI.deleteTranscription(id);
@@ -147,8 +146,7 @@ export default function ControlPanel() {
} else {
showAlertDialog({
title: "Delete Failed",
- description:
- "Failed to delete transcription. It may have already been removed.",
+ description: "Failed to delete transcription. It may have already been removed.",
});
}
} catch (error) {
@@ -186,18 +184,13 @@ export default function ControlPanel() {
<>
{/* Update notification badge */}
{!updateStatus.isDevelopment &&
- (updateStatus.updateAvailable ||
- updateStatus.updateDownloaded) && (
+ (updateStatus.updateAvailable || updateStatus.updateDownloaded) && (
<div className="relative">
<div className="absolute -top-1 -right-1 w-2 h-2 bg-blue-500 rounded-full"></div>
</div>
)}
<SupportDropdown />
- <Button
- variant="ghost"
- size="icon"
- onClick={() => setShowSettings(!showSettings)}
- >
+ <Button variant="ghost" size="icon" onClick={() => setShowSettings(!showSettings)}>
<Settings size={16} />
</Button>
</>
@@ -247,13 +240,10 @@ export default function ControlPanel() {
No transcriptions yet
</h3>
<p className="text-neutral-600 mb-4 max-w-sm mx-auto">
- Press your hotkey to start recording and create your first
- transcription.
+ Press your hotkey to start recording and create your first transcription.
</p>
<div className="bg-neutral-50 border border-neutral-200 rounded-lg p-4 max-w-md mx-auto">
- <h4 className="font-medium text-neutral-800 mb-2">
- Quick Start:
- </h4>
+ <h4 className="font-medium text-neutral-800 mb-2">Quick Start:</h4>
<ol className="text-sm text-neutral-600 text-left space-y-1">
<li>1. Click in any text field</li>
<li>
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 17dfa8c71..53880711c 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -46,7 +46,6 @@ interface OnboardingFlowProps {
onComplete: () => void;
}
-
type ReasoningModelOption = {
value: string;
label: string;
@@ -188,10 +187,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
setCustomModelsError(null);
try {
// Security: Only allow HTTPS endpoints (except localhost for development)
- const isLocalhost = normalizedReasoningBaseUrl.includes('://localhost') ||
- normalizedReasoningBaseUrl.includes('://127.0.0.1');
- if (!normalizedReasoningBaseUrl.startsWith('https://') && !isLocalhost) {
- throw new Error('Only HTTPS endpoints are allowed (except localhost for testing).');
+ const isLocalhost =
+ normalizedReasoningBaseUrl.includes("://localhost") ||
+ normalizedReasoningBaseUrl.includes("://127.0.0.1");
+ if (!normalizedReasoningBaseUrl.startsWith("https://") && !isLocalhost) {
+ throw new Error("Only HTTPS endpoints are allowed (except localhost for testing).");
}
const headers: Record<string, string> = {};
@@ -219,8 +219,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const rawModels = Array.isArray(payload?.data)
? payload.data
: Array.isArray(payload?.models)
- ? payload.models
- : [];
+ ? payload.models
+ : [];
const mappedModels = (rawModels as Array<any>)
.map((item) => {
@@ -338,8 +338,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
showAlertDialog({
title: "Hotkey Not Registered",
description:
- result.message ||
- "We couldn't register that key. Please choose another hotkey.",
+ result.message || "We couldn't register that key. Please choose another hotkey.",
});
return false;
}
@@ -348,16 +347,15 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
console.error("Failed to register onboarding hotkey", error);
showAlertDialog({
title: "Hotkey Error",
- description:
- "We couldn't register that key. Please choose another hotkey.",
+ description: "We couldn't register that key. Please choose another hotkey.",
});
return false;
}
}, [hotkey, showAlertDialog]);
const saveSettings = useCallback(async () => {
- const normalizedTranscriptionBase = (transcriptionBaseUrl || '').trim();
- const normalizedReasoningBaseValue = (reasoningBaseUrl || '').trim();
+ const normalizedTranscriptionBase = (transcriptionBaseUrl || "").trim();
+ const normalizedReasoningBaseValue = (reasoningBaseUrl || "").trim();
setCloudTranscriptionBaseUrl(normalizedTranscriptionBase);
setCloudReasoningBaseUrl(normalizedReasoningBaseValue);
@@ -379,10 +377,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
setDictationKey(hotkey);
saveAgentName(agentName);
- localStorage.setItem(
- "micPermissionGranted",
- permissionsHook.micPermissionGranted.toString()
- );
+ localStorage.setItem("micPermissionGranted", permissionsHook.micPermissionGranted.toString());
localStorage.setItem(
"accessibilityPermissionGranted",
permissionsHook.accessibilityPermissionGranted.toString()
@@ -475,10 +470,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
switch (currentStep) {
case 0: // Welcome
return (
- <div
- className="text-center space-y-6"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <div className="text-center space-y-6" style={{ fontFamily: "Noto Sans, sans-serif" }}>
<div className="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center">
<Sparkles className="w-8 h-8 text-blue-600" />
</div>
@@ -489,18 +481,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
>
Welcome to OpenWhispr
</h2>
- <p
- className="text-stone-600"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <p className="text-stone-600" style={{ fontFamily: "Noto Sans, sans-serif" }}>
Let's set up your voice dictation in just a few simple steps.
</p>
</div>
<div className="bg-blue-50/50 p-4 rounded-lg border border-blue-200/60">
- <p
- className="text-sm text-blue-800"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <p className="text-sm text-blue-800" style={{ fontFamily: "Noto Sans, sans-serif" }}>
🎤 Turn your voice into text instantly
<br />
⚡ Works anywhere on your computer
@@ -513,10 +499,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
case 1: // Choose Mode
return (
- <div
- className="space-y-6"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <div className="space-y-6" style={{ fontFamily: "Noto Sans, sans-serif" }}>
<div className="text-center">
<h2
className="text-2xl font-bold text-stone-900 mb-2"
@@ -524,10 +507,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
>
Choose Your Processing Mode
</h2>
- <p
- className="text-stone-600"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <p className="text-stone-600" style={{ fontFamily: "Noto Sans, sans-serif" }}>
How would you like to convert your speech to text?
</p>
</div>
@@ -544,9 +524,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="space-y-6">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-2">
- {useLocalWhisper
- ? "Local Processing Setup"
- : "Cloud Processing Setup"}
+ {useLocalWhisper ? "Local Processing Setup" : "Cloud Processing Setup"}
</h2>
<p className="text-gray-600">
{useLocalWhisper
@@ -563,11 +541,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="w-16 h-16 mx-auto bg-blue-50 rounded-full flex items-center justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
</div>
- <h3 className="font-semibold text-gray-900">
- Looking for Python...
- </h3>
+ <h3 className="font-semibold text-gray-900">Looking for Python...</h3>
<p className="text-sm text-gray-600 max-w-md mx-auto">
- OpenWhispr is scanning for your existing Python install (including <code>py.exe</code> and any paths supplied via <code>OPENWHISPR_PYTHON</code>). Sit tight—if we find one, we’ll skip this step automatically.
+ OpenWhispr is scanning for your existing Python install (including{" "}
+ <code>py.exe</code> and any paths supplied via <code>OPENWHISPR_PYTHON</code>
+ ). Sit tight—if we find one, we’ll skip this step automatically.
</p>
</div>
) : !pythonHook.pythonInstalled ? (
@@ -576,11 +554,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<Download className="w-8 h-8 text-blue-600" />
</div>
<div>
- <h3 className="font-semibold text-gray-900 mb-2">
- Install Python
- </h3>
+ <h3 className="font-semibold text-gray-900 mb-2">Install Python</h3>
<p className="text-sm text-gray-600 mb-4">
- Python is required for local processing. We'll install it automatically for you.
+ Python is required for local processing. We'll install it automatically for
+ you.
</p>
</div>
@@ -588,9 +565,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="bg-blue-50 p-4 rounded-lg">
<div className="flex items-center justify-center gap-3 mb-3">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
- <span className="font-medium text-blue-900">
- Installing Python...
- </span>
+ <span className="font-medium text-blue-900">Installing Python...</span>
</div>
{pythonHook.installProgress && (
<div className="text-xs text-blue-600 bg-white p-2 rounded font-mono">
@@ -641,9 +616,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<Download className="w-8 h-8 text-purple-600" />
</div>
<div>
- <h3 className="font-semibold text-gray-900 mb-2">
- Install Whisper
- </h3>
+ <h3 className="font-semibold text-gray-900 mb-2">Install Whisper</h3>
<p className="text-sm text-gray-600 mb-4">
Python is ready! Now we'll install Whisper for speech recognition.
</p>
@@ -653,9 +626,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="bg-purple-50 p-4 rounded-lg">
<div className="flex items-center justify-center gap-3 mb-3">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-purple-600"></div>
- <span className="font-medium text-purple-900">
- Installing...
- </span>
+ <span className="font-medium text-purple-900">Installing...</span>
</div>
{whisperHook.installProgress && (
<div className="text-xs text-purple-600 bg-white p-2 rounded font-mono">
@@ -667,10 +638,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</p>
</div>
) : (
- <Button
- onClick={whisperHook.installWhisper}
- className="w-full"
- >
+ <Button onClick={whisperHook.installWhisper} className="w-full">
Install Whisper
</Button>
)}
@@ -681,12 +649,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center mb-4">
<Check className="w-8 h-8 text-green-600" />
</div>
- <h3 className="font-semibold text-green-900 mb-2">
- Whisper Installed!
- </h3>
- <p className="text-sm text-gray-600">
- Now choose your model quality:
- </p>
+ <h3 className="font-semibold text-green-900 mb-2">Whisper Installed!</h3>
+ <p className="text-sm text-gray-600">Now choose your model quality:</p>
</div>
<div>
@@ -734,25 +698,36 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
/>
<div className="space-y-2">
- <label className="block text-sm font-medium text-blue-900">Custom transcription base URL (optional)</label>
+ <label className="block text-sm font-medium text-blue-900">
+ Custom transcription base URL (optional)
+ </label>
<Input
value={transcriptionBaseUrl}
onChange={(event) => setTranscriptionBaseUrl(event.target.value)}
placeholder="https://api.openai.com/v1"
className="text-sm"
/>
- <p className="text-xs text-blue-800">Cloud transcription requests default to <code>{API_ENDPOINTS.TRANSCRIPTION_BASE}</code>. Enter an OpenAI-compatible base URL to override.</p>
+ <p className="text-xs text-blue-800">
+ Cloud transcription requests default to{" "}
+ <code>{API_ENDPOINTS.TRANSCRIPTION_BASE}</code>. Enter an OpenAI-compatible base
+ URL to override.
+ </p>
</div>
<div className="space-y-2">
- <label className="block text-sm font-medium text-blue-900">Custom reasoning base URL (optional)</label>
+ <label className="block text-sm font-medium text-blue-900">
+ Custom reasoning base URL (optional)
+ </label>
<Input
value={reasoningBaseUrl}
onChange={(event) => setReasoningBaseUrl(event.target.value)}
placeholder="https://api.openai.com/v1"
className="text-sm"
/>
- <p className="text-xs text-blue-800">We'll load AI models from this endpoint's /v1/models route during setup. Leave empty to use the default OpenAI endpoint.</p>
+ <p className="text-xs text-blue-800">
+ We'll load AI models from this endpoint's /v1/models route during setup. Leave
+ empty to use the default OpenAI endpoint.
+ </p>
</div>
<div className="space-y-3 pt-4 border-t border-blue-100">
@@ -798,9 +773,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
<div className="bg-blue-50 p-4 rounded-lg">
- <h4 className="font-medium text-blue-900 mb-2">
- How to get your API key:
- </h4>
+ <h4 className="font-medium text-blue-900 mb-2">How to get your API key:</h4>
<ol className="text-sm text-blue-800 space-y-1">
<li>1. Go to platform.openai.com</li>
<li>2. Sign in to your account</li>
@@ -814,9 +787,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
{/* Language Selection - shown for both modes */}
<div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">
- <h4 className="font-medium text-gray-900 mb-3">
- 🌍 Preferred Language
- </h4>
+ <h4 className="font-medium text-gray-900 mb-3">🌍 Preferred Language</h4>
<label className="block text-sm font-medium text-gray-700 mb-2">
Which language do you primarily speak?
</label>
@@ -840,9 +811,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return (
<div className="space-y-6">
<div className="text-center">
- <h2 className="text-2xl font-bold text-gray-900 mb-2">
- Grant Permissions
- </h2>
+ <h2 className="text-2xl font-bold text-gray-900 mb-2">Grant Permissions</h2>
<p className="text-gray-600">
OpenWhispr needs a couple of permissions to work properly
</p>
@@ -877,9 +846,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
<div className="bg-amber-50 p-4 rounded-lg">
- <h4 className="font-medium text-amber-900 mb-2">
- 🔒 Privacy Note
- </h4>
+ <h4 className="font-medium text-amber-900 mb-2">🔒 Privacy Note</h4>
<p className="text-sm text-amber-800">
OpenWhispr only uses these permissions for dictation.
{useLocalWhisper
@@ -894,9 +861,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return (
<div className="space-y-6">
<div className="text-center">
- <h2 className="text-2xl font-bold text-gray-900 mb-2">
- Choose Your Hotkey
- </h2>
+ <h2 className="text-2xl font-bold text-gray-900 mb-2">Choose Your Hotkey</h2>
<p className="text-gray-600">
Select which key you want to press to start/stop dictation
</p>
@@ -919,9 +884,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
<div className="bg-gray-50 p-4 rounded-lg">
- <h4 className="font-medium text-gray-900 mb-3">
- Click any key to select it:
- </h4>
+ <h4 className="font-medium text-gray-900 mb-3">Click any key to select it:</h4>
<React.Suspense fallback={<div>Loading keyboard...</div>}>
<InteractiveKeyboard selectedKey={hotkey} setSelectedKey={setHotkey} />
</React.Suspense>
@@ -932,10 +895,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
case 5: // Test & Practice
return (
- <div
- className="space-y-6"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <div className="space-y-6" style={{ fontFamily: "Noto Sans, sans-serif" }}>
<div className="text-center">
<h2
className="text-2xl font-bold text-stone-900 mb-2"
@@ -943,10 +903,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
>
Test & Practice
</h2>
- <p
- className="text-stone-600"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <p className="text-stone-600" style={{ fontFamily: "Noto Sans, sans-serif" }}>
Let's test your setup and practice using OpenWhispr
</p>
</div>
@@ -963,8 +920,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
className="text-sm text-blue-800 mb-4"
style={{ fontFamily: "Noto Sans, sans-serif" }}
>
- <strong>Step 1:</strong> Click in the text area below to place
- your cursor there.
+ <strong>Step 1:</strong> Click in the text area below to place your cursor there.
<br />
<strong>Step 2:</strong> Press{" "}
<kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-blue-200">
@@ -976,8 +932,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-blue-200">
{readableHotkey}
</kbd>{" "}
- again to stop and see your transcribed text appear where your
- cursor is!
+ again to stop and see your transcribed text appear where your cursor is!
</p>
<div className="space-y-4">
@@ -1037,10 +992,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</kbd>{" "}
again to stop
</li>
- <li>
- 5. Your text will automatically appear where you were
- typing!
- </li>
+ <li>5. Your text will automatically appear where you were typing!</li>
</ol>
</div>
</div>
@@ -1051,44 +1003,32 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return (
<div className="space-y-6">
<div className="text-center">
- <h2 className="text-2xl font-bold text-stone-900 mb-2">
- Name Your Agent
- </h2>
+ <h2 className="text-2xl font-bold text-stone-900 mb-2">Name Your Agent</h2>
<p className="text-stone-600">
- Give your agent a name so you can address it specifically when
- giving instructions.
+ Give your agent a name so you can address it specifically when giving instructions.
</p>
</div>
<div className="space-y-4 p-4 bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded-xl">
- <h4 className="font-medium text-purple-900 mb-3">
- 💡 How this helps:
- </h4>
+ <h4 className="font-medium text-purple-900 mb-3">💡 How this helps:</h4>
<ul className="text-sm text-purple-800 space-y-1">
<li>
- • Say "Hey {agentName || "Agent"}, write a formal email" for
- specific instructions
- </li>
- <li>
- • Use the name to distinguish between dictation and commands
+ • Say "Hey {agentName || "Agent"}, write a formal email" for specific instructions
</li>
+ <li>• Use the name to distinguish between dictation and commands</li>
<li>• Makes interactions feel more natural and personal</li>
</ul>
</div>
<div className="space-y-4">
- <label className="block text-sm font-medium text-gray-700 mb-2">
- Agent Name
- </label>
+ <label className="block text-sm font-medium text-gray-700 mb-2">Agent Name</label>
<Input
placeholder="e.g., Assistant, Jarvis, Alex..."
value={agentName}
onChange={(e) => setAgentName(e.target.value)}
className="text-center text-lg font-mono"
/>
- <p className="text-xs text-gray-500 mt-2">
- You can change this anytime in settings
- </p>
+ <p className="text-xs text-gray-500 mt-2">You can change this anytime in settings</p>
</div>
</div>
);
@@ -1100,25 +1040,17 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<Check className="w-8 h-8 text-green-600" />
</div>
<div>
- <h2 className="text-2xl font-bold text-gray-900 mb-2">
- You're All Set!
- </h2>
- <p className="text-gray-600">
- OpenWhispr is now configured and ready to use.
- </p>
+ <h2 className="text-2xl font-bold text-gray-900 mb-2">You're All Set!</h2>
+ <p className="text-gray-600">OpenWhispr is now configured and ready to use.</p>
</div>
<div className="bg-gradient-to-r from-indigo-50 to-purple-50 p-6 rounded-lg">
- <h3 className="font-semibold text-gray-900 mb-3">
- Your Setup Summary:
- </h3>
+ <h3 className="font-semibold text-gray-900 mb-3">Your Setup Summary:</h3>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span>Processing:</span>
<span className="font-medium">
- {useLocalWhisper
- ? `Local (${whisperModel})`
- : "OpenAI Cloud"}
+ {useLocalWhisper ? `Local (${whisperModel})` : "OpenAI Cloud"}
</span>
</div>
{!useLocalWhisper && (
@@ -1137,15 +1069,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
)}
<div className="flex justify-between">
<span>Hotkey:</span>
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono">
- {hotkey}
- </kbd>
+ <kbd className="bg-white px-2 py-1 rounded text-xs font-mono">{hotkey}</kbd>
</div>
<div className="flex justify-between">
<span>Language:</span>
- <span className="font-medium">
- {getLanguageLabel(preferredLanguage)}
- </span>
+ <span className="font-medium">{getLanguageLabel(preferredLanguage)}</span>
</div>
<div className="flex justify-between">
<span>Agent Name:</span>
@@ -1165,8 +1093,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="bg-blue-50 p-4 rounded-lg">
<p className="text-sm text-blue-800">
- <strong>Pro tip:</strong> You can always change these settings
- later in the Control Panel.
+ <strong>Pro tip:</strong> You can always change these settings later in the Control
+ Panel.
</p>
</div>
</div>
@@ -1197,16 +1125,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
if (!isValidReasoningBase) {
return false;
}
- return (
- customReasoningModels.length > 0 &&
- !customModelsLoading &&
- !customModelsError
- );
+ return customReasoningModels.length > 0 && !customModelsLoading && !customModelsError;
}
case 3:
return (
- permissionsHook.micPermissionGranted &&
- permissionsHook.accessibilityPermissionGranted
+ permissionsHook.micPermissionGranted && permissionsHook.accessibilityPermissionGranted
);
case 4:
return hotkey.trim() !== "";
@@ -1286,10 +1209,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<div className="flex-1 px-6 md:pl-16 md:pr-6 py-12 overflow-y-auto">
<div className="max-w-4xl mx-auto">
<Card className="bg-white/95 backdrop-blur-xl border border-stone-200/60 shadow-lg rounded-2xl overflow-hidden">
- <CardContent
- className="p-12 md:p-16"
- style={{ fontFamily: "Noto Sans, sans-serif" }}
- >
+ <CardContent className="p-12 md:p-16" style={{ fontFamily: "Noto Sans, sans-serif" }}>
<div className="space-y-8">{renderStep()}</div>
</CardContent>
</Card>
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 56ff8cd83..b2e72b640 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -8,10 +8,7 @@ interface SettingsModalProps {
onOpenChange: (open: boolean) => void;
}
-export default function SettingsModal({
- open,
- onOpenChange,
-}: SettingsModalProps) {
+export default function SettingsModal({ open, onOpenChange }: SettingsModalProps) {
const sidebarItems: SidebarItem<SettingsSectionType>[] = [
{ id: "general", label: "General", icon: Settings },
{ id: "transcription", label: "Transcription Mode", icon: Mic },
@@ -20,8 +17,7 @@ export default function SettingsModal({
{ id: "prompts", label: "AI Prompts", icon: Sparkles },
];
- const [activeSection, setActiveSection] =
- React.useState<SettingsSectionType>("general");
+ const [activeSection, setActiveSection] = React.useState<SettingsSectionType>("general");
return (
<SidebarModal<SettingsSectionType>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 451366bd6..8984bdeeb 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -33,9 +33,7 @@ interface SettingsPageProps {
activeSection?: SettingsSectionType;
}
-export default function SettingsPage({
- activeSection = "general",
-}: SettingsPageProps) {
+export default function SettingsPage({ activeSection = "general" }: SettingsPageProps) {
// Use custom hooks
const {
confirmDialog,
@@ -107,8 +105,7 @@ export default function SettingsPage({
: "~/.cache/openwhispr/models";
const isUpdateAvailable =
- !updateStatus.isDevelopment &&
- (updateStatus.updateAvailable || updateStatus.updateDownloaded);
+ !updateStatus.isDevelopment && (updateStatus.updateAvailable || updateStatus.updateDownloaded);
const whisperHook = useWhisper(showAlertDialog);
const permissionsHook = usePermissions(showAlertDialog);
@@ -229,7 +226,10 @@ export default function SettingsPage({
updateAvailable: prev.updateAvailable || statusResult.updateAvailable,
updateDownloaded: prev.updateDownloaded || statusResult.updateDownloaded,
}));
- if ((statusResult.updateAvailable || statusResult.updateDownloaded) && window.electronAPI?.getUpdateInfo) {
+ if (
+ (statusResult.updateAvailable || statusResult.updateDownloaded) &&
+ window.electronAPI?.getUpdateInfo
+ ) {
const info = await window.electronAPI.getUpdateInfo();
if (info) {
setUpdateInfo({
@@ -284,18 +284,21 @@ export default function SettingsPage({
}, [installInitiated, showAlertDialog]);
const saveReasoningSettings = useCallback(async () => {
- const normalizedReasoningBase = (cloudReasoningBaseUrl || '').trim();
+ const normalizedReasoningBase = (cloudReasoningBaseUrl || "").trim();
setCloudReasoningBaseUrl(normalizedReasoningBase);
// Update reasoning settings including the base URL
updateReasoningSettings({
useReasoningModel,
reasoningModel,
- cloudReasoningBaseUrl: normalizedReasoningBase
+ cloudReasoningBaseUrl: normalizedReasoningBase,
});
// Save API keys to backend based on provider (including custom)
- if ((localReasoningProvider === "openai" || localReasoningProvider === "custom") && openaiApiKey) {
+ if (
+ (localReasoningProvider === "openai" || localReasoningProvider === "custom") &&
+ openaiApiKey
+ ) {
await window.electronAPI?.saveOpenAIKey(openaiApiKey);
}
if (localReasoningProvider === "anthropic" && anthropicApiKey) {
@@ -309,8 +312,16 @@ export default function SettingsPage({
}
// Update API keys in state (for custom provider, save the API key used)
- const keysToSave: Partial<{openaiApiKey: string; anthropicApiKey: string; geminiApiKey: string; groqApiKey: string}> = {};
- if ((localReasoningProvider === "openai" || localReasoningProvider === "custom") && openaiApiKey.trim()) {
+ const keysToSave: Partial<{
+ openaiApiKey: string;
+ anthropicApiKey: string;
+ geminiApiKey: string;
+ groqApiKey: string;
+ }> = {};
+ if (
+ (localReasoningProvider === "openai" || localReasoningProvider === "custom") &&
+ openaiApiKey.trim()
+ ) {
keysToSave.openaiApiKey = openaiApiKey;
}
if (localReasoningProvider === "anthropic" && anthropicApiKey.trim()) {
@@ -328,17 +339,14 @@ export default function SettingsPage({
localStorage.setItem("reasoningProvider", localReasoningProvider);
const providerLabel =
- localReasoningProvider === 'custom'
- ? 'Custom'
- : REASONING_PROVIDERS[
- localReasoningProvider as keyof typeof REASONING_PROVIDERS
- ]?.name || localReasoningProvider;
+ localReasoningProvider === "custom"
+ ? "Custom"
+ : REASONING_PROVIDERS[localReasoningProvider as keyof typeof REASONING_PROVIDERS]?.name ||
+ localReasoningProvider;
showAlertDialog({
title: "Reasoning Settings Saved",
- description: `AI text enhancement ${
- useReasoningModel ? "enabled" : "disabled"
- } with ${
+ description: `AI text enhancement ${useReasoningModel ? "enabled" : "disabled"} with ${
providerLabel
} ${reasoningModel}`,
});
@@ -369,7 +377,7 @@ export default function SettingsPage({
if (geminiApiKey) {
await window.electronAPI?.saveGeminiKey(geminiApiKey);
}
-
+
updateApiKeys({ openaiApiKey, anthropicApiKey, geminiApiKey });
updateTranscriptionSettings({ allowLocalFallback, fallbackWhisperModel });
@@ -377,15 +385,15 @@ export default function SettingsPage({
if (openaiApiKey) {
await window.electronAPI?.createProductionEnvFile(openaiApiKey);
}
-
+
const savedKeys: string[] = [];
if (openaiApiKey) savedKeys.push("OpenAI");
if (anthropicApiKey) savedKeys.push("Anthropic");
if (geminiApiKey) savedKeys.push("Gemini");
-
+
showAlertDialog({
title: "API Keys Saved",
- description: `${savedKeys.join(", ")} API key${savedKeys.length > 1 ? 's' : ''} saved successfully! Your credentials have been securely recorded.${
+ description: `${savedKeys.join(", ")} API key${savedKeys.length > 1 ? "s" : ""} saved successfully! Your credentials have been securely recorded.${
allowLocalFallback ? " Local Whisper fallback is enabled." : ""
}`,
});
@@ -446,8 +454,7 @@ export default function SettingsPage({
showAlertDialog({
title: "Hotkey Not Saved",
description:
- result?.message ||
- "This key could not be registered. Please choose a different key.",
+ result?.message || "This key could not be registered. Please choose a different key.",
});
return;
}
@@ -470,8 +477,7 @@ export default function SettingsPage({
showConfirmDialog({
title: "Remove downloaded models?",
- description:
- `This deletes all locally cached Whisper models (${cachePathHint}) and frees disk space. You can download them again from the model picker.`,
+ description: `This deletes all locally cached Whisper models (${cachePathHint}) and frees disk space. You can download them again from the model picker.`,
confirmText: "Delete Models",
variant: "destructive",
onConfirm: () => {
@@ -483,8 +489,7 @@ export default function SettingsPage({
showAlertDialog({
title: "Unable to Remove Models",
description:
- result?.error ||
- "Something went wrong while deleting the cached models.",
+ result?.error || "Something went wrong while deleting the cached models.",
});
return;
}
@@ -518,22 +523,15 @@ export default function SettingsPage({
{/* App Updates Section */}
<div className="space-y-6">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- App Updates
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">App Updates</h3>
<p className="text-sm text-gray-600 mb-4">
- Keep OpenWhispr up to date with the latest features and
- improvements.
+ Keep OpenWhispr up to date with the latest features and improvements.
</p>
</div>
<div className="flex items-center justify-between p-4 bg-neutral-50 rounded-lg">
<div>
- <p className="text-sm font-medium text-neutral-800">
- Current Version
- </p>
- <p className="text-xs text-neutral-600">
- {currentVersion || "Loading..."}
- </p>
+ <p className="text-sm font-medium text-neutral-800">Current Version</p>
+ <p className="text-xs text-neutral-600">{currentVersion || "Loading..."}</p>
</div>
<div className="flex items-center gap-2">
{updateStatus.isDevelopment ? (
@@ -556,11 +554,10 @@ export default function SettingsPage({
onClick={async () => {
setCheckingForUpdates(true);
try {
- const result =
- await window.electronAPI?.checkForUpdates();
+ const result = await window.electronAPI?.checkForUpdates();
if (result?.updateAvailable) {
setUpdateInfo({
- version: result.version || 'unknown',
+ version: result.version || "unknown",
releaseDate: result.releaseDate,
releaseNotes: result.releaseNotes,
});
@@ -571,13 +568,12 @@ export default function SettingsPage({
}));
showAlertDialog({
title: "Update Available",
- description: `Update available: v${result.version || 'new version'}`,
+ description: `Update available: v${result.version || "new version"}`,
});
} else {
showAlertDialog({
title: "No Updates",
- description:
- result?.message || "No updates available",
+ description: result?.message || "No updates available",
});
}
} catch (error: any) {
@@ -632,7 +628,7 @@ export default function SettingsPage({
) : (
<>
<Download size={16} className="mr-2" />
- Download Update{updateInfo.version ? ` v${updateInfo.version}` : ''}
+ Download Update{updateInfo.version ? ` v${updateInfo.version}` : ""}
</>
)}
</Button>
@@ -642,7 +638,9 @@ export default function SettingsPage({
<div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200">
<div
className="h-full bg-green-600 transition-all duration-200"
- style={{ width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%` }}
+ style={{
+ width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%`,
+ }}
/>
</div>
<p className="text-xs text-neutral-600 text-right">
@@ -658,7 +656,7 @@ export default function SettingsPage({
onClick={() => {
showConfirmDialog({
title: "Install Update",
- description: `Ready to install update${updateInfo.version ? ` v${updateInfo.version}` : ''}. The app will restart to complete installation.`,
+ description: `Ready to install update${updateInfo.version ? ` v${updateInfo.version}` : ""}. The app will restart to complete installation.`,
confirmText: "Install & Restart",
onConfirm: async () => {
try {
@@ -709,9 +707,7 @@ export default function SettingsPage({
{updateInfo.version && (
<div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
- <h4 className="font-medium text-blue-900 mb-2">
- Update v{updateInfo.version}
- </h4>
+ <h4 className="font-medium text-blue-900 mb-2">Update v{updateInfo.version}</h4>
{updateInfo.releaseDate && (
<p className="text-sm text-blue-700 mb-2">
Released: {new Date(updateInfo.releaseDate).toLocaleDateString()}
@@ -731,9 +727,7 @@ export default function SettingsPage({
{/* Hotkey Section */}
<div className="border-t pt-8">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- Dictation Hotkey
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">Dictation Hotkey</h3>
<p className="text-sm text-gray-600 mb-6">
Configure the key you press to start and stop voice dictation.
</p>
@@ -754,9 +748,7 @@ export default function SettingsPage({
</p>
</div>
<div className="bg-gray-50 p-4 rounded-lg">
- <h4 className="font-medium text-gray-900 mb-3">
- Click any key to select it:
- </h4>
+ <h4 className="font-medium text-gray-900 mb-3">Click any key to select it:</h4>
<React.Suspense
fallback={
<div className="h-32 flex items-center justify-center text-gray-500">
@@ -770,11 +762,7 @@ export default function SettingsPage({
/>
</React.Suspense>
</div>
- <Button
- onClick={saveKey}
- disabled={!dictationKey.trim()}
- className="w-full"
- >
+ <Button onClick={saveKey} disabled={!dictationKey.trim()} className="w-full">
Save Hotkey
</Button>
</div>
@@ -783,12 +771,9 @@ export default function SettingsPage({
{/* Permissions Section */}
<div className="border-t pt-8">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- Permissions
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">Permissions</h3>
<p className="text-sm text-gray-600 mb-6">
- Test and manage app permissions for microphone and
- accessibility.
+ Test and manage app permissions for microphone and accessibility.
</p>
</div>
<div className="space-y-3">
@@ -829,13 +814,10 @@ export default function SettingsPage({
{/* About Section */}
<div className="border-t pt-8">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- About OpenWhispr
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">About OpenWhispr</h3>
<p className="text-sm text-gray-600 mb-6">
- OpenWhispr converts your speech to text using AI. Press your
- hotkey, speak, and we'll type what you said wherever your
- cursor is.
+ OpenWhispr converts your speech to text using AI. Press your hotkey, speak, and
+ we'll type what you said wherever your cursor is.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm mb-6">
@@ -843,9 +825,7 @@ export default function SettingsPage({
<div className="w-8 h-8 mx-auto mb-2 bg-indigo-600 rounded-lg flex items-center justify-center">
<Keyboard className="w-4 h-4 text-white" />
</div>
- <p className="font-medium text-gray-800 mb-1">
- Default Hotkey
- </p>
+ <p className="font-medium text-gray-800 mb-1">Default Hotkey</p>
<p className="text-gray-600 font-mono text-xs">
{formatHotkeyLabel(dictationKey)}
</p>
@@ -855,9 +835,7 @@ export default function SettingsPage({
<span className="text-white text-sm">🏷️</span>
</div>
<p className="font-medium text-gray-800 mb-1">Version</p>
- <p className="text-gray-600 text-xs">
- {currentVersion || "0.1.0"}
- </p>
+ <p className="text-gray-600 text-xs">{currentVersion || "0.1.0"}</p>
</div>
<div className="text-center p-4 border border-gray-200 rounded-xl bg-white">
<div className="w-8 h-8 mx-auto mb-2 bg-green-600 rounded-lg flex items-center justify-center">
@@ -901,8 +879,7 @@ export default function SettingsPage({
.then(() => {
showAlertDialog({
title: "Cleanup Completed",
- description:
- "✅ Cleanup completed! All app data has been removed.",
+ description: "✅ Cleanup completed! All app data has been removed.",
});
setTimeout(() => {
window.location.reload();
@@ -929,7 +906,8 @@ export default function SettingsPage({
<div className="space-y-3 mt-6 p-4 bg-rose-50 border border-rose-200 rounded-xl">
<h4 className="font-medium text-rose-900">Local Model Storage</h4>
<p className="text-sm text-rose-800">
- Remove all downloaded Whisper models from your cache directory to reclaim disk space. You can re-download any model later.
+ Remove all downloaded Whisper models from your cache directory to reclaim disk
+ space. You can re-download any model later.
</p>
<Button
variant="destructive"
@@ -1005,7 +983,8 @@ export default function SettingsPage({
</Button>
</div>
<p className="text-xs text-blue-800">
- Requests for cloud transcription use this OpenAI-compatible base URL. Leave empty to fall back to
+ Requests for cloud transcription use this OpenAI-compatible base URL. Leave
+ empty to fall back to
<code className="ml-1">{API_ENDPOINTS.TRANSCRIPTION_BASE}</code>.
</p>
</div>
@@ -1013,79 +992,75 @@ export default function SettingsPage({
)}
{useLocalWhisper && whisperHook.whisperInstalled && (
- <div className="space-y-4 p-4 bg-purple-50 border border-purple-200 rounded-xl">
- <h4 className="font-medium text-purple-900">
- Local Whisper Model
- </h4>
- <WhisperModelPicker
- selectedModel={whisperModel}
- onModelSelect={setWhisperModel}
- variant="settings"
+ <div className="space-y-4 p-4 bg-purple-50 border border-purple-200 rounded-xl">
+ <h4 className="font-medium text-purple-900">Local Whisper Model</h4>
+ <WhisperModelPicker
+ selectedModel={whisperModel}
+ onModelSelect={setWhisperModel}
+ variant="settings"
+ />
+ </div>
+ )}
+
+ <div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">
+ <h4 className="font-medium text-gray-900">Preferred Language</h4>
+ <LanguageSelector
+ value={preferredLanguage}
+ onChange={(value) => {
+ setPreferredLanguage(value);
+ updateTranscriptionSettings({ preferredLanguage: value });
+ }}
+ className="w-full"
/>
</div>
- )}
-
- <div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">
- <h4 className="font-medium text-gray-900">Preferred Language</h4>
- <LanguageSelector
- value={preferredLanguage}
- onChange={(value) => {
- setPreferredLanguage(value);
- updateTranscriptionSettings({ preferredLanguage: value });
+
+ <Button
+ onClick={() => {
+ const normalizedTranscriptionBase = (cloudTranscriptionBaseUrl || "").trim();
+ setCloudTranscriptionBaseUrl(normalizedTranscriptionBase);
+
+ updateTranscriptionSettings({
+ useLocalWhisper,
+ whisperModel,
+ preferredLanguage,
+ cloudTranscriptionBaseUrl: normalizedTranscriptionBase,
+ });
+
+ if (!useLocalWhisper && openaiApiKey.trim()) {
+ updateApiKeys({ openaiApiKey });
+ }
+
+ const descriptionParts = [
+ `Transcription mode: ${useLocalWhisper ? "Local Whisper" : "Cloud"}.`,
+ `Language: ${preferredLanguage}.`,
+ ];
+
+ if (!useLocalWhisper) {
+ const baseLabel = normalizedTranscriptionBase || API_ENDPOINTS.TRANSCRIPTION_BASE;
+ descriptionParts.push(`Endpoint: ${baseLabel}.`);
+ }
+
+ showAlertDialog({
+ title: "Settings Saved",
+ description: descriptionParts.join(" "),
+ });
}}
className="w-full"
- />
+ >
+ Save Transcription Settings
+ </Button>
</div>
-
- <Button
- onClick={() => {
- const normalizedTranscriptionBase = (cloudTranscriptionBaseUrl || '').trim();
- setCloudTranscriptionBaseUrl(normalizedTranscriptionBase);
-
- updateTranscriptionSettings({
- useLocalWhisper,
- whisperModel,
- preferredLanguage,
- cloudTranscriptionBaseUrl: normalizedTranscriptionBase,
- });
-
- if (!useLocalWhisper && openaiApiKey.trim()) {
- updateApiKeys({ openaiApiKey });
- }
-
- const descriptionParts = [
- `Transcription mode: ${useLocalWhisper ? 'Local Whisper' : 'Cloud'}.`,
- `Language: ${preferredLanguage}.`,
- ];
-
- if (!useLocalWhisper) {
- const baseLabel = normalizedTranscriptionBase || API_ENDPOINTS.TRANSCRIPTION_BASE;
- descriptionParts.push(`Endpoint: ${baseLabel}.`);
- }
-
- showAlertDialog({
- title: "Settings Saved",
- description: descriptionParts.join(' '),
- });
- }}
- className="w-full"
- >
- Save Transcription Settings
- </Button>
- </div>
- );
+ );
case "aiModels":
return (
<div className="space-y-6">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- AI Text Enhancement
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">AI Text Enhancement</h3>
<p className="text-sm text-gray-600 mb-6">
- Configure how AI models clean up and format your transcriptions.
- This handles commands like "scratch that", creates proper lists,
- and fixes obvious errors while preserving your natural tone.
+ Configure how AI models clean up and format your transcriptions. This handles
+ commands like "scratch that", creates proper lists, and fixes obvious errors while
+ preserving your natural tone.
</p>
</div>
@@ -1123,35 +1098,27 @@ export default function SettingsPage({
return (
<div className="space-y-6">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- Agent Configuration
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">Agent Configuration</h3>
<p className="text-sm text-gray-600 mb-6">
- Customize your AI assistant's name and behavior to make
- interactions more personal and effective.
+ Customize your AI assistant's name and behavior to make interactions more personal
+ and effective.
</p>
</div>
<div className="space-y-4 p-4 bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded-xl">
- <h4 className="font-medium text-purple-900 mb-3">
- 💡 How to use agent names:
- </h4>
+ <h4 className="font-medium text-purple-900 mb-3">💡 How to use agent names:</h4>
<ul className="text-sm text-purple-800 space-y-2">
+ <li>• Say "Hey {agentName}, write a formal email" for specific instructions</li>
<li>
- • Say "Hey {agentName}, write a formal email" for specific
- instructions
+ • Use "Hey {agentName}, format this as a list" for text enhancement commands
</li>
<li>
- • Use "Hey {agentName}, format this as a list" for text
- enhancement commands
+ • The agent will recognize when you're addressing it directly vs. dictating
+ content
</li>
<li>
- • The agent will recognize when you're addressing it directly
- vs. dictating content
- </li>
- <li>
- • Makes conversations feel more natural and helps distinguish
- commands from dictation
+ • Makes conversations feel more natural and helps distinguish commands from
+ dictation
</li>
</ul>
</div>
@@ -1184,42 +1151,28 @@ export default function SettingsPage({
</div>
<div className="bg-blue-50 p-4 rounded-lg">
- <h4 className="font-medium text-blue-900 mb-2">
- 🎯 Example Usage:
- </h4>
+ <h4 className="font-medium text-blue-900 mb-2">🎯 Example Usage:</h4>
<div className="text-sm text-blue-800 space-y-1">
- <p>
- • "Hey {agentName}, write an email to my team about the
- meeting"
- </p>
- <p>
- • "Hey {agentName}, make this more professional" (after
- dictating text)
- </p>
+ <p>• "Hey {agentName}, write an email to my team about the meeting"</p>
+ <p>• "Hey {agentName}, make this more professional" (after dictating text)</p>
<p>• "Hey {agentName}, convert this to bullet points"</p>
- <p>
- • Regular dictation: "This is just normal text" (no agent name
- needed)
- </p>
+ <p>• Regular dictation: "This is just normal text" (no agent name needed)</p>
</div>
</div>
</div>
);
-
case "prompts":
return (
<div className="space-y-6">
<div>
- <h3 className="text-lg font-semibold text-gray-900 mb-2">
- AI Prompt Management
- </h3>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">AI Prompt Management</h3>
<p className="text-sm text-gray-600 mb-6">
- View and customize the prompts that power OpenWhispr's AI text processing.
- Adjust these to change how your transcriptions are formatted and enhanced.
+ View and customize the prompts that power OpenWhispr's AI text processing. Adjust
+ these to change how your transcriptions are formatted and enhanced.
</p>
</div>
-
+
<PromptStudio />
</div>
);
diff --git a/src/components/TitleBar.tsx b/src/components/TitleBar.tsx
index f40752dfd..e01c6bd19 100644
--- a/src/components/TitleBar.tsx
+++ b/src/components/TitleBar.tsx
@@ -36,26 +36,19 @@ export default function TitleBar({
};
return (
- <div
- className={`bg-white border-b border-gray-100 select-none ${className}`}
- >
+ <div className={`bg-white border-b border-gray-100 select-none ${className}`}>
<div
className="flex items-center justify-between h-12 px-4"
style={{ WebkitAppRegion: "drag" }}
>
{/* Left section - title or custom content */}
<div className="flex items-center gap-2">
- {showTitle && title && (
- <h1 className="text-sm font-semibold text-gray-900">{title}</h1>
- )}
+ {showTitle && title && <h1 className="text-sm font-semibold text-gray-900">{title}</h1>}
{children}
</div>
{/* Right section - actions and window controls */}
- <div
- className="flex items-center gap-2"
- style={{ WebkitAppRegion: "no-drag" }}
- >
+ <div className="flex items-center gap-2" style={{ WebkitAppRegion: "no-drag" }}>
{actions}
<Button
variant="ghost"
diff --git a/src/components/UnifiedModelPicker.tsx b/src/components/UnifiedModelPicker.tsx
index a7d1ac917..5d8eeae83 100644
--- a/src/components/UnifiedModelPicker.tsx
+++ b/src/components/UnifiedModelPicker.tsx
@@ -2,14 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "./ui/button";
import { Progress } from "./ui/progress";
import { Alert, AlertDescription } from "./ui/alert";
-import {
- RefreshCw,
- Download,
- Trash2,
- AlertCircle,
- ExternalLink,
- Globe
-} from "lucide-react";
+import { RefreshCw, Download, Trash2, AlertCircle, ExternalLink, Globe } from "lucide-react";
import { useDialogs } from "../hooks/useDialogs";
import { useToast } from "./ui/Toast";
import { formatBytes } from "../utils/formatBytes";
@@ -26,7 +19,7 @@ interface Model {
downloaded?: boolean;
isDownloaded?: boolean;
recommended?: boolean;
- type: 'whisper' | 'llm';
+ type: "whisper" | "llm";
}
interface DownloadProgress {
@@ -40,7 +33,7 @@ interface DownloadProgress {
interface UnifiedModelPickerProps {
selectedModel: string;
onModelSelect: (modelId: string) => void;
- modelType: 'whisper' | 'llm';
+ modelType: "whisper" | "llm";
className?: string;
variant?: "onboarding" | "settings";
}
@@ -119,8 +112,8 @@ export function UnifiedModelPickerCompact({
onClick={() => onModelSelect(model.value)}
className={`w-full p-3 rounded-lg border-2 text-left transition-all ${
selectedModel === model.value
- ? 'border-indigo-500 bg-indigo-50'
- : 'border-gray-200 bg-white hover:border-gray-300'
+ ? "border-indigo-500 bg-indigo-50"
+ : "border-gray-200 bg-white hover:border-gray-300"
}`}
>
<div className="flex items-center justify-between">
@@ -170,10 +163,7 @@ export default function UnifiedModelPicker({
checking: boolean;
}>({ isInstalled: true, checking: false }); // Default to true for now
- const {
- showConfirmDialog,
- showAlertDialog,
- } = useDialogs();
+ const { showConfirmDialog, showAlertDialog } = useDialogs();
const { toast } = useToast();
const styles = useMemo(() => VARIANT_STYLES[variant], [variant]);
@@ -202,46 +192,47 @@ export default function UnifiedModelPicker({
const loadModels = useCallback(async () => {
try {
setLoadingModels(true);
-
- if (modelType === 'whisper') {
+
+ if (modelType === "whisper") {
const result = await window.electronAPI.listWhisperModels();
if (result.success) {
const whisperModels: Model[] = result.models.map((m: any) => ({
...m,
id: m.model,
name: m.model.charAt(0).toUpperCase() + m.model.slice(1),
- size: m.size_mb ? `${m.size_mb}MB` : 'Unknown',
- description: {
- tiny: "Fastest, lower quality",
- base: "Good balance (recommended)",
- small: "Better quality, slower",
- medium: "High quality",
- large: "Best quality, slowest",
- turbo: "Fast with good quality"
- }[m.model] || "Model",
- type: 'whisper' as const,
+ size: m.size_mb ? `${m.size_mb}MB` : "Unknown",
+ description:
+ {
+ tiny: "Fastest, lower quality",
+ base: "Good balance (recommended)",
+ small: "Better quality, slower",
+ medium: "High quality",
+ large: "Best quality, slowest",
+ turbo: "Fast with good quality",
+ }[m.model] || "Model",
+ type: "whisper" as const,
isDownloaded: m.downloaded,
- recommended: m.model === 'base'
+ recommended: m.model === "base",
}));
setModels(whisperModels);
}
} else {
- console.log('[UnifiedModelPicker] Loading LLM models...');
+ console.log("[UnifiedModelPicker] Loading LLM models...");
const result = await window.electronAPI.modelGetAll();
- console.log('[UnifiedModelPicker] Got result:', result);
-
+ console.log("[UnifiedModelPicker] Got result:", result);
+
if (!result || !Array.isArray(result)) {
- console.error('[UnifiedModelPicker] Invalid result format:', result);
+ console.error("[UnifiedModelPicker] Invalid result format:", result);
setModels([]);
return;
}
-
+
const llmModels: Model[] = result.map((m: any) => ({
...m,
- type: 'llm' as const,
- downloaded: m.isDownloaded
+ type: "llm" as const,
+ downloaded: m.isDownloaded,
}));
- console.log('[UnifiedModelPicker] Mapped models:', llmModels);
+ console.log("[UnifiedModelPicker] Mapped models:", llmModels);
setModels(llmModels);
}
} catch (error) {
@@ -267,41 +258,44 @@ export default function UnifiedModelPicker({
};
}, [loadModels]);
- const handleDownloadProgress = useCallback((_event: any, data: any) => {
- if (modelType === 'whisper') {
- // Whisper progress format
- if (data.type === "progress") {
- const progress: DownloadProgress = {
- percentage: data.percentage || 0,
- downloadedBytes: data.downloaded_bytes || 0,
- totalBytes: data.total_bytes || 0,
- };
-
- if (data.speed_mbps && data.speed_mbps > 0) {
- const remainingBytes = progress.totalBytes - progress.downloadedBytes;
- progress.eta = (remainingBytes * 8) / (data.speed_mbps * 1_000_000);
- progress.speed = data.speed_mbps;
- }
+ const handleDownloadProgress = useCallback(
+ (_event: any, data: any) => {
+ if (modelType === "whisper") {
+ // Whisper progress format
+ if (data.type === "progress") {
+ const progress: DownloadProgress = {
+ percentage: data.percentage || 0,
+ downloadedBytes: data.downloaded_bytes || 0,
+ totalBytes: data.total_bytes || 0,
+ };
+
+ if (data.speed_mbps && data.speed_mbps > 0) {
+ const remainingBytes = progress.totalBytes - progress.downloadedBytes;
+ progress.eta = (remainingBytes * 8) / (data.speed_mbps * 1_000_000);
+ progress.speed = data.speed_mbps;
+ }
- setDownloadProgress(progress);
- } else if (data.type === "complete" || data.type === "error") {
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
- loadModels();
+ setDownloadProgress(progress);
+ } else if (data.type === "complete" || data.type === "error") {
+ setDownloadingModel(null);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ loadModels();
+ }
+ } else {
+ // LLM progress format
+ setDownloadProgress({
+ percentage: data.progress || 0,
+ downloadedBytes: data.downloadedSize || 0,
+ totalBytes: data.totalSize || 0,
+ });
}
- } else {
- // LLM progress format
- setDownloadProgress({
- percentage: data.progress || 0,
- downloadedBytes: data.downloadedSize || 0,
- totalBytes: data.totalSize || 0,
- });
- }
- }, [modelType, loadModels]);
+ },
+ [modelType, loadModels]
+ );
useEffect(() => {
const dispose =
- modelType === 'whisper'
+ modelType === "whisper"
? window.electronAPI.onWhisperDownloadProgress(handleDownloadProgress)
: window.electronAPI.onModelDownloadProgress(handleDownloadProgress);
@@ -310,70 +304,76 @@ export default function UnifiedModelPicker({
};
}, [handleDownloadProgress, modelType]);
- const downloadModel = useCallback(async (modelId: string) => {
- try {
- setDownloadingModel(modelId);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
- onModelSelect(modelId);
+ const downloadModel = useCallback(
+ async (modelId: string) => {
+ try {
+ setDownloadingModel(modelId);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ onModelSelect(modelId);
+
+ if (modelType === "whisper") {
+ const result = await window.electronAPI.downloadWhisperModel(modelId);
+ if (!result.success && !result.error?.includes("interrupted by user")) {
+ showAlertDialog({
+ title: "Download Failed",
+ description: `Failed to download model: ${result.error}`,
+ });
+ }
+ } else {
+ await window.electronAPI.modelDownload(modelId);
+ }
- if (modelType === 'whisper') {
- const result = await window.electronAPI.downloadWhisperModel(modelId);
- if (!result.success && !result.error?.includes("interrupted by user")) {
+ await loadModels();
+ } catch (error: any) {
+ if (!error.toString().includes("interrupted by user")) {
showAlertDialog({
title: "Download Failed",
- description: `Failed to download model: ${result.error}`,
+ description: `Failed to download model: ${error}`,
});
}
- } else {
- await window.electronAPI.modelDownload(modelId);
- }
-
- await loadModels();
- } catch (error: any) {
- if (!error.toString().includes("interrupted by user")) {
- showAlertDialog({
- title: "Download Failed",
- description: `Failed to download model: ${error}`,
- });
+ } finally {
+ setDownloadingModel(null);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
}
- } finally {
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
- }
- }, [modelType, onModelSelect, loadModels, showAlertDialog]);
+ },
+ [modelType, onModelSelect, loadModels, showAlertDialog]
+ );
- const deleteModel = useCallback(async (modelId: string) => {
- showConfirmDialog({
- title: "Delete Model",
- description: `Are you sure you want to delete this model? You'll need to re-download it if you want to use it again.`,
- onConfirm: async () => {
- try {
- if (modelType === 'whisper') {
- const result = await window.electronAPI.deleteWhisperModel(modelId);
- if (result.success) {
+ const deleteModel = useCallback(
+ async (modelId: string) => {
+ showConfirmDialog({
+ title: "Delete Model",
+ description: `Are you sure you want to delete this model? You'll need to re-download it if you want to use it again.`,
+ onConfirm: async () => {
+ try {
+ if (modelType === "whisper") {
+ const result = await window.electronAPI.deleteWhisperModel(modelId);
+ if (result.success) {
+ toast({
+ title: "Model Deleted",
+ description: `Model deleted successfully! Freed ${result.freed_mb}MB of disk space.`,
+ });
+ }
+ } else {
+ await window.electronAPI.modelDelete(modelId);
toast({
title: "Model Deleted",
- description: `Model deleted successfully! Freed ${result.freed_mb}MB of disk space.`,
+ description: "Model deleted successfully!",
});
}
- } else {
- await window.electronAPI.modelDelete(modelId);
- toast({
- title: "Model Deleted",
- description: "Model deleted successfully!",
+ loadModels();
+ } catch (error) {
+ showAlertDialog({
+ title: "Delete Failed",
+ description: `Failed to delete model: ${error}`,
});
}
- loadModels();
- } catch (error) {
- showAlertDialog({
- title: "Delete Failed",
- description: `Failed to delete model: ${error}`,
- });
- }
- },
- variant: "destructive",
- });
- }, [modelType, loadModels, showConfirmDialog, showAlertDialog, toast]);
+ },
+ variant: "destructive",
+ });
+ },
+ [modelType, loadModels, showConfirmDialog, showAlertDialog, toast]
+ );
const handleInstallLlamaCpp = async () => {
try {
@@ -392,8 +392,39 @@ export default function UnifiedModelPicker({
}
};
+ // Memoize progress display - must be before any early returns to satisfy React hooks rules
+ const progressDisplay = useMemo(() => {
+ if (!downloadingModel) return null;
+
+ const { percentage, speed, eta } = downloadProgress;
+ const progressText = `${Math.round(percentage)}%`;
+ const speedText = speed ? ` • ${speed.toFixed(1)} MB/s` : "";
+ const etaText = eta ? ` • ETA: ${formatETA(eta)}` : "";
+
+ return (
+ <div className={`${styles.progress} p-3`}>
+ <div className="flex items-center justify-between mb-2">
+ <span className={`text-sm font-medium ${styles.progressText}`}>
+ Downloading {models.find((m) => m.id === downloadingModel)?.name || downloadingModel}...
+ </span>
+ <span className={`text-xs ${styles.progressText}`}>
+ {progressText}
+ {speedText}
+ {etaText}
+ </span>
+ </div>
+ <div className={`w-full ${styles.progressBar} rounded-full h-2`}>
+ <div
+ className={`${styles.progressFill} h-2 rounded-full transition-all duration-300 ease-out`}
+ style={{ width: `${Math.min(percentage, 100)}%` }}
+ />
+ </div>
+ </div>
+ );
+ }, [downloadingModel, downloadProgress, models, styles]);
+
// Show llama.cpp installation prompt for LLM models
- if (modelType === 'llm' && !llamaCppStatus.isInstalled && !llamaCppStatus.checking) {
+ if (modelType === "llm" && !llamaCppStatus.isInstalled && !llamaCppStatus.checking) {
return (
<div className={`${styles.container} ${className}`}>
<div className="p-4">
@@ -409,7 +440,11 @@ export default function UnifiedModelPicker({
<Button
variant="link"
className="p-0 h-auto text-primary"
- onClick={() => window.electronAPI?.openExternal("https://github.com/ggerganov/llama.cpp#installation")}
+ onClick={() =>
+ window.electronAPI?.openExternal(
+ "https://github.com/ggerganov/llama.cpp#installation"
+ )
+ }
>
Manual installation
<ExternalLink className="ml-1 h-3 w-3" />
@@ -422,34 +457,6 @@ export default function UnifiedModelPicker({
);
}
- const progressDisplay = useMemo(() => {
- if (!downloadingModel) return null;
-
- const { percentage, speed, eta } = downloadProgress;
- const progressText = `${Math.round(percentage)}%`;
- const speedText = speed ? ` • ${speed.toFixed(1)} MB/s` : "";
- const etaText = eta ? ` • ETA: ${formatETA(eta)}` : "";
-
- return (
- <div className={`${styles.progress} p-3`}>
- <div className="flex items-center justify-between mb-2">
- <span className={`text-sm font-medium ${styles.progressText}`}>
- Downloading {models.find(m => m.id === downloadingModel)?.name || downloadingModel}...
- </span>
- <span className={`text-xs ${styles.progressText}`}>
- {progressText}{speedText}{etaText}
- </span>
- </div>
- <div className={`w-full ${styles.progressBar} rounded-full h-2`}>
- <div
- className={`${styles.progressFill} h-2 rounded-full transition-all duration-300 ease-out`}
- style={{ width: `${Math.min(percentage, 100)}%` }}
- />
- </div>
- </div>
- );
- }, [downloadingModel, downloadProgress, models, styles]);
-
return (
<div className={`${styles.container} ${className}`}>
{progressDisplay}
@@ -457,7 +464,7 @@ export default function UnifiedModelPicker({
<div className="p-4">
<div className="flex items-center justify-between mb-3">
<h5 className={styles.header}>
- {modelType === 'whisper' ? 'Whisper Models' : 'Local AI Models'}
+ {modelType === "whisper" ? "Whisper Models" : "Local AI Models"}
</h5>
<Button
onClick={loadModels}
@@ -473,7 +480,7 @@ export default function UnifiedModelPicker({
<div className="space-y-2">
{models.map((model) => {
- const modelId = model.id || model.model || '';
+ const modelId = model.id || model.model || "";
const isSelected = modelId === selectedModel;
const isDownloading = downloadingModel === modelId;
const isDownloaded = model.downloaded || model.isDownloaded;
@@ -488,9 +495,7 @@ export default function UnifiedModelPicker({
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-medium">{model.name}</span>
- {isSelected && (
- <span className={styles.badges.selected}>✓ Selected</span>
- )}
+ {isSelected && <span className={styles.badges.selected}>✓ Selected</span>}
{model.recommended && (
<span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">
Recommended
@@ -500,9 +505,7 @@ export default function UnifiedModelPicker({
<div className="flex items-center gap-2 mt-1">
<p className="text-xs text-gray-600">{model.description}</p>
<span className="text-xs text-gray-500">• {model.size}</span>
- {isDownloaded && (
- <span className={styles.badges.downloaded}>✓ Downloaded</span>
- )}
+ {isDownloaded && <span className={styles.badges.downloaded}>✓ Downloaded</span>}
</div>
</div>
@@ -551,7 +554,7 @@ export default function UnifiedModelPicker({
})}
</div>
- {modelType === 'llm' && (
+ {modelType === "llm" && (
<div className="mt-6 text-xs text-muted-foreground">
<p>Models are stored in: ~/.cache/openwhispr/models/</p>
</div>
diff --git a/src/components/WhisperModelPicker.tsx b/src/components/WhisperModelPicker.tsx
index aadac47d8..630dd388c 100644
--- a/src/components/WhisperModelPicker.tsx
+++ b/src/components/WhisperModelPicker.tsx
@@ -23,4 +23,4 @@ export default function WhisperModelPicker({
variant={variant}
/>
);
-}
\ No newline at end of file
+}
diff --git a/src/components/lib/utils.ts b/src/components/lib/utils.ts
index bd0c391dd..a5ef19350 100644
--- a/src/components/lib/utils.ts
+++ b/src/components/lib/utils.ts
@@ -1,6 +1,6 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { clsx, type ClassValue } from "clsx";
+import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
+ return twMerge(clsx(inputs));
}
diff --git a/src/components/ui/ApiKeyInput.tsx b/src/components/ui/ApiKeyInput.tsx
index c217966b7..2f19c5bcc 100644
--- a/src/components/ui/ApiKeyInput.tsx
+++ b/src/components/ui/ApiKeyInput.tsx
@@ -24,19 +24,14 @@ export default function ApiKeyInput({
}: ApiKeyInputProps) {
const { pasteFromClipboardWithFallback } = useClipboard();
- const variantClasses =
- variant === "purple" ? "border-purple-300 focus:border-purple-500" : "";
+ const variantClasses = variant === "purple" ? "border-purple-300 focus:border-purple-500" : "";
const buttonVariantClasses =
- variant === "purple"
- ? "border-purple-300 text-purple-700 hover:bg-purple-50"
- : "";
+ variant === "purple" ? "border-purple-300 text-purple-700 hover:bg-purple-50" : "";
return (
<div className={className}>
- <label className="block text-sm font-medium text-neutral-700 mb-2">
- {label}
- </label>
+ <label className="block text-sm font-medium text-neutral-700 mb-2">{label}</label>
<div className="flex gap-3">
<Input
type="password"
@@ -53,9 +48,7 @@ export default function ApiKeyInput({
Paste
</Button>
</div>
- {helpText && (
- <p className="text-xs text-neutral-600 mt-2">{helpText}</p>
- )}
+ {helpText && <p className="text-xs text-neutral-600 mt-2">{helpText}</p>}
</div>
);
}
diff --git a/src/components/ui/DotFlashing.tsx b/src/components/ui/DotFlashing.tsx
index 6c735e6ea..b297cb488 100644
--- a/src/components/ui/DotFlashing.tsx
+++ b/src/components/ui/DotFlashing.tsx
@@ -1,8 +1,8 @@
-import React from 'react';
+import React from "react";
export const DotFlashing = () => (
<>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 16 }}>
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: 16 }}>
<div className="dot-flashing"></div>
</div>
<style>{`
@@ -48,4 +48,4 @@ export const DotFlashing = () => (
}
`}</style>
</>
-);
\ No newline at end of file
+);
diff --git a/src/components/ui/Keyboard.tsx b/src/components/ui/Keyboard.tsx
index 144ded230..d7333db37 100644
--- a/src/components/ui/Keyboard.tsx
+++ b/src/components/ui/Keyboard.tsx
@@ -15,7 +15,14 @@ interface KeyProps {
displayValue?: React.ReactNode;
}
-const Key: React.FC<KeyProps> = ({ keyValue, isSelected, onClick, width = "w-12", disabled = false, displayValue }) => {
+const Key: React.FC<KeyProps> = ({
+ keyValue,
+ isSelected,
+ onClick,
+ width = "w-12",
+ disabled = false,
+ displayValue,
+}) => {
const [isPressed, setIsPressed] = useState(false);
const handleClick = () => {
@@ -33,20 +40,20 @@ const Key: React.FC<KeyProps> = ({ keyValue, isSelected, onClick, width = "w-12"
${width} h-12 rounded-lg font-mono text-sm font-medium
transition-all duration-150 ease-in-out
transform active:scale-95
- ${isPressed ? 'translate-y-1 shadow-inner' : 'translate-y-0 shadow-lg'}
+ ${isPressed ? "translate-y-1 shadow-inner" : "translate-y-0 shadow-lg"}
hover:translate-y-0.5 hover:shadow-md
focus:outline-none focus:ring-2 focus:ring-indigo-300
${
isSelected
- ? 'bg-indigo-500 text-white border-2 border-indigo-600'
+ ? "bg-indigo-500 text-white border-2 border-indigo-600"
: disabled
- ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
- : 'bg-white text-gray-800 border-2 border-gray-300 hover:border-gray-400'
+ ? "bg-gray-300 text-gray-500 cursor-not-allowed"
+ : "bg-white text-gray-800 border-2 border-gray-300 hover:border-gray-400"
}
- ${isPressed ? 'bg-gray-100' : ''}
+ ${isPressed ? "bg-gray-100" : ""}
`}
>
- {displayValue ?? (keyValue === 'Space' ? '' : keyValue)}
+ {displayValue ?? (keyValue === "Space" ? "" : keyValue)}
</button>
);
};
@@ -54,15 +61,29 @@ const Key: React.FC<KeyProps> = ({ keyValue, isSelected, onClick, width = "w-12"
export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps) {
const isMac = typeof navigator !== "undefined" && /Mac|Darwin/.test(navigator.platform);
const canUseGlobe = isMac;
- const functionKeys = ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'];
-
- const numberRow = ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='];
-
- const qwertyRow = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\\'];
-
- const asdfRow = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'"];
-
- const zxcvRow = ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/'];
+ const functionKeys = [
+ "Esc",
+ "F1",
+ "F2",
+ "F3",
+ "F4",
+ "F5",
+ "F6",
+ "F7",
+ "F8",
+ "F9",
+ "F10",
+ "F11",
+ "F12",
+ ];
+
+ const numberRow = ["`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="];
+
+ const qwertyRow = ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"];
+
+ const asdfRow = ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"];
+
+ const zxcvRow = ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"];
const handleKeyClick = (key: string) => {
setSelectedKey(key);
@@ -70,7 +91,7 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
useEffect(() => {
if (!canUseGlobe && selectedKey === "GLOBE") {
- setSelectedKey('`');
+ setSelectedKey("`");
}
}, [canUseGlobe, selectedKey, setSelectedKey]);
@@ -84,7 +105,7 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
keyValue={key}
isSelected={selectedKey === key}
onClick={() => handleKeyClick(key)}
- width={key === 'Esc' ? 'w-14' : 'w-12'}
+ width={key === "Esc" ? "w-14" : "w-12"}
/>
))}
</div>
@@ -101,8 +122,8 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
))}
<Key
keyValue="Backspace"
- isSelected={selectedKey === 'Backspace'}
- onClick={() => handleKeyClick('Backspace')}
+ isSelected={selectedKey === "Backspace"}
+ onClick={() => handleKeyClick("Backspace")}
width="w-20"
disabled
/>
@@ -112,8 +133,8 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
<div className="flex justify-center gap-1 mb-2">
<Key
keyValue="Tab"
- isSelected={selectedKey === 'Tab'}
- onClick={() => handleKeyClick('Tab')}
+ isSelected={selectedKey === "Tab"}
+ onClick={() => handleKeyClick("Tab")}
width="w-16"
disabled
/>
@@ -131,8 +152,8 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
<div className="flex justify-center gap-1 mb-2">
<Key
keyValue="Caps"
- isSelected={selectedKey === 'CapsLock'}
- onClick={() => handleKeyClick('CapsLock')}
+ isSelected={selectedKey === "CapsLock"}
+ onClick={() => handleKeyClick("CapsLock")}
width="w-18"
disabled
/>
@@ -146,8 +167,8 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
))}
<Key
keyValue="Enter"
- isSelected={selectedKey === 'Enter'}
- onClick={() => handleKeyClick('Enter')}
+ isSelected={selectedKey === "Enter"}
+ onClick={() => handleKeyClick("Enter")}
width="w-20"
disabled
/>
@@ -157,8 +178,8 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
<div className="flex justify-center gap-1 mb-2">
<Key
keyValue="Shift"
- isSelected={selectedKey === 'Shift'}
- onClick={() => handleKeyClick('Shift')}
+ isSelected={selectedKey === "Shift"}
+ onClick={() => handleKeyClick("Shift")}
width="w-24"
disabled
/>
@@ -173,7 +194,7 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
<Key
keyValue="Shift"
isSelected={false}
- onClick={() => handleKeyClick('Shift')}
+ onClick={() => handleKeyClick("Shift")}
width="w-24"
disabled
/>
@@ -183,23 +204,31 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
<div className="flex justify-center gap-1">
<Key
keyValue="Ctrl"
- isSelected={selectedKey === 'Ctrl'}
- onClick={() => handleKeyClick('Ctrl')}
+ isSelected={selectedKey === "Ctrl"}
+ onClick={() => handleKeyClick("Ctrl")}
width="w-16"
disabled
/>
{canUseGlobe ? (
<Key
keyValue="GLOBE"
- displayValue={<span role="img" aria-label="Globe">🌐</span>}
- isSelected={selectedKey === 'GLOBE'}
- onClick={() => handleKeyClick('GLOBE')}
+ displayValue={
+ <span role="img" aria-label="Globe">
+ 🌐
+ </span>
+ }
+ isSelected={selectedKey === "GLOBE"}
+ onClick={() => handleKeyClick("GLOBE")}
width="w-16"
/>
) : (
<Key
keyValue="Globe"
- displayValue={<span role="img" aria-label="Globe">🌐</span>}
+ displayValue={
+ <span role="img" aria-label="Globe">
+ 🌐
+ </span>
+ }
isSelected={false}
onClick={() => {}}
width="w-16"
@@ -208,28 +237,28 @@ export default function Keyboard({ selectedKey, setSelectedKey }: KeyboardProps)
)}
<Key
keyValue="Alt"
- isSelected={selectedKey === 'Alt'}
- onClick={() => handleKeyClick('Alt')}
+ isSelected={selectedKey === "Alt"}
+ onClick={() => handleKeyClick("Alt")}
width="w-16"
disabled
/>
<Key
keyValue="Space"
- isSelected={selectedKey === 'Space'}
- onClick={() => handleKeyClick('Space')}
+ isSelected={selectedKey === "Space"}
+ onClick={() => handleKeyClick("Space")}
width="w-64"
/>
<Key
keyValue="Alt"
isSelected={false}
- onClick={() => handleKeyClick('Alt')}
+ onClick={() => handleKeyClick("Alt")}
width="w-16"
disabled
/>
<Key
keyValue="Ctrl"
isSelected={false}
- onClick={() => handleKeyClick('Ctrl')}
+ onClick={() => handleKeyClick("Ctrl")}
width="w-16"
disabled
/>
diff --git a/src/components/ui/LanguageSelector.tsx b/src/components/ui/LanguageSelector.tsx
index 5092b5246..b41649234 100644
--- a/src/components/ui/LanguageSelector.tsx
+++ b/src/components/ui/LanguageSelector.tsx
@@ -36,10 +36,7 @@ export default function LanguageSelector({
}, [isOpen]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
- if (
- dropdownRef.current &&
- !dropdownRef.current.contains(event.target as Node)
- ) {
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsOpen(false);
setSearchQuery("");
}
@@ -60,15 +57,11 @@ export default function LanguageSelector({
switch (e.key) {
case "ArrowDown":
e.preventDefault();
- setHighlightedIndex((prev) =>
- prev < filteredLanguages.length - 1 ? prev + 1 : 0
- );
+ setHighlightedIndex((prev) => (prev < filteredLanguages.length - 1 ? prev + 1 : 0));
break;
case "ArrowUp":
e.preventDefault();
- setHighlightedIndex((prev) =>
- prev > 0 ? prev - 1 : filteredLanguages.length - 1
- );
+ setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredLanguages.length - 1));
break;
case "Enter":
e.preventDefault();
@@ -143,9 +136,7 @@ export default function LanguageSelector({
</div>
<div className="max-h-48 overflow-y-auto">
{filteredLanguages.length === 0 ? (
- <div className="px-3 py-2 text-sm text-gray-500">
- No languages found
- </div>
+ <div className="px-3 py-2 text-sm text-gray-500">No languages found</div>
) : (
<div role="listbox">
{filteredLanguages.map((language, index) => (
@@ -160,9 +151,7 @@ export default function LanguageSelector({
aria-selected={language.value === value}
>
{language.label}
- {language.value === value && (
- <span className="ml-2 text-blue-500">✓</span>
- )}
+ {language.value === value && <span className="ml-2 text-blue-500">✓</span>}
</button>
))}
</div>
diff --git a/src/components/ui/LoadingDots.tsx b/src/components/ui/LoadingDots.tsx
index ad1c2a2ce..9b24bf95f 100644
--- a/src/components/ui/LoadingDots.tsx
+++ b/src/components/ui/LoadingDots.tsx
@@ -1,28 +1,28 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect } from "react";
export const LoadingDots = () => {
const [tick, setTick] = useState(0);
-
+
useEffect(() => {
- const interval = setInterval(() => setTick(t => t + 1), 350);
+ const interval = setInterval(() => setTick((t) => t + 1), 350);
return () => clearInterval(interval);
}, []);
-
+
return (
- <div style={{ display: 'flex', alignItems: 'flex-end', height: 10, gap: 1 }}>
- {[0, 1, 2].map(i => (
+ <div style={{ display: "flex", alignItems: "flex-end", height: 10, gap: 1 }}>
+ {[0, 1, 2].map((i) => (
<div
key={i}
style={{
width: 4,
height: 6 + 6 * (tick % 3 === i ? 1 : 0),
- background: '#fff',
+ background: "#fff",
borderRadius: 3,
opacity: 0.9,
- transition: 'height 0.2s',
+ transition: "height 0.2s",
}}
/>
))}
</div>
);
-};
\ No newline at end of file
+};
diff --git a/src/components/ui/ProcessingModeSelector.tsx b/src/components/ui/ProcessingModeSelector.tsx
index 03985b4bb..b5d404470 100644
--- a/src/components/ui/ProcessingModeSelector.tsx
+++ b/src/components/ui/ProcessingModeSelector.tsx
@@ -49,9 +49,7 @@ export default function ProcessingModeSelector({
<Lock className="w-6 h-6 text-blue-600" />
<h4 className="font-medium text-neutral-900">Local Processing</h4>
</div>
- <span className="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full">
- Private
- </span>
+ <span className="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full">Private</span>
</div>
<p className="text-sm text-neutral-600">
Audio stays on your device. Complete privacy, works offline.
diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsx
index 442fb0601..b89e43267 100644
--- a/src/components/ui/PromptStudio.tsx
+++ b/src/components/ui/PromptStudio.tsx
@@ -2,17 +2,17 @@ import React, { useState, useEffect } from "react";
import { Button } from "./button";
import { Textarea } from "./textarea";
import { Card, CardContent, CardHeader, CardTitle } from "./card";
-import {
- Eye,
- Edit3,
- Play,
- Save,
- RotateCcw,
- Copy,
- Sparkles,
+import {
+ Eye,
+ Edit3,
+ Play,
+ Save,
+ RotateCcw,
+ Copy,
+ Sparkles,
Zap,
TestTube,
- AlertTriangle
+ AlertTriangle,
} from "lucide-react";
import { AlertDialog } from "./dialog";
import { useDialogs } from "../../hooks/useDialogs";
@@ -23,7 +23,6 @@ interface PromptStudioProps {
className?: string;
}
-
type ProviderConfig = {
label: string;
apiKeyStorageKey?: string;
@@ -46,10 +45,12 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
const [activeTab, setActiveTab] = useState<"current" | "edit" | "test">("current");
const [editedAgentPrompt, setEditedAgentPrompt] = useState(DEFAULT_PROMPTS.agent);
const [editedRegularPrompt, setEditedRegularPrompt] = useState(DEFAULT_PROMPTS.regular);
- const [testText, setTestText] = useState("Hey Assistant, make this more professional: This is a test message that needs some work.");
+ const [testText, setTestText] = useState(
+ "Hey Assistant, make this more professional: This is a test message that needs some work."
+ );
const [testResult, setTestResult] = useState("");
const [isLoading, setIsLoading] = useState(false);
-
+
const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();
const { agentName } = useAgentName();
@@ -70,13 +71,14 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
const savePrompts = () => {
const customPrompts = {
agent: editedAgentPrompt,
- regular: editedRegularPrompt
+ regular: editedRegularPrompt,
};
-
+
localStorage.setItem("customPrompts", JSON.stringify(customPrompts));
showAlertDialog({
title: "Prompts Saved!",
- description: "Your custom prompts have been saved and will be used for all future AI processing."
+ description:
+ "Your custom prompts have been saved and will be used for all future AI processing.",
});
};
@@ -86,28 +88,29 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
localStorage.removeItem("customPrompts");
showAlertDialog({
title: "Reset Complete",
- description: "Prompts have been reset to default values."
+ description: "Prompts have been reset to default values.",
});
};
-
const testPrompt = async () => {
if (!testText.trim()) return;
-
+
setIsLoading(true);
setTestResult("");
-
+
try {
// Check if reasoning model is enabled and if we have the necessary settings
const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";
const reasoningModel = localStorage.getItem("reasoningModel") || "gpt-4o-mini";
const reasoningProvider = localStorage.getItem("reasoningProvider") || "openai";
-
+
if (!useReasoningModel) {
- setTestResult("⚠️ AI text enhancement is disabled. Enable it in AI Models settings to test prompts.");
+ setTestResult(
+ "⚠️ AI text enhancement is disabled. Enable it in AI Models settings to test prompts."
+ );
return;
}
-
+
const providerConfig = PROVIDER_CONFIG[reasoningProvider] || {
label: reasoningProvider.charAt(0).toUpperCase() + reasoningProvider.slice(1),
};
@@ -131,22 +134,30 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
// Save current prompts temporarily so the test uses them
const currentCustomPrompts = localStorage.getItem("customPrompts");
- localStorage.setItem("customPrompts", JSON.stringify({
- agent: editedAgentPrompt,
- regular: editedRegularPrompt
- }));
-
+ localStorage.setItem(
+ "customPrompts",
+ JSON.stringify({
+ agent: editedAgentPrompt,
+ regular: editedRegularPrompt,
+ })
+ );
+
try {
// For local models, use a different approach
if (reasoningProvider === "local") {
// Call local reasoning directly
- const result = await window.electronAPI.processLocalReasoning(testText, reasoningModel, agentName, {
- customPrompts: {
- agent: editedAgentPrompt,
- regular: editedRegularPrompt
+ const result = await window.electronAPI.processLocalReasoning(
+ testText,
+ reasoningModel,
+ agentName,
+ {
+ customPrompts: {
+ agent: editedAgentPrompt,
+ regular: editedRegularPrompt,
+ },
}
- });
-
+ );
+
if (result.success) {
setTestResult(result.text);
} else {
@@ -157,8 +168,8 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
const result = await ReasoningService.processText(testText, reasoningModel, agentName, {
customPrompts: {
agent: editedAgentPrompt,
- regular: editedRegularPrompt
- }
+ regular: editedRegularPrompt,
+ },
});
setTestResult(result);
}
@@ -170,7 +181,6 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
localStorage.removeItem("customPrompts");
}
}
-
} catch (error) {
console.error("Test failed:", error);
setTestResult(`❌ Test failed: ${error.message}`);
@@ -183,7 +193,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
navigator.clipboard.writeText(prompt);
showAlertDialog({
title: "Copied!",
- description: "Prompt copied to clipboard."
+ description: "Prompt copied to clipboard.",
});
};
@@ -195,7 +205,8 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
Current AI Prompts
</h3>
<p className="text-sm text-gray-600 mb-6">
- These are the exact prompts currently being sent to your AI models. Understanding these helps you see how OpenWhispr thinks!
+ These are the exact prompts currently being sent to your AI models. Understanding these
+ helps you see how OpenWhispr thinks!
</p>
</div>
@@ -208,12 +219,14 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
</CardHeader>
<CardContent>
<div className="bg-gray-50 border rounded-lg p-4 font-mono text-sm">
- <pre className="whitespace-pre-wrap">{editedAgentPrompt.replace(/\{\{agentName\}\}/g, agentName)}</pre>
+ <pre className="whitespace-pre-wrap">
+ {editedAgentPrompt.replace(/\{\{agentName\}\}/g, agentName)}
+ </pre>
</div>
- <Button
- onClick={() => copyPrompt(editedAgentPrompt)}
- variant="outline"
- size="sm"
+ <Button
+ onClick={() => copyPrompt(editedAgentPrompt)}
+ variant="outline"
+ size="sm"
className="mt-3"
>
<Copy className="w-4 h-4 mr-2" />
@@ -233,10 +246,10 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
<div className="bg-gray-50 border rounded-lg p-4 font-mono text-sm">
<pre className="whitespace-pre-wrap">{editedRegularPrompt}</pre>
</div>
- <Button
- onClick={() => copyPrompt(editedRegularPrompt)}
- variant="outline"
- size="sm"
+ <Button
+ onClick={() => copyPrompt(editedRegularPrompt)}
+ variant="outline"
+ size="sm"
className="mt-3"
>
<Copy className="w-4 h-4 mr-2" />
@@ -255,7 +268,8 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
Customize Your AI Prompts
</h3>
<p className="text-sm text-gray-600 mb-6">
- Edit these prompts to change how your AI behaves. Use <code>{"{{agentName}}"}</code> and <code>{"{{text}}"}</code> as placeholders.
+ Edit these prompts to change how your AI behaves. Use <code>{"{{agentName}}"}</code> and{" "}
+ <code>{"{{text}}"}</code> as placeholders.
</p>
</div>
@@ -302,7 +316,6 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
</div>
);
-
const renderTestPlayground = () => {
const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";
const reasoningModel = localStorage.getItem("reasoningModel") || "gpt-4o-mini";
@@ -314,7 +327,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
const providerEndpoint = providerConfig.baseStorageKey
? (localStorage.getItem(providerConfig.baseStorageKey) || "").trim()
: "";
-
+
return (
<div className="space-y-6">
<div>
@@ -358,7 +371,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
)}
</div>
</div>
-
+
<div>
<label className="block text-sm font-medium mb-2">Test Input</label>
<Textarea
@@ -372,11 +385,13 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
Try including "{agentName}" in your text to test agent mode prompts
</p>
{testText && (
- <span className={`text-xs px-2 py-1 rounded-full ${
- testText.toLowerCase().includes(agentName.toLowerCase())
- ? "bg-purple-100 text-purple-700"
- : "bg-green-100 text-green-700"
- }`}>
+ <span
+ className={`text-xs px-2 py-1 rounded-full ${
+ testText.toLowerCase().includes(agentName.toLowerCase())
+ ? "bg-purple-100 text-purple-700"
+ : "bg-green-100 text-green-700"
+ }`}
+ >
{testText.toLowerCase().includes(agentName.toLowerCase())
? "🤖 Agent Mode"
: "✨ Regular Mode"}
@@ -385,8 +400,8 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
</div>
</div>
- <Button
- onClick={testPrompt}
+ <Button
+ onClick={testPrompt}
disabled={!testText.trim() || isLoading || !useReasoningModel}
className="w-full"
>
@@ -398,19 +413,17 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
<div>
<div className="flex items-center justify-between mb-2">
<label className="text-sm font-medium">AI Response</label>
- <Button
- onClick={() => copyPrompt(testResult)}
- variant="ghost"
- size="sm"
- >
+ <Button onClick={() => copyPrompt(testResult)} variant="ghost" size="sm">
<Copy className="w-4 h-4" />
</Button>
</div>
- <div className={`border rounded-lg p-4 text-sm max-h-60 overflow-y-auto ${
- testResult.startsWith("⚠️") || testResult.startsWith("❌")
- ? "bg-amber-50 border-amber-200 text-amber-800"
- : "bg-gray-50 border-gray-200"
- }`}>
+ <div
+ className={`border rounded-lg p-4 text-sm max-h-60 overflow-y-auto ${
+ testResult.startsWith("⚠️") || testResult.startsWith("❌")
+ ? "bg-amber-50 border-amber-200 text-amber-800"
+ : "bg-gray-50 border-gray-200"
+ }`}
+ >
<pre className="whitespace-pre-wrap">{testResult}</pre>
</div>
</div>
@@ -436,7 +449,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
{[
{ id: "current", label: "Current Prompts", icon: Eye },
{ id: "edit", label: "Customize", icon: Edit3 },
- { id: "test", label: "Test", icon: TestTube }
+ { id: "test", label: "Test", icon: TestTube },
].map((tab) => {
const Icon = tab.icon;
return (
@@ -462,4 +475,4 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
{activeTab === "test" && renderTestPlayground()}
</div>
);
-}
\ No newline at end of file
+}
diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsx
index db1bf6208..51ddc2e82 100644
--- a/src/components/ui/SettingsSection.tsx
+++ b/src/components/ui/SettingsSection.tsx
@@ -17,9 +17,7 @@ export const SettingsSection: React.FC<SettingsSectionProps> = ({
<div className={`space-y-4 ${className}`}>
<div>
<h3 className="text-lg font-semibold text-gray-900 mb-2">{title}</h3>
- {description && (
- <p className="text-sm text-gray-600 mb-4">{description}</p>
- )}
+ {description && <p className="text-sm text-gray-600 mb-4">{description}</p>}
</div>
{children}
</div>
diff --git a/src/components/ui/SidebarModal.tsx b/src/components/ui/SidebarModal.tsx
index 5bdab24ce..ec9c6aa9f 100644
--- a/src/components/ui/SidebarModal.tsx
+++ b/src/components/ui/SidebarModal.tsx
@@ -42,12 +42,8 @@ export default function SidebarModal<T extends string>({
<div className="flex h-[90vh]">
{/* Sidebar */}
- <div
- className={`${sidebarWidth} bg-gray-50 border-r border-gray-200 p-4`}
- >
- <h2 className="text-xl font-semibold text-gray-900 mb-4 px-2">
- {title}
- </h2>
+ <div className={`${sidebarWidth} bg-gray-50 border-r border-gray-200 p-4`}>
+ <h2 className="text-xl font-semibold text-gray-900 mb-4 px-2">{title}</h2>
<nav className="space-y-1">
{sidebarItems.map((item) => {
const Icon = item.icon;
diff --git a/src/components/ui/StepProgress.tsx b/src/components/ui/StepProgress.tsx
index 4c1c5644e..33d789d1b 100644
--- a/src/components/ui/StepProgress.tsx
+++ b/src/components/ui/StepProgress.tsx
@@ -12,11 +12,7 @@ interface StepProgressProps {
className?: string;
}
-export default function StepProgress({
- steps,
- currentStep,
- className = "",
-}: StepProgressProps) {
+export default function StepProgress({ steps, currentStep, className = "" }: StepProgressProps) {
return (
<div className={`flex items-center justify-between ${className}`}>
{steps.map((step, index) => {
@@ -28,11 +24,7 @@ export default function StepProgress({
<div key={index} className="flex">
<div
className={`flex items-center gap-2 ${
- isActive
- ? "text-blue-600"
- : isCompleted
- ? "text-green-600"
- : "text-stone-400"
+ isActive ? "text-blue-600" : isCompleted ? "text-green-600" : "text-stone-400"
}`}
style={{ fontFamily: "Noto Sans, sans-serif" }}
>
@@ -41,19 +33,13 @@ export default function StepProgress({
isActive
? "border-blue-600 bg-blue-50 shadow-sm"
: isCompleted
- ? "border-green-600 bg-green-50 shadow-sm"
- : "border-stone-300 bg-white"
+ ? "border-green-600 bg-green-50 shadow-sm"
+ : "border-stone-300 bg-white"
}`}
>
- {isCompleted ? (
- <Check className="w-4 h-4" />
- ) : (
- <Icon className="w-4 h-4" />
- )}
+ {isCompleted ? <Check className="w-4 h-4" /> : <Icon className="w-4 h-4" />}
</div>
- <span className="text-xs font-medium hidden md:block truncate">
- {step.title}
- </span>
+ <span className="text-xs font-medium hidden md:block truncate">{step.title}</span>
</div>
{index < steps.length - 1 && (
<div
diff --git a/src/components/ui/SupportDropdown.tsx b/src/components/ui/SupportDropdown.tsx
index 1a4478205..c05add6d8 100644
--- a/src/components/ui/SupportDropdown.tsx
+++ b/src/components/ui/SupportDropdown.tsx
@@ -15,9 +15,7 @@ interface SupportDropdownProps {
export default function SupportDropdown({ className }: SupportDropdownProps) {
const handleContactSupport = async () => {
try {
- const result = await window.electronAPI?.openExternal(
- );
+ const result = await window.electronAPI?.openExternal("mailto:[email protected]");
if (!result?.success) {
console.error("Failed to open email client:", result?.error);
// Fallback: try opening the email as a web URL
@@ -50,10 +48,7 @@ export default function SupportDropdown({ className }: SupportDropdownProps) {
<HelpCircle size={16} />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="bg-white border border-gray-200 shadow-lg"
- >
+ <DropdownMenuContent align="end" className="bg-white border border-gray-200 shadow-lg">
<DropdownMenuItem
onClick={handleContactSupport}
className="cursor-pointer hover:bg-gray-50 focus:bg-gray-50"
diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsx
index dd5ca1ce7..3996b1f6c 100644
--- a/src/components/ui/Toast.tsx
+++ b/src/components/ui/Toast.tsx
@@ -16,9 +16,7 @@ export interface ToastContextType {
dismiss: (id?: string) => void;
}
-const ToastContext = React.createContext<ToastContextType | undefined>(
- undefined
-);
+const ToastContext = React.createContext<ToastContextType | undefined>(undefined);
export const useToast = () => {
const context = React.useContext(ToastContext);
@@ -28,12 +26,8 @@ export const useToast = () => {
return context;
};
-export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({
- children,
-}) => {
- const [toasts, setToasts] = React.useState<(ToastProps & { id: string })[]>(
- []
- );
+export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const [toasts, setToasts] = React.useState<(ToastProps & { id: string })[]>([]);
const toast = React.useCallback((props: Omit<ToastProps, "id">) => {
const id = Math.random().toString(36).substr(2, 9);
diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsx
index cc6d39bea..c0ccb5cd8 100644
--- a/src/components/ui/TranscriptionItem.tsx
+++ b/src/components/ui/TranscriptionItem.tsx
@@ -18,9 +18,7 @@ export default function TranscriptionItem({
onCopy,
onDelete,
}: TranscriptionItemProps) {
- const timestampSource = item.timestamp.endsWith("Z")
- ? item.timestamp
- : `${item.timestamp}Z`;
+ const timestampSource = item.timestamp.endsWith("Z") ? item.timestamp : `${item.timestamp}Z`;
const timestampDate = new Date(timestampSource);
const formattedTimestamp = Number.isNaN(timestampDate.getTime())
? item.timestamp
@@ -40,13 +38,9 @@ export default function TranscriptionItem({
className="flex items-center gap-2 mb-1"
style={{ marginTop: "2px", lineHeight: "24px" }}
>
- <span className="text-indigo-600 text-xs font-medium">
- #{total - index}
- </span>
+ <span className="text-indigo-600 text-xs font-medium">#{total - index}</span>
<div className="w-px h-3 bg-neutral-300" />
- <span className="text-xs text-neutral-500">
- {formattedTimestamp}
- </span>
+ <span className="text-xs text-neutral-500">{formattedTimestamp}</span>
</div>
<p
className="text-neutral-800 text-sm"
@@ -62,10 +56,7 @@ export default function TranscriptionItem({
{item.text}
</p>
</div>
- <div
- className="flex gap-1 flex-shrink-0"
- style={{ marginTop: "2px" }}
- >
+ <div className="flex gap-1 flex-shrink-0" style={{ marginTop: "2px" }}>
<Button
size="icon"
variant="ghost"
diff --git a/src/components/ui/alert.tsx b/src/components/ui/alert.tsx
index e40141369..dc87abbc9 100644
--- a/src/components/ui/alert.tsx
+++ b/src/components/ui/alert.tsx
@@ -1,7 +1,7 @@
-import * as React from "react"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from "react";
+import { cva, type VariantProps } from "class-variance-authority";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
@@ -17,43 +17,33 @@ const alertVariants = cva(
variant: "default",
},
}
-)
+);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
- <div
- ref={ref}
- role="alert"
- className={cn(alertVariants({ variant }), className)}
- {...props}
- />
-))
-Alert.displayName = "Alert"
+ <div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
+));
+Alert.displayName = "Alert";
-const AlertTitle = React.forwardRef<
- HTMLParagraphElement,
- React.HTMLAttributes<HTMLHeadingElement>
->(({ className, ...props }, ref) => (
- <h5
- ref={ref}
- className={cn("mb-1 font-medium leading-none tracking-tight", className)}
- {...props}
- />
-))
-AlertTitle.displayName = "AlertTitle"
+const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
+ ({ className, ...props }, ref) => (
+ <h5
+ ref={ref}
+ className={cn("mb-1 font-medium leading-none tracking-tight", className)}
+ {...props}
+ />
+ )
+);
+AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("text-sm [&_p]:leading-relaxed", className)}
- {...props}
- />
-))
-AlertDescription.displayName = "AlertDescription"
+ <div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />
+));
+AlertDescription.displayName = "AlertDescription";
-export { Alert, AlertTitle, AlertDescription }
\ No newline at end of file
+export { Alert, AlertTitle, AlertDescription };
diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx
index 800d12165..0163f80f7 100644
--- a/src/components/ui/badge.tsx
+++ b/src/components/ui/badge.tsx
@@ -1,15 +1,14 @@
-import * as React from "react"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from "react";
+import { cva, type VariantProps } from "class-variance-authority";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
- default:
- "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
+ default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
@@ -21,16 +20,13 @@ const badgeVariants = cva(
variant: "default",
},
}
-)
+);
export interface BadgeProps
- extends React.HTMLAttributes<HTMLDivElement>,
- VariantProps<typeof badgeVariants> {}
+ extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
- return (
- <div className={cn(badgeVariants({ variant }), className)} {...props} />
- )
+ return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
-export { Badge, badgeVariants }
\ No newline at end of file
+export { Badge, badgeVariants };
diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx
index 3b08f306e..029440e83 100644
--- a/src/components/ui/card.tsx
+++ b/src/components/ui/card.tsx
@@ -1,79 +1,56 @@
-import * as React from "react"
-
-import { cn } from "../lib/utils"
-
-const Card = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn(
- "rounded-lg border bg-card text-card-foreground shadow-sm",
- className
- )}
- {...props}
- />
-))
-Card.displayName = "Card"
-
-const CardHeader = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("flex flex-col space-y-1.5 p-6", className)}
- {...props}
- />
-))
-CardHeader.displayName = "CardHeader"
-
-const CardTitle = React.forwardRef<
- HTMLParagraphElement,
- React.HTMLAttributes<HTMLHeadingElement>
->(({ className, ...props }, ref) => (
- <h3
- ref={ref}
- className={cn(
- "text-2xl font-semibold leading-none tracking-tight",
- className
- )}
- {...props}
- />
-))
-CardTitle.displayName = "CardTitle"
+import * as React from "react";
+
+import { cn } from "../lib/utils";
+
+const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
+ {...props}
+ />
+ )
+);
+Card.displayName = "Card";
+
+const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
+ )
+);
+CardHeader.displayName = "CardHeader";
+
+const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
+ ({ className, ...props }, ref) => (
+ <h3
+ ref={ref}
+ className={cn("text-2xl font-semibold leading-none tracking-tight", className)}
+ {...props}
+ />
+ )
+);
+CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
- <p
- ref={ref}
- className={cn("text-sm text-muted-foreground", className)}
- {...props}
- />
-))
-CardDescription.displayName = "CardDescription"
-
-const CardContent = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
-))
-CardContent.displayName = "CardContent"
-
-const CardFooter = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("flex items-center p-6 pt-0", className)}
- {...props}
- />
-))
-CardFooter.displayName = "CardFooter"
-
-export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+ <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
+));
+CardDescription.displayName = "CardDescription";
+
+const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
+ )
+);
+CardContent.displayName = "CardContent";
+
+const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
+ )
+);
+CardFooter.displayName = "CardFooter";
+
+export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index b6b6bf5b0..af0666079 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -50,29 +50,14 @@ const DialogContent = React.forwardRef<
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
-const DialogHeader = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) => (
- <div
- className={cn(
- "flex flex-col space-y-1.5 text-center sm:text-left",
- className
- )}
- {...props}
- />
+const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
-const DialogFooter = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) => (
+const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
- className={cn(
- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
- className
- )}
+ className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props}
/>
);
diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx
index 0a84341cd..0eafb8ac3 100644
--- a/src/components/ui/dropdown-menu.tsx
+++ b/src/components/ui/dropdown-menu.tsx
@@ -35,8 +35,7 @@ const DropdownMenuSubTrigger = React.forwardRef<
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
-DropdownMenuSubTrigger.displayName =
- DropdownMenuPrimitive.SubTrigger.displayName;
+DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
@@ -51,8 +50,7 @@ const DropdownMenuSubContent = React.forwardRef<
{...props}
/>
));
-DropdownMenuSubContent.displayName =
- DropdownMenuPrimitive.SubContent.displayName;
+DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
@@ -111,8 +109,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
-DropdownMenuCheckboxItem.displayName =
- DropdownMenuPrimitive.CheckboxItem.displayName;
+DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
@@ -144,11 +141,7 @@ const DropdownMenuLabel = React.forwardRef<
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
- className={cn(
- "px-2 py-1.5 text-sm font-semibold",
- inset && "pl-8",
- className
- )}
+ className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
{...props}
/>
));
@@ -166,15 +159,9 @@ const DropdownMenuSeparator = React.forwardRef<
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
-const DropdownMenuShortcut = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLSpanElement>) => {
+const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return (
- <span
- className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
- {...props}
- />
+ <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx
index 23124aafc..210e85eaa 100644
--- a/src/components/ui/input.tsx
+++ b/src/components/ui/input.tsx
@@ -1,6 +1,6 @@
-import * as React from "react"
+import * as React from "react";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
@@ -15,7 +15,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
)}
{...props}
/>
- )
+ );
}
-export { Input }
+export { Input };
diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx
index 404b74260..a102c8c4e 100644
--- a/src/components/ui/label.tsx
+++ b/src/components/ui/label.tsx
@@ -1,24 +1,19 @@
-import * as React from "react"
-import * as LabelPrimitive from "@radix-ui/react-label"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from "react";
+import * as LabelPrimitive from "@radix-ui/react-label";
+import { cva, type VariantProps } from "class-variance-authority";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
-)
+);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
- VariantProps<typeof labelVariants>
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
- <LabelPrimitive.Root
- ref={ref}
- className={cn(labelVariants(), className)}
- {...props}
- />
-))
-Label.displayName = LabelPrimitive.Root.displayName
+ <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
+));
+Label.displayName = LabelPrimitive.Root.displayName;
-export { Label }
\ No newline at end of file
+export { Label };
diff --git a/src/components/ui/progress.tsx b/src/components/ui/progress.tsx
index e71c0a80d..19619baa2 100644
--- a/src/components/ui/progress.tsx
+++ b/src/components/ui/progress.tsx
@@ -1,7 +1,7 @@
-import * as React from "react"
-import * as ProgressPrimitive from "@radix-ui/react-progress"
+import * as React from "react";
+import * as ProgressPrimitive from "@radix-ui/react-progress";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
@@ -9,10 +9,7 @@ const Progress = React.forwardRef<
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
- className={cn(
- "relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
- className
- )}
+ className={cn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20", className)}
{...props}
>
<ProgressPrimitive.Indicator
@@ -20,7 +17,7 @@ const Progress = React.forwardRef<
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
-))
-Progress.displayName = ProgressPrimitive.Root.displayName
+));
+Progress.displayName = ProgressPrimitive.Root.displayName;
-export { Progress }
\ No newline at end of file
+export { Progress };
diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsx
index 9b5d27e4a..9e28e2855 100644
--- a/src/components/ui/select.tsx
+++ b/src/components/ui/select.tsx
@@ -1,14 +1,14 @@
-import * as React from "react"
-import * as SelectPrimitive from "@radix-ui/react-select"
-import { Check, ChevronDown, ChevronUp } from "lucide-react"
+import * as React from "react";
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { Check, ChevronDown, ChevronUp } from "lucide-react";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
-const Select = SelectPrimitive.Root
+const Select = SelectPrimitive.Root;
-const SelectGroup = SelectPrimitive.Group
+const SelectGroup = SelectPrimitive.Group;
-const SelectValue = SelectPrimitive.Value
+const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
@@ -27,8 +27,8 @@ const SelectTrigger = React.forwardRef<
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
-))
-SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
+));
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
@@ -36,16 +36,13 @@ const SelectScrollUpButton = React.forwardRef<
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
+ className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
-))
-SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
+));
+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
@@ -53,17 +50,13 @@ const SelectScrollDownButton = React.forwardRef<
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
+ className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
-))
-SelectScrollDownButton.displayName =
- SelectPrimitive.ScrollDownButton.displayName
+));
+SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
@@ -94,8 +87,8 @@ const SelectContent = React.forwardRef<
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
-))
-SelectContent.displayName = SelectPrimitive.Content.displayName
+));
+SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
@@ -106,8 +99,8 @@ const SelectLabel = React.forwardRef<
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
-))
-SelectLabel.displayName = SelectPrimitive.Label.displayName
+));
+SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
@@ -128,8 +121,8 @@ const SelectItem = React.forwardRef<
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
-))
-SelectItem.displayName = SelectPrimitive.Item.displayName
+));
+SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
@@ -140,8 +133,8 @@ const SelectSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
-))
-SelectSeparator.displayName = SelectPrimitive.Separator.displayName
+));
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
@@ -154,4 +147,4 @@ export {
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
-}
\ No newline at end of file
+};
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx
index e39fce576..944ad9fed 100644
--- a/src/components/ui/tabs.tsx
+++ b/src/components/ui/tabs.tsx
@@ -1,9 +1,9 @@
-import * as React from "react"
-import * as TabsPrimitive from "@radix-ui/react-tabs"
+import * as React from "react";
+import * as TabsPrimitive from "@radix-ui/react-tabs";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
-const Tabs = TabsPrimitive.Root
+const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
@@ -17,8 +17,8 @@ const TabsList = React.forwardRef<
)}
{...props}
/>
-))
-TabsList.displayName = TabsPrimitive.List.displayName
+));
+TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
@@ -32,8 +32,8 @@ const TabsTrigger = React.forwardRef<
)}
{...props}
/>
-))
-TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
+));
+TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
@@ -47,7 +47,7 @@ const TabsContent = React.forwardRef<
)}
{...props}
/>
-))
-TabsContent.displayName = TabsPrimitive.Content.displayName
+));
+TabsContent.displayName = TabsPrimitive.Content.displayName;
-export { Tabs, TabsList, TabsTrigger, TabsContent }
\ No newline at end of file
+export { Tabs, TabsList, TabsTrigger, TabsContent };
diff --git a/src/components/ui/textarea.tsx b/src/components/ui/textarea.tsx
index ccc28babb..afa394c48 100644
--- a/src/components/ui/textarea.tsx
+++ b/src/components/ui/textarea.tsx
@@ -1,9 +1,8 @@
-import * as React from "react"
+import * as React from "react";
-import { cn } from "../lib/utils"
+import { cn } from "../lib/utils";
-export interface TextareaProps
- extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
+export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
@@ -17,9 +16,9 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
ref={ref}
{...props}
/>
- )
+ );
}
-)
-Textarea.displayName = "Textarea"
+);
+Textarea.displayName = "Textarea";
-export { Textarea }
\ No newline at end of file
+export { Textarea };
diff --git a/src/components/ui/toggle.tsx b/src/components/ui/toggle.tsx
index 6c4b0c4dd..8c293a6d2 100644
--- a/src/components/ui/toggle.tsx
+++ b/src/components/ui/toggle.tsx
@@ -11,14 +11,13 @@ export const Toggle = ({ checked, onChange, disabled = false }: ToggleProps) =>
onClick={() => !disabled && onChange(!checked)}
disabled={disabled}
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:ring-offset-1 ${
- checked ? 'bg-indigo-600' : 'bg-neutral-300'
- } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
+ checked ? "bg-indigo-600" : "bg-neutral-300"
+ } ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
>
<span
className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform shadow-sm ${
- checked ? 'translate-x-5' : 'translate-x-1'
+ checked ? "translate-x-5" : "translate-x-1"
}`}
/>
</button>
);
-
diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx
index 637c32943..effd3e4ee 100644
--- a/src/components/ui/tooltip.tsx
+++ b/src/components/ui/tooltip.tsx
@@ -7,13 +7,10 @@ interface TooltipProps {
export const Tooltip = ({ children, content }: TooltipProps) => {
const [isVisible, setIsVisible] = useState(false);
-
+
return (
<div className="relative inline-block">
- <div
- onMouseEnter={() => setIsVisible(true)}
- onMouseLeave={() => setIsVisible(false)}
- >
+ <div onMouseEnter={() => setIsVisible(true)} onMouseLeave={() => setIsVisible(false)}>
{children}
</div>
{isVisible && (
diff --git a/src/config/InferenceConfig.ts b/src/config/InferenceConfig.ts
index ac87decdd..d6adee723 100644
--- a/src/config/InferenceConfig.ts
+++ b/src/config/InferenceConfig.ts
@@ -1,4 +1,4 @@
-import { cpus } from 'os';
+import { cpus } from "os";
export interface InferenceConfig {
temperature: number;
@@ -33,7 +33,7 @@ export class InferenceConfigManager {
updateConfig(updates: Partial<InferenceConfig>) {
this.config = {
...this.config,
- ...updates
+ ...updates,
};
}
@@ -52,36 +52,36 @@ export class InferenceConfigManager {
repeatPenalty: 1.1,
threads: this.getOptimalThreadCount(),
contextSize: 2048,
- timeout: 30000
+ timeout: 30000,
};
}
// Get config optimized for specific use cases
- getConfigForUseCase(useCase: 'reasoning' | 'creative' | 'factual'): Partial<InferenceConfig> {
+ getConfigForUseCase(useCase: "reasoning" | "creative" | "factual"): Partial<InferenceConfig> {
switch (useCase) {
- case 'reasoning':
+ case "reasoning":
return {
temperature: 0.3,
topK: 40,
topP: 0.9,
- repeatPenalty: 1.1
+ repeatPenalty: 1.1,
};
- case 'creative':
+ case "creative":
return {
temperature: 0.8,
topK: 100,
topP: 0.95,
- repeatPenalty: 1.0
+ repeatPenalty: 1.0,
};
- case 'factual':
+ case "factual":
return {
temperature: 0.1,
topK: 20,
topP: 0.85,
- repeatPenalty: 1.2
+ repeatPenalty: 1.2,
};
}
}
}
-export const inferenceConfig = InferenceConfigManager.getInstance();
\ No newline at end of file
+export const inferenceConfig = InferenceConfigManager.getInstance();
diff --git a/src/config/aiProvidersConfig.ts b/src/config/aiProvidersConfig.ts
index b513723ea..aacdca128 100644
--- a/src/config/aiProvidersConfig.ts
+++ b/src/config/aiProvidersConfig.ts
@@ -12,167 +12,176 @@ export interface AIProvider {
}
export interface AIMode {
- id: 'cloud' | 'local';
+ id: "cloud" | "local";
name: string;
providers: AIProvider[];
}
export const AI_MODES: AIMode[] = [
{
- id: 'cloud',
- name: 'Cloud AI',
+ id: "cloud",
+ name: "Cloud AI",
providers: [
{
- id: 'openai',
- name: 'OpenAI',
+ id: "openai",
+ name: "OpenAI",
models: [
{
- value: 'gpt-3.5-turbo',
- label: 'GPT-3.5 Turbo',
- description: 'Fast and efficient for most tasks'
+ value: "gpt-3.5-turbo",
+ label: "GPT-3.5 Turbo",
+ description: "Fast and efficient for most tasks",
},
{
- value: 'gpt-4o-mini',
- label: 'GPT-4o Mini',
- description: 'Higher quality reasoning'
+ value: "gpt-4o-mini",
+ label: "GPT-4o Mini",
+ description: "Higher quality reasoning",
},
{
- value: 'gpt-4-turbo-preview',
- label: 'GPT-4 Turbo',
- description: 'Most capable model'
- }
- ]
+ value: "gpt-4-turbo-preview",
+ label: "GPT-4 Turbo",
+ description: "Most capable model",
+ },
+ ],
},
{
- id: 'anthropic',
- name: 'Anthropic',
+ id: "anthropic",
+ name: "Anthropic",
models: [
{
- value: 'claude-3-haiku-20240307',
- label: 'Claude 3 Haiku',
- description: 'Fast and affordable'
+ value: "claude-3-haiku-20240307",
+ label: "Claude 3 Haiku",
+ description: "Fast and affordable",
},
{
- value: 'claude-3-sonnet-20240229',
- label: 'Claude 3 Sonnet',
- description: 'Balanced performance'
+ value: "claude-3-sonnet-20240229",
+ label: "Claude 3 Sonnet",
+ description: "Balanced performance",
},
{
- value: 'claude-3-opus-20240229',
- label: 'Claude 3 Opus',
- description: 'Most capable Claude model'
- }
- ]
- }
- ]
+ value: "claude-3-opus-20240229",
+ label: "Claude 3 Opus",
+ description: "Most capable Claude model",
+ },
+ ],
+ },
+ ],
},
{
- id: 'local',
- name: 'Local AI',
+ id: "local",
+ name: "Local AI",
providers: [
{
- id: 'qwen',
- name: 'Qwen',
+ id: "qwen",
+ name: "Qwen",
models: [
{
- value: 'qwen2.5-0.5b-instruct-q5_k_m',
- label: 'Qwen 2.5 0.5B',
- description: 'Smallest, fast but limited',
- size: '0.4GB'
+ value: "qwen2.5-0.5b-instruct-q5_k_m",
+ label: "Qwen 2.5 0.5B",
+ description: "Smallest, fast but limited",
+ size: "0.4GB",
},
{
- value: 'qwen2.5-1.5b-instruct-q5_k_m',
- label: 'Qwen 2.5 1.5B',
- description: 'Small, good for basic tasks',
- size: '1.3GB'
+ value: "qwen2.5-1.5b-instruct-q5_k_m",
+ label: "Qwen 2.5 1.5B",
+ description: "Small, good for basic tasks",
+ size: "1.3GB",
},
{
- value: 'qwen2.5-3b-instruct-q5_k_m',
- label: 'Qwen 2.5 3B',
- description: 'Balanced for general use',
- size: '2.3GB'
+ value: "qwen2.5-3b-instruct-q5_k_m",
+ label: "Qwen 2.5 3B",
+ description: "Balanced for general use",
+ size: "2.3GB",
},
{
- value: 'qwen2.5-7b-instruct-q4km',
- label: 'Qwen 2.5 7B (Q4_K_M)',
- description: 'Large, high quality',
- size: '4.7GB'
+ value: "qwen2.5-7b-instruct-q4km",
+ label: "Qwen 2.5 7B (Q4_K_M)",
+ description: "Large, high quality",
+ size: "4.7GB",
},
{
- value: 'qwen2.5-7b-instruct-q5_k_m',
- label: 'Qwen 2.5 7B (Q5_K_M)',
- description: 'Large, highest quality',
- size: '5.4GB'
- }
- ]
+ value: "qwen2.5-7b-instruct-q5_k_m",
+ label: "Qwen 2.5 7B (Q5_K_M)",
+ description: "Large, highest quality",
+ size: "5.4GB",
+ },
+ ],
},
{
- id: 'mistral',
- name: 'Mistral',
+ id: "mistral",
+ name: "Mistral",
models: [
{
- value: 'mistral-7b-instruct-v0.2-q4_k_m',
- label: 'Mistral 7B v0.2',
- description: 'Popular open model',
- size: '4.1GB'
+ value: "mistral-7b-instruct-v0.2-q4_k_m",
+ label: "Mistral 7B v0.2",
+ description: "Popular open model",
+ size: "4.1GB",
},
{
- value: 'mixtral-8x7b-instruct-v0.1-q3_k_m',
- label: 'Mixtral 8x7B',
- description: 'MoE architecture, very capable',
- size: '26.4GB'
- }
- ]
+ value: "mixtral-8x7b-instruct-v0.1-q3_k_m",
+ label: "Mixtral 8x7B",
+ description: "MoE architecture, very capable",
+ size: "26.4GB",
+ },
+ ],
},
{
- id: 'llama',
- name: 'Meta Llama',
+ id: "llama",
+ name: "Meta Llama",
models: [
{
- value: 'llama-3.2-1b-instruct-q5_k_m',
- label: 'Llama 3.2 1B',
- description: 'Small and efficient',
- size: '1.0GB'
+ value: "llama-3.2-1b-instruct-q5_k_m",
+ label: "Llama 3.2 1B",
+ description: "Small and efficient",
+ size: "1.0GB",
},
{
- value: 'llama-3.2-3b-instruct-q4_k_m',
- label: 'Llama 3.2 3B',
- description: 'Good balance',
- size: '2.0GB'
+ value: "llama-3.2-3b-instruct-q4_k_m",
+ label: "Llama 3.2 3B",
+ description: "Good balance",
+ size: "2.0GB",
},
{
- value: 'llama-3.1-8b-instruct-q4_k_m',
- label: 'Llama 3.1 8B',
- description: 'Large, high quality',
- size: '4.7GB'
- }
- ]
- }
- ]
- }
+ value: "llama-3.1-8b-instruct-q4_k_m",
+ label: "Llama 3.1 8B",
+ description: "Large, high quality",
+ size: "4.7GB",
+ },
+ ],
+ },
+ ],
+ },
];
-export function getAIMode(modeId: 'cloud' | 'local'): AIMode | undefined {
- return AI_MODES.find(mode => mode.id === modeId);
+export function getAIMode(modeId: "cloud" | "local"): AIMode | undefined {
+ return AI_MODES.find((mode) => mode.id === modeId);
}
-export function getAIProvider(modeId: 'cloud' | 'local', providerId: string): AIProvider | undefined {
+export function getAIProvider(
+ modeId: "cloud" | "local",
+ providerId: string
+): AIProvider | undefined {
const mode = getAIMode(modeId);
- return mode?.providers.find(provider => provider.id === providerId);
+ return mode?.providers.find((provider) => provider.id === providerId);
}
-export function getAIModel(modeId: 'cloud' | 'local', providerId: string, modelId: string): AIModel | undefined {
+export function getAIModel(
+ modeId: "cloud" | "local",
+ providerId: string,
+ modelId: string
+): AIModel | undefined {
const provider = getAIProvider(modeId, providerId);
- return provider?.models.find(model => model.value === modelId);
+ return provider?.models.find((model) => model.value === modelId);
}
-export function detectModeFromModel(modelId: string): { mode: 'cloud' | 'local', providerId: string } | undefined {
+export function detectModeFromModel(
+ modelId: string
+): { mode: "cloud" | "local"; providerId: string } | undefined {
for (const mode of AI_MODES) {
for (const provider of mode.providers) {
- if (provider.models.some(model => model.value === modelId)) {
+ if (provider.models.some((model) => model.value === modelId)) {
return { mode: mode.id, providerId: provider.id };
}
}
}
return undefined;
-}
\ No newline at end of file
+}
diff --git a/src/config/constants.ts b/src/config/constants.ts
index cd1f3bb98..f90b199e3 100644
--- a/src/config/constants.ts
+++ b/src/config/constants.ts
@@ -7,16 +7,16 @@ export const normalizeBaseUrl = (value?: string | null): string => {
// Remove common API endpoint suffixes to get the base URL
const suffixReplacements: Array<[RegExp, string]> = [
- [/\/v1\/chat\/completions$/i, '/v1'],
- [/\/chat\/completions$/i, ''],
- [/\/v1\/responses$/i, '/v1'],
- [/\/responses$/i, ''],
- [/\/v1\/models$/i, '/v1'],
- [/\/models$/i, ''],
- [/\/v1\/audio\/transcriptions$/i, '/v1'],
- [/\/audio\/transcriptions$/i, ''],
- [/\/v1\/audio\/translations$/i, '/v1'],
- [/\/audio\/translations$/i, ''],
+ [/\/v1\/chat\/completions$/i, "/v1"],
+ [/\/chat\/completions$/i, ""],
+ [/\/v1\/responses$/i, "/v1"],
+ [/\/responses$/i, ""],
+ [/\/v1\/models$/i, "/v1"],
+ [/\/models$/i, ""],
+ [/\/v1\/audio\/transcriptions$/i, "/v1"],
+ [/\/audio\/transcriptions$/i, ""],
+ [/\/v1\/audio\/translations$/i, "/v1"],
+ [/\/audio\/translations$/i, ""],
];
for (const [pattern, replacement] of suffixReplacements) {
@@ -33,7 +33,7 @@ export const buildApiUrl = (base: string, path: string): string => {
if (!path) {
return normalizedBase;
}
- const normalizedPath = path.startsWith('/') ? path : `/${path}`;
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
return `${normalizedBase}${normalizedPath}`;
};
@@ -50,11 +50,8 @@ const computeBaseUrl = (candidates: Array<string | undefined>, fallback: string)
};
const DEFAULT_OPENAI_BASE = computeBaseUrl(
- [
- env.OPENWHISPR_OPENAI_BASE_URL as string | undefined,
- env.OPENAI_BASE_URL as string | undefined,
- ],
- 'https://api.openai.com/v1'
+ [env.OPENWHISPR_OPENAI_BASE_URL as string | undefined, env.OPENAI_BASE_URL as string | undefined],
+ "https://api.openai.com/v1"
);
const DEFAULT_TRANSCRIPTION_BASE = computeBaseUrl(
@@ -67,18 +64,18 @@ const DEFAULT_TRANSCRIPTION_BASE = computeBaseUrl(
export const API_ENDPOINTS = {
OPENAI_BASE: DEFAULT_OPENAI_BASE,
- OPENAI: buildApiUrl(DEFAULT_OPENAI_BASE, '/responses'),
- OPENAI_MODELS: buildApiUrl(DEFAULT_OPENAI_BASE, '/models'),
- ANTHROPIC: 'https://api.anthropic.com/v1/messages',
- GEMINI: 'https://generativelanguage.googleapis.com/v1beta',
- GROQ_BASE: 'https://api.groq.com/openai/v1',
+ OPENAI: buildApiUrl(DEFAULT_OPENAI_BASE, "/responses"),
+ OPENAI_MODELS: buildApiUrl(DEFAULT_OPENAI_BASE, "/models"),
+ ANTHROPIC: "https://api.anthropic.com/v1/messages",
+ GEMINI: "https://generativelanguage.googleapis.com/v1beta",
+ GROQ_BASE: "https://api.groq.com/openai/v1",
TRANSCRIPTION_BASE: DEFAULT_TRANSCRIPTION_BASE,
- TRANSCRIPTION: buildApiUrl(DEFAULT_TRANSCRIPTION_BASE, '/audio/transcriptions'),
+ TRANSCRIPTION: buildApiUrl(DEFAULT_TRANSCRIPTION_BASE, "/audio/transcriptions"),
} as const;
export const API_VERSIONS = {
- ANTHROPIC: '2023-06-01',
- GEMINI: 'v1beta',
+ ANTHROPIC: "2023-06-01",
+ GEMINI: "v1beta",
} as const;
// Model Configuration
@@ -114,4 +111,4 @@ export const RETRY_CONFIG = {
INITIAL_DELAY: 1000, // 1 second
MAX_DELAY: 10000, // 10 seconds
BACKOFF_MULTIPLIER: 2,
-} as const;
\ No newline at end of file
+} as const;
diff --git a/src/eslint.config.js b/src/eslint.config.js
index f6b44c3e1..d9c671095 100644
--- a/src/eslint.config.js
+++ b/src/eslint.config.js
@@ -2,10 +2,11 @@ import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
+import tseslint from "typescript-eslint";
export default [
- { ignores: ["dist"] },
- // JS and JSX files
+ { ignores: ["dist", "helpers/**", "utils/**"] },
+ // JS and JSX files (renderer - ES modules)
{
files: ["**/*.{js,jsx}"],
languageOptions: {
@@ -27,14 +28,16 @@ export default [
rules: {
...js.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
- // Relaxed rules
- "no-unused-vars": ["warn", { varsIgnorePattern: "^[A-Z_]", argsIgnorePattern: "^_" }],
- "no-console": "off",
- "no-empty": ["error", { allowEmptyCatch: true }],
- "react-refresh/only-export-components": [
+ "no-unused-vars": [
"warn",
- { allowConstantExport: true },
+ { varsIgnorePattern: "^[A-Z_]", argsIgnorePattern: "^_|^event|^err|^error" },
],
+ "no-console": "off",
+ "no-empty": ["error", { allowEmptyCatch: true }],
+ "no-control-regex": "off",
+ "no-useless-catch": "off",
+ "no-async-promise-executor": "off",
+ "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
},
},
// TypeScript files
@@ -46,6 +49,7 @@ export default [
...globals.browser,
...globals.node,
},
+ parser: tseslint.parser,
parserOptions: {
ecmaVersion: "latest",
ecmaFeatures: { jsx: true },
@@ -55,18 +59,15 @@ export default [
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
+ "@typescript-eslint": tseslint.plugin,
},
rules: {
...reactHooks.configs.recommended.rules,
- // TypeScript handles these better
"no-undef": "off",
"no-unused-vars": "off",
"no-console": "off",
"no-empty": ["error", { allowEmptyCatch: true }],
- "react-refresh/only-export-components": [
- "warn",
- { allowConstantExport: true },
- ],
+ "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
},
},
];
diff --git a/src/helpers/ModelManager.ts b/src/helpers/ModelManager.ts
index 4dc74ab53..8c4dfc3c5 100644
--- a/src/helpers/ModelManager.ts
+++ b/src/helpers/ModelManager.ts
@@ -107,29 +107,27 @@ class ModelManager {
const stats = await fsPromises.stat(tempPath);
if (stats.size < MODEL_CONSTRAINTS.MIN_FILE_SIZE) {
- throw new ModelError(
- "Downloaded file appears to be corrupted",
- "DOWNLOAD_CORRUPTED",
- { size: stats.size }
- );
+ throw new ModelError("Downloaded file appears to be corrupted", "DOWNLOAD_CORRUPTED", {
+ size: stats.size,
+ });
}
await fsPromises.rename(tempPath, modelPath);
-
+
this.downloadProgress.delete(modelId);
this.activeDownloads.delete(modelId);
-
+
return modelPath;
} catch (error) {
this.downloadProgress.delete(modelId);
this.activeDownloads.delete(modelId);
-
+
try {
await fsPromises.unlink(tempPath);
} catch {
// Ignore cleanup errors
}
-
+
throw error;
}
}
@@ -142,10 +140,10 @@ class ModelManager {
try {
await fsPromises.unlink(modelPath);
} catch (error: any) {
- if (error.code !== 'ENOENT') {
+ if (error.code !== "ENOENT") {
throw new ModelError(`Failed to delete model`, "DELETE_ERROR", {
modelId,
- error: error.message
+ error: error.message,
});
}
}
@@ -176,14 +174,12 @@ class ModelManager {
): Promise<void> {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(destPath);
-
+
const request = https.get(url, (response) => {
if (response.statusCode === 301 || response.statusCode === 302) {
const redirectUrl = response.headers.location;
if (redirectUrl) {
- this.downloadFile(redirectUrl, destPath, onProgress)
- .then(resolve)
- .catch(reject);
+ this.downloadFile(redirectUrl, destPath, onProgress).then(resolve).catch(reject);
return;
}
}
@@ -193,28 +189,28 @@ class ModelManager {
return;
}
- const totalSize = parseInt(response.headers['content-length'] || '0', 10);
+ const totalSize = parseInt(response.headers["content-length"] || "0", 10);
let downloadedSize = 0;
- response.on('data', (chunk) => {
+ response.on("data", (chunk) => {
downloadedSize += chunk.length;
onProgress(downloadedSize, totalSize);
});
response.pipe(file);
- file.on('finish', () => {
+ file.on("finish", () => {
file.close();
resolve();
});
- file.on('error', (err) => {
+ file.on("error", (err) => {
fs.unlink(destPath, () => {});
reject(err);
});
});
- request.on('error', reject);
+ request.on("error", reject);
});
}
@@ -223,7 +219,7 @@ class ModelManager {
// Dynamic import to avoid loading in frontend
const llamaCppInstaller = require("./llamaCppInstaller").default;
-
+
if (await llamaCppInstaller.isInstalled()) {
this.llamaCppPath = llamaCppInstaller.getInstalledBinaryPath();
return true;
@@ -240,8 +236,9 @@ class ModelManager {
try {
if (p === "llama-cli") {
await new Promise((resolve, reject) => {
- spawn("which", ["llama-cli"])
- .on("close", code => code === 0 ? resolve(p) : reject());
+ spawn("which", ["llama-cli"]).on("close", (code) =>
+ code === 0 ? resolve(p) : reject()
+ );
});
this.llamaCppPath = p;
return true;
@@ -271,12 +268,9 @@ class ModelManager {
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"
- );
+ throw new ModelError(`Model ${modelId} is not downloaded`, "MODEL_NOT_DOWNLOADED");
}
const config = inferenceConfig.getConfig();
@@ -284,16 +278,25 @@ class ModelManager {
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(),
+ "-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(),
+ "-t",
+ finalOptions.threads.toString(),
];
return new Promise((resolve, reject) => {
@@ -313,10 +316,7 @@ class ModelManager {
if (code === 0) {
resolve(output.trim());
} else {
- reject(new ModelError(
- `Inference failed: ${error}`,
- "INFERENCE_ERROR"
- ));
+ reject(new ModelError(`Inference failed: ${error}`, "INFERENCE_ERROR"));
}
});
@@ -329,13 +329,13 @@ class ModelManager {
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)
+ isDownloading: this.activeDownloads.has(model.id),
}))
);
}
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 88ad296c4..a977c4059 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -5,7 +5,6 @@ import logger from "../utils/logger";
const SHORT_CLIP_DURATION_SECONDS = 2.5;
const REASONING_CACHE_TTL = 30000; // 30 seconds
-
class AudioManager {
constructor() {
this.mediaRecorder = null;
@@ -124,22 +123,24 @@ class AudioManager {
{ description: "Failed to start recording", error: error.message },
{ total: true, complete: true }
);
-
+
// Provide more specific error messages
let errorTitle = "Recording Error";
let errorDescription = `Failed to access microphone: ${error.message}`;
-
+
if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {
errorTitle = "Microphone Access Denied";
- errorDescription = "Please grant microphone permission in your system settings and try again.";
+ errorDescription =
+ "Please grant microphone permission in your system settings and try again.";
} else if (error.name === "NotFoundError" || error.name === "DevicesNotFoundError") {
errorTitle = "No Microphone Found";
errorDescription = "No microphone was detected. Please connect a microphone and try again.";
} else if (error.name === "NotReadableError" || error.name === "TrackStartError") {
errorTitle = "Microphone In Use";
- errorDescription = "The microphone is being used by another application. Please close other apps and try again.";
+ errorDescription =
+ "The microphone is being used by another application. Please close other apps and try again.";
}
-
+
this.onError?.({
title: errorTitle,
description: errorDescription,
@@ -243,10 +244,7 @@ class AudioManager {
options.language = language;
}
- const result = await window.electronAPI.transcribeLocalWhisper(
- arrayBuffer,
- options
- );
+ const result = await window.electronAPI.transcribeLocalWhisper(arrayBuffer, options);
if (result.success && result.text) {
this.markLatencyStage("05_transcription_response", {
@@ -263,7 +261,8 @@ class AudioManager {
} else if (result.success === false && result.message === "No audio detected") {
this.onError?.({
title: "No Audio Detected",
- description: "The recording contained no detectable audio. Please check your microphone settings.",
+ description:
+ "The recording contained no detectable audio. Please check your microphone settings.",
});
throw new Error("No audio detected");
} else {
@@ -286,7 +285,9 @@ class AudioManager {
const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);
return { ...fallbackResult, source: "openai-fallback" };
} catch (fallbackError) {
- throw new Error(`Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`);
+ throw new Error(
+ `Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`
+ );
}
} else {
throw new Error(`Local Whisper failed: ${error.message}`);
@@ -300,19 +301,11 @@ class AudioManager {
}
let apiKey = await window.electronAPI.getOpenAIKey();
- if (
- !apiKey ||
- apiKey.trim() === "" ||
- apiKey === "your_openai_api_key_here"
- ) {
+ if (!apiKey || apiKey.trim() === "" || apiKey === "your_openai_api_key_here") {
apiKey = localStorage.getItem("openaiApiKey");
}
- if (
- !apiKey ||
- apiKey.trim() === "" ||
- apiKey === "your_openai_api_key_here"
- ) {
+ if (!apiKey || apiKey.trim() === "" || apiKey === "your_openai_api_key_here") {
throw new Error(
"OpenAI API key not found. Please set your API key in the .env file or Control Panel."
);
@@ -324,8 +317,7 @@ class AudioManager {
async optimizeAudio(audioBlob) {
return new Promise((resolve) => {
- const audioContext = new (window.AudioContext ||
- window.webkitAudioContext)();
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const reader = new FileReader();
reader.onload = async () => {
@@ -337,11 +329,7 @@ class AudioManager {
const sampleRate = 16000;
const channels = 1;
const length = Math.floor(audioBuffer.duration * sampleRate);
- const offlineContext = new OfflineAudioContext(
- channels,
- length,
- sampleRate
- );
+ const offlineContext = new OfflineAudioContext(channels, length, sampleRate);
const source = offlineContext.createBufferSource();
source.buffer = audioBuffer;
@@ -392,11 +380,7 @@ class AudioManager {
let offset = 44;
for (let i = 0; i < length; i++) {
const sample = Math.max(-1, Math.min(1, channelData[i]));
- view.setInt16(
- offset,
- sample < 0 ? sample * 0x8000 : sample * 0x7fff,
- true
- );
+ view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);
offset += 2;
}
@@ -407,34 +391,34 @@ class AudioManager {
logger.logReasoning("CALLING_REASONING_SERVICE", {
model,
agentName,
- textLength: text.length
+ textLength: text.length,
});
-
+
const startTime = Date.now();
-
+
try {
const result = await ReasoningService.processText(text, model, agentName);
-
+
const processingTime = Date.now() - startTime;
-
+
logger.logReasoning("REASONING_SERVICE_COMPLETE", {
model,
processingTimeMs: processingTime,
resultLength: result.length,
- success: true
+ success: true,
});
-
+
return result;
} catch (error) {
const processingTime = Date.now() - startTime;
-
+
logger.logReasoning("REASONING_SERVICE_ERROR", {
model,
processingTimeMs: processingTime,
error: error.message,
- stack: error.stack
+ stack: error.stack,
});
-
+
throw error;
}
}
@@ -462,8 +446,7 @@ class AudioManager {
isTruthy: !!storedValue && storedValue !== "false",
});
- const useReasoning =
- storedValue === "true" || (!!storedValue && storedValue !== "false");
+ const useReasoning = storedValue === "true" || (!!storedValue && storedValue !== "false");
if (!useReasoning) {
this.reasoningAvailabilityCache = {
@@ -512,25 +495,28 @@ class AudioManager {
source,
textLength: normalizedText.length,
textPreview: normalizedText.substring(0, 100) + (normalizedText.length > 100 ? "..." : ""),
- timestamp: new Date().toISOString()
+ timestamp: new Date().toISOString(),
});
- const reasoningModel = (typeof window !== 'undefined' && window.localStorage)
- ? (localStorage.getItem("reasoningModel") || "gpt-4o-mini")
- : "gpt-4o-mini";
- const reasoningProvider = (typeof window !== 'undefined' && window.localStorage)
- ? (localStorage.getItem("reasoningProvider") || "auto")
- : "auto";
- const agentName = (typeof window !== 'undefined' && window.localStorage)
- ? (localStorage.getItem("agentName") || null)
- : null;
+ const reasoningModel =
+ typeof window !== "undefined" && window.localStorage
+ ? localStorage.getItem("reasoningModel") || "gpt-4o-mini"
+ : "gpt-4o-mini";
+ const reasoningProvider =
+ typeof window !== "undefined" && window.localStorage
+ ? localStorage.getItem("reasoningProvider") || "auto"
+ : "auto";
+ const agentName =
+ typeof window !== "undefined" && window.localStorage
+ ? localStorage.getItem("agentName") || null
+ : null;
const useReasoning = await this.isReasoningAvailable();
logger.logReasoning("REASONING_CHECK", {
useReasoning,
reasoningModel,
reasoningProvider,
- agentName
+ agentName,
});
if (useReasoning) {
@@ -540,7 +526,7 @@ class AudioManager {
logger.logReasoning("SENDING_TO_REASONING", {
preparedTextLength: preparedText.length,
model: reasoningModel,
- provider: reasoningProvider
+ provider: reasoningProvider,
});
this.markLatencyStage("06_reasoning_request", {
@@ -548,12 +534,16 @@ class AudioManager {
model: reasoningModel,
provider: reasoningProvider,
});
- const result = await this.processWithReasoningModel(preparedText, reasoningModel, agentName);
+ const result = await this.processWithReasoningModel(
+ preparedText,
+ reasoningModel,
+ agentName
+ );
logger.logReasoning("REASONING_SUCCESS", {
resultLength: result.length,
resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),
- processingTime: new Date().toISOString()
+ processingTime: new Date().toISOString(),
});
this.markLatencyStage("07_reasoning_response", {
@@ -569,7 +559,7 @@ class AudioManager {
logger.logReasoning("REASONING_FAILED", {
error: error.message,
stack: error.stack,
- fallbackToCleanup: true
+ fallbackToCleanup: true,
});
console.error(`Reasoning failed (${source}):`, error.message);
logger.logReasoning("USING_STANDARD_CLEANUP", { reason: "Reasoning failed" });
@@ -586,20 +576,17 @@ class AudioManager {
async processWithOpenAIAPI(audioBlob, metadata = {}) {
const language = localStorage.getItem("preferredLanguage");
- const allowLocalFallback =
- localStorage.getItem("allowLocalFallback") === "true";
+ const allowLocalFallback = localStorage.getItem("allowLocalFallback") === "true";
const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";
try {
-
const durationSeconds = metadata.durationSeconds ?? null;
const shouldSkipOptimizationForDuration =
typeof durationSeconds === "number" &&
durationSeconds > 0 &&
durationSeconds < SHORT_CLIP_DURATION_SECONDS;
- const shouldOptimize =
- !shouldSkipOptimizationForDuration && audioBlob.size > 1024 * 1024;
+ const shouldOptimize = !shouldSkipOptimizationForDuration && audioBlob.size > 1024 * 1024;
const [apiKey, optimizedAudio] = await Promise.all([
this.getAPIKey(),
@@ -614,16 +601,13 @@ class AudioManager {
formData.append("language", language);
}
- const response = await fetch(
- this.getTranscriptionEndpoint(),
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- },
- body: formData,
- }
- );
+ const response = await fetch(this.getTranscriptionEndpoint(), {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: formData,
+ });
if (!response.ok) {
const errorText = await response.text();
@@ -639,7 +623,7 @@ class AudioManager {
textLength: result.text.length,
});
const text = await this.processTranscription(result.text, "openai");
- const source = await this.isReasoningAvailable() ? "openai-reasoned" : "openai";
+ const source = (await this.isReasoningAvailable()) ? "openai-reasoned" : "openai";
return { success: true, text, source };
} else {
throw new Error("No text transcribed");
@@ -659,10 +643,7 @@ class AudioManager {
options.language = language;
}
- const result = await window.electronAPI.transcribeLocalWhisper(
- arrayBuffer,
- options
- );
+ const result = await window.electronAPI.transcribeLocalWhisper(arrayBuffer, options);
if (result.success && result.text) {
this.markLatencyStage("05_transcription_response", {
@@ -690,18 +671,20 @@ class AudioManager {
getTranscriptionModel() {
try {
// Check if a custom model is configured
- const customModel = typeof localStorage !== "undefined"
- ? localStorage.getItem("cloudTranscriptionModel") || ""
- : "";
+ const customModel =
+ typeof localStorage !== "undefined"
+ ? localStorage.getItem("cloudTranscriptionModel") || ""
+ : "";
if (customModel.trim()) {
return customModel.trim();
}
// Auto-detect model based on endpoint
- const endpoint = typeof localStorage !== "undefined"
- ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""
- : "";
+ const endpoint =
+ typeof localStorage !== "undefined"
+ ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""
+ : "";
if (endpoint.includes("groq.com")) {
return "whisper-large-v3-turbo"; // Groq's fast model
@@ -720,9 +703,10 @@ class AudioManager {
}
try {
- const stored = typeof localStorage !== "undefined"
- ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""
- : "";
+ const stored =
+ typeof localStorage !== "undefined"
+ ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""
+ : "";
const trimmed = stored.trim();
const base = trimmed ? trimmed : API_ENDPOINTS.TRANSCRIPTION_BASE;
const normalizedBase = normalizeBaseUrl(base);
@@ -732,9 +716,10 @@ class AudioManager {
return API_ENDPOINTS.TRANSCRIPTION;
}
- const isLocalhost = normalizedBase.includes('://localhost') || normalizedBase.includes('://127.0.0.1');
- if (!normalizedBase.startsWith('https://') && !isLocalhost) {
- console.warn('Non-HTTPS endpoint rejected for security. Using default.');
+ const isLocalhost =
+ normalizedBase.includes("://localhost") || normalizedBase.includes("://127.0.0.1");
+ if (!normalizedBase.startsWith("https://") && !isLocalhost) {
+ console.warn("Non-HTTPS endpoint rejected for security. Using default.");
this.cachedTranscriptionEndpoint = API_ENDPOINTS.TRANSCRIPTION;
return API_ENDPOINTS.TRANSCRIPTION;
}
@@ -743,13 +728,13 @@ class AudioManager {
if (/\/audio\/(transcriptions|translations)$/i.test(normalizedBase)) {
endpoint = normalizedBase;
} else {
- endpoint = buildApiUrl(normalizedBase, '/audio/transcriptions');
+ endpoint = buildApiUrl(normalizedBase, "/audio/transcriptions");
}
this.cachedTranscriptionEndpoint = endpoint;
return endpoint;
} catch (error) {
- console.warn('Failed to resolve transcription endpoint:', error);
+ console.warn("Failed to resolve transcription endpoint:", error);
this.cachedTranscriptionEndpoint = API_ENDPOINTS.TRANSCRIPTION;
return API_ENDPOINTS.TRANSCRIPTION;
}
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index f1138509e..cb0b25ef5 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -38,22 +38,15 @@ class ClipboardManager {
// Copy text to clipboard first - this always works
clipboard.writeText(text);
- this.safeLog(
- "📋 Text copied to clipboard:",
- text.substring(0, 50) + "..."
- );
+ this.safeLog("📋 Text copied to clipboard:", text.substring(0, 50) + "...");
if (process.platform === "darwin") {
// Check accessibility permissions first
- this.safeLog(
- "🔍 Checking accessibility permissions for paste operation..."
- );
+ this.safeLog("🔍 Checking accessibility permissions for paste operation...");
const hasPermissions = await this.checkAccessibilityPermissions();
if (!hasPermissions) {
- this.safeLog(
- "⚠️ No accessibility permissions - text copied to clipboard only"
- );
+ this.safeLog("⚠️ No accessibility permissions - text copied to clipboard only");
const errorMsg =
"Accessibility permissions required for automatic pasting. Text has been copied to clipboard - please paste manually with Cmd+V.";
throw new Error(errorMsg);
@@ -118,7 +111,7 @@ class ClipboardManager {
const timeoutId = setTimeout(() => {
hasTimedOut = true;
- killProcess(pasteProcess, 'SIGKILL');
+ killProcess(pasteProcess, "SIGKILL");
pasteProcess.removeAllListeners();
const errorMsg =
"Paste operation timed out. Text is copied to clipboard - please paste manually with Cmd+V.";
@@ -168,7 +161,7 @@ class ClipboardManager {
const timeoutId = setTimeout(() => {
hasTimedOut = true;
- killProcess(pasteProcess, 'SIGKILL');
+ killProcess(pasteProcess, "SIGKILL");
pasteProcess.removeAllListeners();
reject(
new Error(
@@ -231,15 +224,10 @@ class ClipboardManager {
try {
// Try xdotool (works on X11 and XWayland)
if (commandExists("xdotool")) {
- const result = spawnSync("xdotool", [
- "getactivewindow",
- "getwindowclassname",
- ]);
+ const result = spawnSync("xdotool", ["getactivewindow", "getwindowclassname"]);
if (result.status === 0) {
const className = result.stdout.toString().toLowerCase().trim();
- const isTerminalWindow = terminalClasses.some((term) =>
- className.includes(term)
- );
+ const isTerminalWindow = terminalClasses.some((term) => className.includes(term));
if (isTerminalWindow) {
this.safeLog(`🖥️ Terminal detected via xdotool: ${className}`);
}
@@ -257,9 +245,7 @@ class ClipboardManager {
const classResult = spawnSync("kdotool", ["getwindowclassname", windowId]);
if (classResult.status === 0) {
const className = classResult.stdout.toString().toLowerCase().trim();
- const isTerminalWindow = terminalClasses.some((term) =>
- className.includes(term)
- );
+ const isTerminalWindow = terminalClasses.some((term) => className.includes(term));
if (isTerminalWindow) {
this.safeLog(`🖥️ Terminal detected via kdotool: ${className}`);
}
@@ -314,14 +300,11 @@ class ClipboardManager {
let timedOut = false;
const timeoutId = setTimeout(() => {
timedOut = true;
- killProcess(proc, 'SIGKILL');
+ killProcess(proc, "SIGKILL");
}, 1000);
proc.on("close", (code) => {
- if (timedOut)
- return reject(
- new Error(`Paste with ${tool.cmd} timed out after 1 second`)
- );
+ if (timedOut) return reject(new Error(`Paste with ${tool.cmd} timed out after 1 second`));
clearTimeout(timeoutId);
if (code === 0) {
@@ -348,10 +331,7 @@ class ClipboardManager {
this.safeLog(`✅ Paste successful using ${tool.cmd}`);
return; // Success!
} catch (error) {
- this.safeLog(
- `⚠️ Paste with ${tool.cmd} failed:`,
- error?.message || error
- );
+ this.safeLog(`⚠️ Paste with ${tool.cmd} failed:`, error?.message || error);
// Continue to next tool
}
}
@@ -368,10 +348,7 @@ class ClipboardManager {
if (process.platform !== "darwin") return true;
const now = Date.now();
- if (
- now < this.accessibilityCache.expiresAt &&
- this.accessibilityCache.value !== null
- ) {
+ if (now < this.accessibilityCache.expiresAt && this.accessibilityCache.value !== null) {
return this.accessibilityCache.value;
}
@@ -478,12 +455,7 @@ Would you like to open System Settings now?`;
openSystemSettings() {
const settingsCommands = [
- [
- "open",
- [
- "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
- ],
- ],
+ ["open", ["x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"]],
["open", ["-b", "com.apple.systempreferences"]],
["open", ["/System/Library/PreferencePanes/Security.prefPane"]],
];
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 9c1c7265c..1f5f3bb98 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -13,9 +13,7 @@ class DatabaseManager {
initDatabase() {
try {
const dbFileName =
- process.env.NODE_ENV === "development"
- ? "transcriptions-dev.db"
- : "transcriptions.db";
+ process.env.NODE_ENV === "development" ? "transcriptions-dev.db" : "transcriptions.db";
const dbPath = path.join(app.getPath("userData"), dbFileName);
@@ -42,14 +40,10 @@ class DatabaseManager {
if (!this.db) {
throw new Error("Database not initialized");
}
- const stmt = this.db.prepare(
- "INSERT INTO transcriptions (text) VALUES (?)"
- );
+ const stmt = this.db.prepare("INSERT INTO transcriptions (text) VALUES (?)");
const result = stmt.run(text);
- const fetchStmt = this.db.prepare(
- "SELECT * FROM transcriptions WHERE id = ?"
- );
+ const fetchStmt = this.db.prepare("SELECT * FROM transcriptions WHERE id = ?");
const transcription = fetchStmt.get(result.lastInsertRowid);
return { id: result.lastInsertRowid, success: true, transcription };
@@ -64,9 +58,7 @@ class DatabaseManager {
if (!this.db) {
throw new Error("Database not initialized");
}
- const stmt = this.db.prepare(
- "SELECT * FROM transcriptions ORDER BY timestamp DESC LIMIT ?"
- );
+ const stmt = this.db.prepare("SELECT * FROM transcriptions ORDER BY timestamp DESC LIMIT ?");
const transcriptions = stmt.all(limit);
return transcriptions;
} catch (error) {
@@ -96,9 +88,7 @@ class DatabaseManager {
}
const stmt = this.db.prepare("DELETE FROM transcriptions WHERE id = ?");
const result = stmt.run(id);
- console.log(
- `🗑️ Deleted transcription ${id}, affected rows: ${result.changes}`
- );
+ console.log(`🗑️ Deleted transcription ${id}, affected rows: ${result.changes}`);
return { success: result.changes > 0, id };
} catch (error) {
console.error("❌ Error deleting transcription:", error);
@@ -111,9 +101,7 @@ class DatabaseManager {
try {
const dbPath = path.join(
app.getPath("userData"),
- process.env.NODE_ENV === "development"
- ? "transcriptions-dev.db"
- : "transcriptions.db"
+ process.env.NODE_ENV === "development" ? "transcriptions-dev.db" : "transcriptions.db"
);
if (fs.existsSync(dbPath)) {
fs.unlinkSync(dbPath);
diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.js
index 9e96ad442..038436ca8 100644
--- a/src/helpers/debugLogger.js
+++ b/src/helpers/debugLogger.js
@@ -82,9 +82,7 @@ class DebugLogger {
return argLevel;
}
- const envLevel = normalizeLevel(
- process.env.OPENWHISPR_LOG_LEVEL || process.env.LOG_LEVEL
- );
+ const envLevel = normalizeLevel(process.env.OPENWHISPR_LOG_LEVEL || process.env.LOG_LEVEL);
if (envLevel) {
return envLevel;
}
@@ -261,8 +259,14 @@ class DebugLogger {
if (process.platform === "win32") {
possiblePaths = [
ffmpegPath,
- ffmpegPath?.replace(/app\.asar([/\\])/, 'app.asar.unpacked$1'),
- path.join(process.resourcesPath || "", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg.exe"),
+ ffmpegPath?.replace(/app\.asar([/\\])/, "app.asar.unpacked$1"),
+ path.join(
+ process.resourcesPath || "",
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ "ffmpeg.exe"
+ ),
path.join(process.env.ProgramFiles || "C:\\Program Files", "ffmpeg", "bin", "ffmpeg.exe"),
"C:\\ffmpeg\\bin\\ffmpeg.exe",
].filter(Boolean);
@@ -270,7 +274,13 @@ class DebugLogger {
possiblePaths = [
ffmpegPath,
ffmpegPath?.replace("app.asar", "app.asar.unpacked"),
- path.join(process.resourcesPath || "", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg"),
+ path.join(
+ process.resourcesPath || "",
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ "ffmpeg"
+ ),
"/usr/local/bin/ffmpeg",
"/opt/homebrew/bin/ffmpeg",
"/usr/bin/ffmpeg",
@@ -289,13 +299,17 @@ class DebugLogger {
logWindowsPythonSearch(context, details) {
if (!this.isDebugEnabled() || process.platform !== "win32") return;
- this.debug(`Windows Python Search - ${context}`, {
- ...details,
- platform: process.platform,
- PATH: process.env.PATH?.substring(0, 300) + "...",
- LOCALAPPDATA: process.env.LOCALAPPDATA,
- ProgramFiles: process.env.ProgramFiles,
- }, "python");
+ this.debug(
+ `Windows Python Search - ${context}`,
+ {
+ ...details,
+ platform: process.platform,
+ PATH: process.env.PATH?.substring(0, 300) + "...",
+ LOCALAPPDATA: process.env.LOCALAPPDATA,
+ ProgramFiles: process.env.ProgramFiles,
+ },
+ "python"
+ );
}
logAudioData(context, audioBlob) {
@@ -311,11 +325,7 @@ class DebugLogger {
if (audioBlob instanceof ArrayBuffer) {
audioInfo.byteLength = audioBlob.byteLength;
// Check first few bytes
- const view = new Uint8Array(
- audioBlob,
- 0,
- Math.min(16, audioBlob.byteLength)
- );
+ const view = new Uint8Array(audioBlob, 0, Math.min(16, audioBlob.byteLength));
audioInfo.firstBytes = Array.from(view)
.map((b) => b.toString(16).padStart(2, "0"))
.join(" ");
@@ -333,17 +343,21 @@ class DebugLogger {
logProcessStart(command, args, options = {}) {
if (!this.isDebugEnabled()) return;
- this.debug("Starting process", {
- command,
- args,
- cwd: options.cwd || process.cwd(),
- env: {
- FFMPEG_PATH: options.env?.FFMPEG_PATH,
- FFMPEG_EXECUTABLE: options.env?.FFMPEG_EXECUTABLE,
- FFMPEG_BINARY: options.env?.FFMPEG_BINARY,
- PATH_preview: options.env?.PATH?.substring(0, 200) + "...",
+ this.debug(
+ "Starting process",
+ {
+ command,
+ args,
+ cwd: options.cwd || process.cwd(),
+ env: {
+ FFMPEG_PATH: options.env?.FFMPEG_PATH,
+ FFMPEG_EXECUTABLE: options.env?.FFMPEG_EXECUTABLE,
+ FFMPEG_BINARY: options.env?.FFMPEG_BINARY,
+ PATH_preview: options.env?.PATH?.substring(0, 200) + "...",
+ },
},
- }, "process");
+ "process"
+ );
}
logProcessOutput(processName, type, data) {
@@ -375,7 +389,6 @@ class DebugLogger {
this.logStream = null;
}
}
-
}
// Singleton instance
diff --git a/src/helpers/devServerManager.js b/src/helpers/devServerManager.js
index 26905313a..e6268a4c6 100644
--- a/src/helpers/devServerManager.js
+++ b/src/helpers/devServerManager.js
@@ -1,9 +1,5 @@
class DevServerManager {
- static async waitForDevServer(
- url = "http://localhost:5174/",
- maxAttempts = 30,
- delay = 1000
- ) {
+ static async waitForDevServer(url = "http://localhost:5174/", maxAttempts = 30, delay = 1000) {
for (let i = 0; i < maxAttempts; i++) {
try {
const http = require("http");
@@ -34,9 +30,7 @@ class DevServerManager {
return true;
}
} catch (error) {
- console.log(
- `Waiting for dev server... attempt ${i + 1}/${maxAttempts}`
- );
+ console.log(`Waiting for dev server... attempt ${i + 1}/${maxAttempts}`);
}
await new Promise((resolve) => setTimeout(resolve, delay));
}
@@ -46,25 +40,14 @@ class DevServerManager {
static getAppUrl(isControlPanel = false) {
if (process.env.NODE_ENV === "development") {
- return isControlPanel
- ? "http://localhost:5174/?panel=true"
- : "http://localhost:5174/";
+ return isControlPanel ? "http://localhost:5174/?panel=true" : "http://localhost:5174/";
} else {
const path = require("path");
- const htmlPath = path.join(
- __dirname,
- "..",
- "..",
- "src",
- "dist",
- "index.html"
- );
- const url = isControlPanel
- ? `file://${htmlPath}?panel=true`
- : `file://${htmlPath}`;
+ const htmlPath = path.join(__dirname, "..", "..", "src", "dist", "index.html");
+ const url = isControlPanel ? `file://${htmlPath}?panel=true` : `file://${htmlPath}`;
return url;
}
}
}
-module.exports = DevServerManager;
\ No newline at end of file
+module.exports = DevServerManager;
diff --git a/src/helpers/dragManager.js b/src/helpers/dragManager.js
index 72d4e523d..7b57eece8 100644
--- a/src/helpers/dragManager.js
+++ b/src/helpers/dragManager.js
@@ -60,11 +60,7 @@ class DragManager {
}
this.mouseTrackingInterval = setInterval(() => {
- if (
- this.isDragging &&
- this.targetWindow &&
- !this.targetWindow.isDestroyed()
- ) {
+ if (this.isDragging && this.targetWindow && !this.targetWindow.isDestroyed()) {
this.updateWindowPosition();
}
}, 16); // ~60fps
diff --git a/src/helpers/environment.js b/src/helpers/environment.js
index d023fa2d2..8c8a8d144 100644
--- a/src/helpers/environment.js
+++ b/src/helpers/environment.js
@@ -132,12 +132,12 @@ OPENAI_API_KEY=${apiKey}
saveAllKeysToEnvFile() {
try {
const envPath = path.join(app.getPath("userData"), ".env");
-
+
// Build env content with all current keys
let envContent = `# OpenWhispr Environment Variables
# This file was created automatically for production use
`;
-
+
if (process.env.OPENAI_API_KEY) {
envContent += `OPENAI_API_KEY=${process.env.OPENAI_API_KEY}\n`;
}
@@ -152,7 +152,7 @@ OPENAI_API_KEY=${apiKey}
}
fs.writeFileSync(envPath, envContent, "utf8");
-
+
// Reload the env file
require("dotenv").config({ path: envPath });
diff --git a/src/helpers/globeKeyManager.js b/src/helpers/globeKeyManager.js
index 923340407..c890e7aed 100644
--- a/src/helpers/globeKeyManager.js
+++ b/src/helpers/globeKeyManager.js
@@ -29,9 +29,7 @@ class GlobeKeyManager extends EventEmitter {
try {
fs.accessSync(listenerPath, fs.constants.X_OK);
} catch (accessError) {
- this.reportError(
- new Error(`macOS Globe listener is not executable: ${listenerPath}`)
- );
+ this.reportError(new Error(`macOS Globe listener is not executable: ${listenerPath}`));
return;
}
@@ -115,12 +113,7 @@ class GlobeKeyManager extends EventEmitter {
path.join(process.resourcesPath, "bin", "macos-globe-listener"),
path.join(process.resourcesPath, "resources", "macos-globe-listener"),
path.join(process.resourcesPath, "resources", "bin", "macos-globe-listener"),
- path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "resources",
- "macos-globe-listener"
- ),
+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "macos-globe-listener"),
path.join(
process.resourcesPath,
"app.asar.unpacked",
@@ -131,9 +124,7 @@ class GlobeKeyManager extends EventEmitter {
].forEach((candidate) => candidates.add(candidate));
}
- const candidatePaths = [
- ...candidates,
- ];
+ const candidatePaths = [...candidates];
for (const candidate of candidatePaths) {
try {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index bbe90a972..cf7ac8f61 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -193,41 +193,35 @@ class IPCHandlers {
});
// Whisper handlers
- ipcMain.handle(
- "transcribe-local-whisper",
- async (event, audioBlob, options = {}) => {
- debugLogger.log('transcribe-local-whisper called', {
- audioBlobType: typeof audioBlob,
- audioBlobSize: audioBlob?.byteLength || audioBlob?.length || 0,
- options
+ ipcMain.handle("transcribe-local-whisper", async (event, audioBlob, options = {}) => {
+ debugLogger.log("transcribe-local-whisper called", {
+ audioBlobType: typeof audioBlob,
+ audioBlobSize: audioBlob?.byteLength || audioBlob?.length || 0,
+ options,
+ });
+
+ try {
+ const result = await this.whisperManager.transcribeLocalWhisper(audioBlob, options);
+
+ debugLogger.log("Whisper result", {
+ success: result.success,
+ hasText: !!result.text,
+ message: result.message,
+ error: result.error,
});
-
- try {
- const result = await this.whisperManager.transcribeLocalWhisper(
- audioBlob,
- options
- );
-
- debugLogger.log('Whisper result', {
- success: result.success,
- hasText: !!result.text,
- message: result.message,
- error: result.error
- });
-
- // Check if no audio was detected and send appropriate event
- if (!result.success && result.message === "No audio detected") {
- debugLogger.log('Sending no-audio-detected event to renderer');
- event.sender.send("no-audio-detected");
- }
- return result;
- } catch (error) {
- debugLogger.error('Local Whisper transcription error', error);
- throw error;
+ // Check if no audio was detected and send appropriate event
+ if (!result.success && result.message === "No audio detected") {
+ debugLogger.log("Sending no-audio-detected event to renderer");
+ event.sender.send("no-audio-detected");
}
+
+ return result;
+ } catch (error) {
+ debugLogger.error("Local Whisper transcription error", error);
+ throw error;
}
- );
+ });
ipcMain.handle("check-whisper-installation", async (event) => {
return this.whisperManager.checkWhisperInstallation();
@@ -284,13 +278,10 @@ class IPCHandlers {
ipcMain.handle("download-whisper-model", async (event, modelName) => {
try {
- const result = await this.whisperManager.downloadWhisperModel(
- modelName,
- (progressData) => {
- // Forward progress updates to the renderer
- event.sender.send("whisper-download-progress", progressData);
- }
- );
+ const result = await this.whisperManager.downloadWhisperModel(modelName, (progressData) => {
+ // Forward progress updates to the renderer
+ event.sender.send("whisper-download-progress", progressData);
+ });
// Send completion event
event.sender.send("whisper-download-progress", {
@@ -301,7 +292,6 @@ class IPCHandlers {
return result;
} catch (error) {
-
// Send error event
event.sender.send("whisper-download-progress", {
type: "error",
@@ -368,13 +358,13 @@ class IPCHandlers {
// Model management handlers
ipcMain.handle("model-get-all", async () => {
try {
- console.log('[IPC] model-get-all called');
+ console.log("[IPC] model-get-all called");
const modelManager = require("./modelManagerBridge").default;
const models = await modelManager.getModelsWithStatus();
- console.log('[IPC] Returning models:', models.length);
+ console.log("[IPC] Returning models:", models.length);
return models;
} catch (error) {
- console.error('[IPC] Error in model-get-all:', error);
+ console.error("[IPC] Error in model-get-all:", error);
throw error;
}
});
@@ -400,11 +390,11 @@ class IPCHandlers {
);
return { success: true, path: result };
} catch (error) {
- return {
- success: false,
+ return {
+ success: false,
error: error.message,
code: error.code,
- details: error.details
+ details: error.details,
};
}
});
@@ -415,11 +405,11 @@ class IPCHandlers {
await modelManager.deleteModel(modelId);
return { success: true };
} catch (error) {
- return {
- success: false,
+ return {
+ success: false,
error: error.message,
code: error.code,
- details: error.details
+ details: error.details,
};
}
});
@@ -445,11 +435,11 @@ class IPCHandlers {
await modelManager.ensureLlamaCpp();
return { available: true };
} catch (error) {
- return {
- available: false,
+ return {
+ available: false,
error: error.message,
code: error.code,
- details: error.details
+ details: error.details,
};
}
});
@@ -490,56 +480,64 @@ class IPCHandlers {
});
// Anthropic reasoning handler
- ipcMain.handle("process-anthropic-reasoning", async (event, text, modelId, agentName, config) => {
- try {
- const apiKey = this.environmentManager.getAnthropicKey();
-
- if (!apiKey) {
- throw new Error("Anthropic API key not configured");
- }
+ ipcMain.handle(
+ "process-anthropic-reasoning",
+ async (event, text, modelId, agentName, config) => {
+ try {
+ const apiKey = this.environmentManager.getAnthropicKey();
- const systemPrompt = "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
- const userPrompt = agentName && text.toLowerCase().includes(agentName.toLowerCase())
- ? `You are ${agentName}, a helpful AI assistant. Clean up the following dictated text by fixing grammar, punctuation, and formatting. Remove any reference to your name. Output ONLY the cleaned text without explanations or options:\n\n${text}`
- : `Clean up the following dictated text by fixing grammar, punctuation, and formatting. Output ONLY the cleaned text without any explanations, options, or commentary:\n\n${text}`;
-
- const requestBody = {
- model: modelId || "claude-3-5-sonnet-20241022",
- messages: [{ role: "user", content: userPrompt }],
- system: systemPrompt,
- max_tokens: config?.maxTokens || Math.max(100, Math.min(text.length * 2, 4096)),
- temperature: config?.temperature || 0.3,
- };
+ if (!apiKey) {
+ throw new Error("Anthropic API key not configured");
+ }
- const response = await fetch("https://api.anthropic.com/v1/messages", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-API-Key": apiKey,
- "anthropic-version": "2023-06-01",
- },
- body: JSON.stringify(requestBody),
- });
+ const systemPrompt =
+ "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
+ const userPrompt =
+ agentName && text.toLowerCase().includes(agentName.toLowerCase())
+ ? `You are ${agentName}, a helpful AI assistant. Clean up the following dictated text by fixing grammar, punctuation, and formatting. Remove any reference to your name. Output ONLY the cleaned text without explanations or options:\n\n${text}`
+ : `Clean up the following dictated text by fixing grammar, punctuation, and formatting. Output ONLY the cleaned text without any explanations, options, or commentary:\n\n${text}`;
+
+ const requestBody = {
+ model: modelId || "claude-3-5-sonnet-20241022",
+ messages: [{ role: "user", content: userPrompt }],
+ system: systemPrompt,
+ max_tokens: config?.maxTokens || Math.max(100, Math.min(text.length * 2, 4096)),
+ temperature: config?.temperature || 0.3,
+ };
+
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-API-Key": apiKey,
+ "anthropic-version": "2023-06-01",
+ },
+ body: JSON.stringify(requestBody),
+ });
- if (!response.ok) {
- const errorText = await response.text();
- let errorData = { error: response.statusText };
- try {
- errorData = JSON.parse(errorText);
- } catch {
- errorData = { error: errorText || response.statusText };
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData = { error: response.statusText };
+ try {
+ errorData = JSON.parse(errorText);
+ } catch {
+ errorData = { error: errorText || response.statusText };
+ }
+ throw new Error(
+ errorData.error?.message ||
+ errorData.error ||
+ `Anthropic API error: ${response.status}`
+ );
}
- throw new Error(errorData.error?.message || errorData.error || `Anthropic API error: ${response.status}`);
- }
- const data = await response.json();
- return { success: true, text: data.content[0].text.trim() };
- } catch (error) {
- debugLogger.error("Anthropic reasoning error:", error);
- return { success: false, error: error.message };
+ const data = await response.json();
+ return { success: true, text: data.content[0].text.trim() };
+ } catch (error) {
+ debugLogger.error("Anthropic reasoning error:", error);
+ return { success: false, error: error.message };
+ }
}
- });
-
+ );
// Check if local reasoning is available
ipcMain.handle("check-local-reasoning-available", async () => {
@@ -610,10 +608,7 @@ class IPCHandlers {
}
if (process.platform === "win32") {
- const uri =
- target === "microphone"
- ? "ms-settings:privacy-microphone"
- : "ms-settings:sound";
+ const uri = target === "microphone" ? "ms-settings:privacy-microphone" : "ms-settings:sound";
try {
await shell.openExternal(uri);
return { success: true };
diff --git a/src/helpers/llamaCppInstaller.js b/src/helpers/llamaCppInstaller.js
index 0ed938c99..af3b3efa9 100644
--- a/src/helpers/llamaCppInstaller.js
+++ b/src/helpers/llamaCppInstaller.js
@@ -10,7 +10,7 @@ const os = require("os");
// Only import unzipper in main process
let unzipper;
-if (typeof window === 'undefined') {
+if (typeof window === "undefined") {
unzipper = require("unzipper");
}
@@ -54,7 +54,7 @@ class LlamaCppInstaller {
return true;
}
}
-
+
// Then check for local installation
const binaryPath = this.getInstalledBinaryPath();
await fsPromises.access(binaryPath, fs.constants.X_OK);
@@ -69,14 +69,15 @@ class LlamaCppInstaller {
return new Promise((resolve) => {
// Cross-platform command resolution
const checkCmd = this.platform === "win32" ? "where" : "which";
- const binaryNames = this.platform === "win32"
- ? ["llama-cli.exe", "llama.exe"]
- : ["llama-cli", "llama", "llama.cpp"];
-
+ const binaryNames =
+ this.platform === "win32"
+ ? ["llama-cli.exe", "llama.exe"]
+ : ["llama-cli", "llama", "llama.cpp"];
+
// Try each possible binary name
let found = false;
let remaining = binaryNames.length;
-
+
for (const name of binaryNames) {
const proc = spawn(checkCmd, [name], {
shell: true,
@@ -91,7 +92,7 @@ class LlamaCppInstaller {
proc.on("close", (code) => {
if (!found && code === 0 && output) {
found = true;
- resolve(output.trim().split('\n')[0]);
+ resolve(output.trim().split("\n")[0]);
}
remaining--;
if (remaining === 0 && !found) {
@@ -117,7 +118,7 @@ class LlamaCppInstaller {
async getVersion() {
try {
const binaryPath = this.binPath || this.getInstalledBinaryPath();
-
+
return new Promise((resolve, reject) => {
const proc = spawn(binaryPath, ["--version"], {
shell: false,
@@ -176,52 +177,57 @@ class LlamaCppInstaller {
async downloadBinary(url, destPath) {
return new Promise((resolve, reject) => {
const file = createWriteStream(destPath);
-
- https.get(url, (response) => {
- if (response.statusCode === 302 || response.statusCode === 301) {
- // Handle redirect
- https.get(response.headers.location, (redirectResponse) => {
- redirectResponse.pipe(file);
+
+ https
+ .get(url, (response) => {
+ if (response.statusCode === 302 || response.statusCode === 301) {
+ // Handle redirect
+ https
+ .get(response.headers.location, (redirectResponse) => {
+ redirectResponse.pipe(file);
+ file.on("finish", () => {
+ file.close();
+ resolve();
+ });
+ })
+ .on("error", reject);
+ } else if (response.statusCode === 200) {
+ response.pipe(file);
file.on("finish", () => {
file.close();
resolve();
});
- }).on("error", reject);
- } else if (response.statusCode === 200) {
- response.pipe(file);
- file.on("finish", () => {
- file.close();
- resolve();
- });
- } else {
- reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
- }
- }).on("error", reject);
+ } else {
+ reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
+ }
+ })
+ .on("error", reject);
});
}
async install() {
try {
await this.ensureInstallDir();
-
+
// For now, return a message about manual installation
// since we don't have a real binary distribution yet
return {
success: false,
- message: "Please install llama.cpp manually using Homebrew (macOS) or from source. Run: brew install llama.cpp",
+ message:
+ "Please install llama.cpp manually using Homebrew (macOS) or from source. Run: brew install llama.cpp",
};
-
+
// Future implementation:
// const url = this.getReleaseUrl();
// const binaryPath = this.getInstalledBinaryPath();
- //
+ //
// await this.downloadBinary(url, binaryPath);
- //
+ //
// // Make executable on Unix-like systems
// if (this.platform !== "win32") {
// await fsPromises.chmod(binaryPath, 0o755);
// }
- //
+ //
// this.binPath = binaryPath;
// return { success: true, path: binaryPath };
} catch (error) {
@@ -251,17 +257,17 @@ class LlamaCppInstaller {
if (this.binPath) {
return this.binPath;
}
-
+
// Check for system installation first
const systemPath = await this.getSystemBinaryPath();
if (systemPath) {
this.binPath = systemPath;
return systemPath;
}
-
+
// Fall back to local installation
return this.getInstalledBinaryPath();
}
}
-module.exports = { default: new LlamaCppInstaller() };
\ No newline at end of file
+module.exports = { default: new LlamaCppInstaller() };
diff --git a/src/helpers/llamaCppInstaller.ts b/src/helpers/llamaCppInstaller.ts
index 6180eda9d..daaebd6ac 100644
--- a/src/helpers/llamaCppInstaller.ts
+++ b/src/helpers/llamaCppInstaller.ts
@@ -10,7 +10,7 @@ import os from "os";
// Only import unzipper in main process
let unzipper: any;
-if (typeof window === 'undefined') {
+if (typeof window === "undefined") {
unzipper = require("unzipper");
}
@@ -63,14 +63,14 @@ class LlamaCppInstaller {
}
async getVersion(): Promise<string | null> {
- if (!await this.isInstalled()) {
+ 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();
});
@@ -88,7 +88,7 @@ class LlamaCppInstaller {
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") {
@@ -96,53 +96,56 @@ class LlamaCppInstaller {
} 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);
+
+ 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;
}
- }
-
- 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);
+ 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)
+ await fs
+ .createReadStream(archivePath)
.pipe(unzipper.Extract({ path: this.installDir }))
.promise();
} else {
@@ -191,9 +194,9 @@ class LlamaCppInstaller {
}
} catch (error: any) {
console.error("llama.cpp installation error:", error);
- return {
- success: false,
- error: error.message || "Installation failed"
+ return {
+ success: false,
+ error: error.message || "Installation failed",
};
}
}
@@ -204,12 +207,12 @@ class LlamaCppInstaller {
this.binPath = null;
return { success: true };
} catch (error: any) {
- return {
- success: false,
- error: error.message || "Uninstall failed"
+ return {
+ success: false,
+ error: error.message || "Uninstall failed",
};
}
}
}
-export default new LlamaCppInstaller();
\ No newline at end of file
+export default new LlamaCppInstaller();
diff --git a/src/helpers/menuManager.js b/src/helpers/menuManager.js
index e1141d575..c5b3a2c7a 100644
--- a/src/helpers/menuManager.js
+++ b/src/helpers/menuManager.js
@@ -57,10 +57,7 @@ class MenuManager {
{ type: "separator" },
{
label: "Speech",
- submenu: [
- { role: "startSpeaking" },
- { role: "stopSpeaking" },
- ],
+ submenu: [{ role: "startSpeaking" }, { role: "stopSpeaking" }],
},
],
},
@@ -102,7 +99,7 @@ class MenuManager {
],
},
];
-
+
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
} else {
@@ -140,7 +137,7 @@ class MenuManager {
],
},
];
-
+
const menu = Menu.buildFromTemplate(template);
controlPanelWindow.setMenu(menu);
}
diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.js
index b13a07e30..1b7bbf6ab 100644
--- a/src/helpers/modelManagerBridge.js
+++ b/src/helpers/modelManagerBridge.js
@@ -9,9 +9,9 @@ const { app } = require("electron");
let modelRegistryData;
try {
modelRegistryData = require("../models/modelRegistryData.json");
- console.log('[ModelManager] Loaded registry data successfully');
+ console.log("[ModelManager] Loaded registry data successfully");
} catch (error) {
- console.error('[ModelManager] Failed to load registry data:', error);
+ console.error("[ModelManager] Failed to load registry data:", error);
// Fallback to inline data
modelRegistryData = {
providers: [
@@ -28,7 +28,7 @@ try {
description: "Smallest model, fast but limited capabilities",
fileName: "qwen2.5-0.5b-instruct-q5_k_m.gguf",
quantization: "q5_k_m",
- contextLength: 32768
+ contextLength: 32768,
},
{
id: "qwen2.5-1.5b-instruct-q5_k_m",
@@ -38,7 +38,7 @@ try {
description: "Small model, good for basic tasks",
fileName: "qwen2.5-1.5b-instruct-q5_k_m.gguf",
quantization: "q5_k_m",
- contextLength: 32768
+ contextLength: 32768,
},
{
id: "qwen2.5-3b-instruct-q5_k_m",
@@ -48,7 +48,7 @@ try {
description: "Balanced model for general use",
fileName: "qwen2.5-3b-instruct-q5_k_m.gguf",
quantization: "q5_k_m",
- contextLength: 32768
+ contextLength: 32768,
},
{
id: "qwen2.5-7b-instruct-q4km",
@@ -59,21 +59,21 @@ try {
fileName: "qwen2.5-7b-instruct-q4_k_m.gguf",
quantization: "q4_k_m",
contextLength: 128000,
- recommended: true
+ recommended: true,
},
{
id: "qwen2.5-7b-instruct-q5_k_m",
name: "Qwen2.5 7B",
- size: "5.4GB",
+ size: "5.4GB",
sizeBytes: 5798205849,
description: "Large model, high quality reasoning (Q5_K_M quantization)",
fileName: "qwen2.5-7b-instruct-q5_k_m.gguf",
quantization: "q5_k_m",
- contextLength: 128000
- }
- ]
- }
- ]
+ contextLength: 128000,
+ },
+ ],
+ },
+ ],
};
}
@@ -117,30 +117,30 @@ class ModelManager {
async getAllModels() {
try {
const models = [];
-
- console.log('[ModelManager] Getting all models from registry');
- console.log('[ModelManager] Registry data:', modelRegistryData);
-
+
+ console.log("[ModelManager] Getting all models from registry");
+ console.log("[ModelManager] Registry data:", modelRegistryData);
+
// Get all models from registry
for (const provider of modelRegistryData.providers) {
for (const model of provider.models) {
const modelPath = path.join(this.modelsDir, model.fileName);
const isDownloaded = await this.checkFileExists(modelPath);
-
+
models.push({
...model,
providerId: provider.id,
providerName: provider.name,
isDownloaded,
- path: isDownloaded ? modelPath : null
+ path: isDownloaded ? modelPath : null,
});
}
}
-
- console.log('[ModelManager] Found models:', models.length);
+
+ console.log("[ModelManager] Found models:", models.length);
return models;
} catch (error) {
- console.error('[ModelManager] Error getting all models:', error);
+ console.error("[ModelManager] Error getting all models:", error);
throw error;
}
}
@@ -152,7 +152,7 @@ class ModelManager {
async isModelDownloaded(modelId) {
const modelInfo = this.findModelById(modelId);
if (!modelInfo) return false;
-
+
const modelPath = path.join(this.modelsDir, modelInfo.model.fileName);
return this.checkFileExists(modelPath);
}
@@ -168,7 +168,7 @@ class ModelManager {
findModelById(modelId) {
for (const provider of modelRegistryData.providers) {
- const model = provider.models.find(m => m.id === modelId);
+ const model = provider.models.find((m) => m.id === modelId);
if (model) {
return { model, provider };
}
@@ -192,7 +192,9 @@ class ModelManager {
// Check if already downloading
if (this.activeDownloads.get(modelId)) {
- throw new ModelError("Model is already being downloaded", "DOWNLOAD_IN_PROGRESS", { modelId });
+ throw new ModelError("Model is already being downloaded", "DOWNLOAD_IN_PROGRESS", {
+ modelId,
+ });
}
this.activeDownloads.set(modelId, true);
@@ -200,13 +202,13 @@ class ModelManager {
try {
// Construct download URL based on provider
const downloadUrl = this.getDownloadUrl(provider, model);
-
+
await this.downloadFile(downloadUrl, modelPath, (progress, downloadedSize, totalSize) => {
- this.downloadProgress.set(modelId, {
- modelId,
- progress,
- downloadedSize,
- totalSize
+ this.downloadProgress.set(modelId, {
+ modelId,
+ progress,
+ downloadedSize,
+ totalSize,
});
if (onProgress) {
onProgress(progress, downloadedSize, totalSize);
@@ -222,8 +224,8 @@ class ModelManager {
getDownloadUrl(provider, model) {
// Based on the provider type, construct the download URL
- if (provider.id === 'qwen') {
- return `https://huggingface.co/Qwen/Qwen2.5-${model.name.split(' ')[1]}-Instruct-GGUF/resolve/main/${model.fileName}`;
+ if (provider.id === "qwen") {
+ return `https://huggingface.co/Qwen/Qwen2.5-${model.name.split(" ")[1]}-Instruct-GGUF/resolve/main/${model.fileName}`;
}
// Add more providers as needed
throw new ModelError(`Unknown provider: ${provider.id}`, "UNKNOWN_PROVIDER");
@@ -235,67 +237,75 @@ class ModelManager {
let downloadedSize = 0;
let totalSize = 0;
- https.get(url, {
- headers: { 'User-Agent': 'OpenWhispr/1.0' },
- timeout: 30000
- }, (response) => {
- if (response.statusCode === 302 || response.statusCode === 301) {
- // Handle redirect
- file.close();
- fs.unlinkSync(destPath);
- return this.downloadFile(response.headers.location, destPath, onProgress)
- .then(resolve)
- .catch(reject);
- }
-
- if (response.statusCode !== 200) {
- file.close();
- fs.unlinkSync(destPath);
- reject(new ModelError(
- `Download failed with status ${response.statusCode}`,
- "DOWNLOAD_FAILED",
- { statusCode: response.statusCode }
- ));
- return;
- }
-
- totalSize = parseInt(response.headers['content-length'], 10);
-
- response.on('data', (chunk) => {
- downloadedSize += chunk.length;
- file.write(chunk);
-
- if (onProgress && totalSize > 0) {
- const progress = (downloadedSize / totalSize) * 100;
- onProgress(progress, downloadedSize, totalSize);
+ https
+ .get(
+ url,
+ {
+ headers: { "User-Agent": "OpenWhispr/1.0" },
+ timeout: 30000,
+ },
+ (response) => {
+ if (response.statusCode === 302 || response.statusCode === 301) {
+ // Handle redirect
+ file.close();
+ fs.unlinkSync(destPath);
+ return this.downloadFile(response.headers.location, destPath, onProgress)
+ .then(resolve)
+ .catch(reject);
+ }
+
+ if (response.statusCode !== 200) {
+ file.close();
+ fs.unlinkSync(destPath);
+ reject(
+ new ModelError(
+ `Download failed with status ${response.statusCode}`,
+ "DOWNLOAD_FAILED",
+ { statusCode: response.statusCode }
+ )
+ );
+ return;
+ }
+
+ totalSize = parseInt(response.headers["content-length"], 10);
+
+ response.on("data", (chunk) => {
+ downloadedSize += chunk.length;
+ file.write(chunk);
+
+ if (onProgress && totalSize > 0) {
+ const progress = (downloadedSize / totalSize) * 100;
+ onProgress(progress, downloadedSize, totalSize);
+ }
+ });
+
+ response.on("end", () => {
+ file.close();
+ resolve(destPath);
+ });
+
+ response.on("error", (error) => {
+ file.close();
+ fs.unlinkSync(destPath);
+ reject(
+ new ModelError(`Download error: ${error.message}`, "DOWNLOAD_ERROR", {
+ error: error.message,
+ })
+ );
+ });
}
- });
-
- response.on('end', () => {
+ )
+ .on("error", (error) => {
file.close();
- resolve(destPath);
- });
-
- response.on('error', (error) => {
- file.close();
- fs.unlinkSync(destPath);
- reject(new ModelError(
- `Download error: ${error.message}`,
- "DOWNLOAD_ERROR",
- { error: error.message }
- ));
+ if (fs.existsSync(destPath)) {
+ fs.unlinkSync(destPath);
+ }
+ reject(
+ new ModelError(`Network error: ${error.message}`, "NETWORK_ERROR", {
+ error: error.message,
+ })
+ );
});
- }).on('error', (error) => {
- file.close();
- if (fs.existsSync(destPath)) {
- fs.unlinkSync(destPath);
- }
- reject(new ModelError(
- `Network error: ${error.message}`,
- "NETWORK_ERROR",
- { error: error.message }
- ));
- });
});
}
@@ -306,7 +316,7 @@ class ModelManager {
}
const modelPath = path.join(this.modelsDir, modelInfo.model.fileName);
-
+
if (await this.checkFileExists(modelPath)) {
await fsPromises.unlink(modelPath);
}
@@ -317,7 +327,9 @@ class ModelManager {
if (fsPromises.rm) {
await fsPromises.rm(this.modelsDir, { recursive: true, force: true });
} else {
- const entries = await fsPromises.readdir(this.modelsDir, { withFileTypes: true }).catch(() => []);
+ const entries = await fsPromises
+ .readdir(this.modelsDir, { withFileTypes: true })
+ .catch(() => []);
for (const entry of entries) {
const fullPath = path.join(this.modelsDir, entry.name);
if (entry.isDirectory()) {
@@ -341,12 +353,9 @@ class ModelManager {
async ensureLlamaCpp() {
// Simplify - isInstalled already checks system installation
const llamaCppInstaller = require("./llamaCppInstaller").default;
-
- if (!await llamaCppInstaller.isInstalled()) {
- throw new ModelError(
- "llama.cpp is not installed",
- "LLAMACPP_NOT_INSTALLED"
- );
+
+ if (!(await llamaCppInstaller.isInstalled())) {
+ throw new ModelError("llama.cpp is not installed", "LLAMACPP_NOT_INSTALLED");
}
this.llamaCppPath = await llamaCppInstaller.getBinaryPath();
@@ -355,75 +364,87 @@ class ModelManager {
async runInference(modelId, prompt, options = {}) {
await this.ensureLlamaCpp();
-
+
const modelInfo = this.findModelById(modelId);
if (!modelInfo) {
throw new ModelNotFoundError(modelId);
}
const modelPath = path.join(this.modelsDir, modelInfo.model.fileName);
- if (!await this.checkFileExists(modelPath)) {
- throw new ModelError(
- `Model ${modelId} is not downloaded`,
- "MODEL_NOT_DOWNLOADED",
- { modelId }
- );
+ if (!(await this.checkFileExists(modelPath))) {
+ throw new ModelError(`Model ${modelId} is not downloaded`, "MODEL_NOT_DOWNLOADED", {
+ modelId,
+ });
}
// Format the prompt based on the provider
- const formattedPrompt = this.formatPrompt(modelInfo.provider, prompt, options.systemPrompt || "");
+ const formattedPrompt = this.formatPrompt(
+ modelInfo.provider,
+ prompt,
+ options.systemPrompt || ""
+ );
// Run inference with llama.cpp
return new Promise((resolve, reject) => {
const args = [
- "-m", modelPath,
- "-p", formattedPrompt,
- "-n", String(options.maxTokens || 512),
- "--temp", String(options.temperature || 0.7),
- "--top-k", String(options.topK || 40),
- "--top-p", String(options.topP || 0.9),
- "--repeat-penalty", String(options.repeatPenalty || 1.1),
- "-c", String(options.contextSize || modelInfo.model.contextLength),
- "-t", String(options.threads || 4),
- "--no-display-prompt"
+ "-m",
+ modelPath,
+ "-p",
+ formattedPrompt,
+ "-n",
+ String(options.maxTokens || 512),
+ "--temp",
+ String(options.temperature || 0.7),
+ "--top-k",
+ String(options.topK || 40),
+ "--top-p",
+ String(options.topP || 0.9),
+ "--repeat-penalty",
+ String(options.repeatPenalty || 1.1),
+ "-c",
+ String(options.contextSize || modelInfo.model.contextLength),
+ "-t",
+ String(options.threads || 4),
+ "--no-display-prompt",
];
const process = spawn(this.llamaCppPath, args);
let output = "";
let error = "";
- process.stdout.on('data', (data) => {
+ process.stdout.on("data", (data) => {
output += data.toString();
});
- process.stderr.on('data', (data) => {
+ process.stderr.on("data", (data) => {
error += data.toString();
});
- process.on('close', (code) => {
+ process.on("close", (code) => {
if (code !== 0) {
- reject(new ModelError(
- `Inference failed with code ${code}: ${error}`,
- "INFERENCE_FAILED",
- { code, error }
- ));
+ reject(
+ new ModelError(`Inference failed with code ${code}: ${error}`, "INFERENCE_FAILED", {
+ code,
+ error,
+ })
+ );
} else {
resolve(output.trim());
}
});
- process.on('error', (err) => {
- reject(new ModelError(
- `Failed to start inference: ${err.message}`,
- "INFERENCE_START_FAILED",
- { error: err.message }
- ));
+ process.on("error", (err) => {
+ reject(
+ new ModelError(`Failed to start inference: ${err.message}`, "INFERENCE_START_FAILED", {
+ error: err.message,
+ })
+ );
});
});
}
formatPrompt(provider, text, systemPrompt) {
- if (provider.id === 'qwen') {
+ if (provider.id === "qwen") {
return `<|im_start|>system\n${systemPrompt}<|im_end|>\n<|im_start|>user\n${text}<|im_end|>\n<|im_start|>assistant\n`;
}
// Add more providers as needed
@@ -434,5 +455,5 @@ class ModelManager {
module.exports = {
default: new ModelManager(),
ModelError,
- ModelNotFoundError
+ ModelNotFoundError,
};
diff --git a/src/helpers/pythonInstaller.js b/src/helpers/pythonInstaller.js
index 1d6fda568..fb644ac9a 100644
--- a/src/helpers/pythonInstaller.js
+++ b/src/helpers/pythonInstaller.js
@@ -12,49 +12,50 @@ class PythonInstaller {
async downloadFile(url, outputPath, progressCallback = null) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(outputPath);
-
- https.get(url, (response) => {
- if (response.statusCode !== 200) {
- reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
- return;
- }
-
- const totalSize = parseInt(response.headers['content-length'], 10);
- let downloadedSize = 0;
- response.on('data', (chunk) => {
- downloadedSize += chunk.length;
- if (progressCallback && totalSize) {
- progressCallback({
- downloaded: downloadedSize,
- total: totalSize,
- percentage: Math.round((downloadedSize / totalSize) * 100)
- });
+ https
+ .get(url, (response) => {
+ if (response.statusCode !== 200) {
+ reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
+ return;
}
- });
- response.pipe(file);
+ const totalSize = parseInt(response.headers["content-length"], 10);
+ let downloadedSize = 0;
- file.on('finish', () => {
- file.close();
- resolve();
- });
+ response.on("data", (chunk) => {
+ downloadedSize += chunk.length;
+ if (progressCallback && totalSize) {
+ progressCallback({
+ downloaded: downloadedSize,
+ total: totalSize,
+ percentage: Math.round((downloadedSize / totalSize) * 100),
+ });
+ }
+ });
+
+ response.pipe(file);
+
+ file.on("finish", () => {
+ file.close();
+ resolve();
+ });
- file.on('error', (error) => {
- fs.unlink(outputPath, () => {}); // Clean up on error
+ file.on("error", (error) => {
+ fs.unlink(outputPath, () => {}); // Clean up on error
+ reject(error);
+ });
+ })
+ .on("error", (error) => {
reject(error);
});
-
- }).on('error', (error) => {
- reject(error);
- });
});
}
async installPythonMacOS(progressCallback = null) {
- const platform = process.arch === 'arm64' ? 'macos11' : 'macosx10.9';
+ const platform = process.arch === "arm64" ? "macos11" : "macosx10.9";
const installerUrl = `https://www.python.org/ftp/python/${this.pythonVersion}/python-${this.pythonVersion}-${platform}.pkg`;
-
+
const tempDir = os.tmpdir();
const installerPath = path.join(tempDir, `python-${this.pythonVersion}.pkg`);
@@ -63,32 +64,31 @@ class PythonInstaller {
try {
await runCommand("brew", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
console.log("Installing Python via Homebrew...");
-
+
if (progressCallback) {
progressCallback({ stage: "Installing Python via Homebrew...", percentage: 25 });
}
-
+
await runCommand("brew", ["install", "[email protected]"], { timeout: TIMEOUTS.INSTALL });
-
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "homebrew" };
-
} catch (brewError) {
console.log("Homebrew not available, using official installer...");
-
+
if (progressCallback) {
progressCallback({ stage: "Downloading Python installer...", percentage: 10 });
}
-
+
// Download official Python installer
await this.downloadFile(installerUrl, installerPath, (progress) => {
if (progressCallback) {
- progressCallback({
- stage: `Downloading Python installer... ${progress.percentage}%`,
- percentage: 10 + (progress.percentage * 0.4) // 10-50%
+ progressCallback({
+ stage: `Downloading Python installer... ${progress.percentage}%`,
+ percentage: 10 + progress.percentage * 0.4, // 10-50%
});
}
});
@@ -98,18 +98,19 @@ class PythonInstaller {
}
// Install Python silently
- await runCommand("sudo", ["installer", "-pkg", installerPath, "-target", "/"], { timeout: TIMEOUTS.INSTALL });
-
+ await runCommand("sudo", ["installer", "-pkg", installerPath, "-target", "/"], {
+ timeout: TIMEOUTS.INSTALL,
+ });
+
// Clean up
fs.unlink(installerPath, () => {});
-
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "official_installer" };
}
-
} catch (error) {
// Clean up on error
if (fs.existsSync(installerPath)) {
@@ -122,7 +123,7 @@ class PythonInstaller {
async checkWindowsAdmin() {
try {
// Try to read a protected registry key to check admin rights
- await runCommand('reg', ['query', 'HKU\\S-1-5-19'], { timeout: TIMEOUTS.QUICK_CHECK });
+ await runCommand("reg", ["query", "HKU\\S-1-5-19"], { timeout: TIMEOUTS.QUICK_CHECK });
return true;
} catch (error) {
return false;
@@ -130,26 +131,26 @@ class PythonInstaller {
}
async installPythonWindows(progressCallback = null) {
- const arch = process.arch === 'ia32' ? '' : '-amd64';
+ const arch = process.arch === "ia32" ? "" : "-amd64";
const installerUrl = `https://www.python.org/ftp/python/${this.pythonVersion}/python-${this.pythonVersion}${arch}.exe`;
-
+
const tempDir = os.tmpdir();
const installerPath = path.join(tempDir, `python-${this.pythonVersion}.exe`);
try {
// Check for admin rights
const isAdmin = await this.checkWindowsAdmin();
-
+
if (progressCallback) {
progressCallback({ stage: "Downloading Python installer...", percentage: 10 });
}
-
+
// Download Python installer
await this.downloadFile(installerUrl, installerPath, (progress) => {
if (progressCallback) {
- progressCallback({
- stage: `Downloading Python installer... ${progress.percentage}%`,
- percentage: 10 + (progress.percentage * 0.4) // 10-50%
+ progressCallback({
+ stage: `Downloading Python installer... ${progress.percentage}%`,
+ percentage: 10 + progress.percentage * 0.4, // 10-50%
});
}
});
@@ -159,40 +160,41 @@ class PythonInstaller {
}
// Install Python with appropriate options based on admin rights
- const installArgs = isAdmin ? [
- "/quiet",
- "InstallAllUsers=1",
- "PrependPath=1",
- "Include_test=0",
- "Include_doc=0",
- "Include_dev=0",
- "Include_debug=0",
- "Include_launcher=1",
- "InstallLauncherAllUsers=1"
- ] : [
- "/quiet",
- "InstallAllUsers=0",
- "PrependPath=1",
- "Include_test=0",
- "Include_doc=0",
- "Include_dev=0",
- "Include_debug=0",
- "Include_launcher=1",
- "InstallLauncherAllUsers=0",
- "DefaultJustForMeTargetDir=%LOCALAPPDATA%\\Programs\\Python\\Python311"
- ];
+ const installArgs = isAdmin
+ ? [
+ "/quiet",
+ "InstallAllUsers=1",
+ "PrependPath=1",
+ "Include_test=0",
+ "Include_doc=0",
+ "Include_dev=0",
+ "Include_debug=0",
+ "Include_launcher=1",
+ "InstallLauncherAllUsers=1",
+ ]
+ : [
+ "/quiet",
+ "InstallAllUsers=0",
+ "PrependPath=1",
+ "Include_test=0",
+ "Include_doc=0",
+ "Include_dev=0",
+ "Include_debug=0",
+ "Include_launcher=1",
+ "InstallLauncherAllUsers=0",
+ "DefaultJustForMeTargetDir=%LOCALAPPDATA%\\Programs\\Python\\Python311",
+ ];
await runCommand(installerPath, installArgs, { timeout: TIMEOUTS.INSTALL });
-
+
// Clean up
fs.unlink(installerPath, () => {});
-
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "official_installer" };
-
} catch (error) {
// Clean up on error
if (fs.existsSync(installerPath)) {
@@ -207,78 +209,88 @@ class PythonInstaller {
if (progressCallback) {
progressCallback({ stage: "Detecting Linux distribution...", percentage: 10 });
}
-
+
// Detect package manager and install Python
try {
// Try apt (Debian/Ubuntu)
await runCommand("apt", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
-
+
if (progressCallback) {
progressCallback({ stage: "Installing Python via apt...", percentage: 30 });
}
-
+
await runCommand("sudo", ["apt", "update"], { timeout: TIMEOUTS.PIP_UPGRADE });
const preferredPackages = [
"python3.11",
"python3.11-pip",
"python3.11-dev",
- "python3.11-venv"
+ "python3.11-venv",
];
try {
- await runCommand("sudo", ["apt", "install", "-y", ...preferredPackages], { timeout: TIMEOUTS.INSTALL });
+ await runCommand("sudo", ["apt", "install", "-y", ...preferredPackages], {
+ timeout: TIMEOUTS.INSTALL,
+ });
} catch (installError) {
- const fallbackPackages = [
- "python3",
- "python3-pip",
- "python3-dev",
- "python3-venv"
- ];
- await runCommand("sudo", ["apt", "install", "-y", ...fallbackPackages], { timeout: TIMEOUTS.INSTALL });
+ const fallbackPackages = ["python3", "python3-pip", "python3-dev", "python3-venv"];
+ await runCommand("sudo", ["apt", "install", "-y", ...fallbackPackages], {
+ timeout: TIMEOUTS.INSTALL,
+ });
}
-
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "apt" };
-
} catch (aptError) {
try {
// Try yum (RHEL/CentOS/Fedora)
await runCommand("yum", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
-
+
if (progressCallback) {
progressCallback({ stage: "Installing Python via yum...", percentage: 30 });
}
-
+
// Note: python311-libs typically includes venv on RHEL/Fedora, but we add it explicitly for safety
- await runCommand("sudo", ["yum", "install", "-y", "python311", "python311-pip", "python311-devel", "python311-libs"], { timeout: TIMEOUTS.INSTALL });
-
+ await runCommand(
+ "sudo",
+ [
+ "yum",
+ "install",
+ "-y",
+ "python311",
+ "python311-pip",
+ "python311-devel",
+ "python311-libs",
+ ],
+ { timeout: TIMEOUTS.INSTALL }
+ );
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "yum" };
-
} catch (yumError) {
try {
// Try pacman (Arch Linux)
await runCommand("pacman", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
-
+
if (progressCallback) {
progressCallback({ stage: "Installing Python via pacman...", percentage: 30 });
}
-
- await runCommand("sudo", ["pacman", "-S", "--noconfirm", "python", "python-pip"], { timeout: TIMEOUTS.INSTALL });
-
+
+ await runCommand("sudo", ["pacman", "-S", "--noconfirm", "python", "python-pip"], {
+ timeout: TIMEOUTS.INSTALL,
+ });
+
if (progressCallback) {
progressCallback({ stage: "Python installation complete!", percentage: 100 });
}
-
+
return { success: true, method: "pacman" };
-
} catch (pacmanError) {
throw new Error("No supported package manager found (apt, yum, or pacman)");
}
@@ -297,17 +309,16 @@ class PythonInstaller {
}
switch (platform) {
- case 'darwin':
+ case "darwin":
return await this.installPythonMacOS(progressCallback);
- case 'win32':
+ case "win32":
return await this.installPythonWindows(progressCallback);
- case 'linux':
+ case "linux":
return await this.installPythonLinux(progressCallback);
default:
throw new Error(`Unsupported platform: ${platform}`);
}
}
-
}
module.exports = PythonInstaller;
diff --git a/src/helpers/tray.js b/src/helpers/tray.js
index 1ac4c2dcf..65befe036 100644
--- a/src/helpers/tray.js
+++ b/src/helpers/tray.js
@@ -37,7 +37,6 @@ class TrayManager {
this.createControlPanelCallback = callback;
}
-
attachControlPanelListeners(window) {
if (!window || this.attachedControlPanels.has(window)) {
return;
@@ -65,15 +64,11 @@ class TrayManager {
async showControlPanelFromTray() {
try {
if (this.windowManager) {
- this.controlPanelWindow =
- this.windowManager.controlPanelWindow || this.controlPanelWindow;
+ this.controlPanelWindow = this.windowManager.controlPanelWindow || this.controlPanelWindow;
}
this.attachControlPanelListeners(this.controlPanelWindow);
- if (
- this.controlPanelWindow &&
- !this.controlPanelWindow.isDestroyed()
- ) {
+ if (this.controlPanelWindow && !this.controlPanelWindow.isDestroyed()) {
if (process.platform === "win32") {
this.controlPanelWindow.setSkipTaskbar(false);
}
@@ -92,10 +87,7 @@ class TrayManager {
}
this.attachControlPanelListeners(this.controlPanelWindow);
- if (
- this.controlPanelWindow &&
- !this.controlPanelWindow.isDestroyed()
- ) {
+ if (this.controlPanelWindow && !this.controlPanelWindow.isDestroyed()) {
if (process.platform === "win32") {
this.controlPanelWindow.setSkipTaskbar(false);
}
@@ -142,9 +134,7 @@ class TrayManager {
if (platform === "darwin") {
if (isDevelopment) {
- candidatePaths.push(
- path.join(__dirname, "..", "assets", "[email protected]")
- );
+ candidatePaths.push(path.join(__dirname, "..", "assets", "[email protected]"));
} else {
candidatePaths.push(
path.join(process.resourcesPath, "src", "assets", "[email protected]"),
@@ -171,13 +161,7 @@ class TrayManager {
candidatePaths.push(
path.join(process.resourcesPath, "src", "assets", fileName),
path.join(process.resourcesPath, "assets", fileName),
- path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "src",
- "assets",
- fileName
- ),
+ path.join(process.resourcesPath, "app.asar.unpacked", "src", "assets", fileName),
path.join(__dirname, "..", "..", "src", "assets", fileName),
path.join(app.getAppPath(), "src", "assets", fileName)
);
@@ -225,11 +209,10 @@ class TrayManager {
console.warn("Canvas not available, creating minimal fallback icon");
// Create a minimal 16x16 black square PNG as fallback
const pngData = Buffer.from([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
- 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,
- 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x91, 0x68, 0x36, 0x00, 0x00, 0x00,
- 0x0c, 0x49, 0x44, 0x41, 0x54, 0x28, 0x53, 0x63, 0x08, 0x05, 0x00, 0x00,
- 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x49,
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
+ 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
+ 0x91, 0x68, 0x36, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x28, 0x53, 0x63, 0x08,
+ 0x05, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x49,
0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index fbb8a7861..174ef9e33 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -35,9 +35,7 @@ class WhisperManager {
isTomlResolverError(message = "") {
const normalized = this.sanitizeErrorMessage(message).toLowerCase();
- return (
- normalized.includes("pyproject.toml") || normalized.includes("tomlerror")
- );
+ return normalized.includes("pyproject.toml") || normalized.includes("tomlerror");
}
formatWhisperInstallError(message = "") {
@@ -248,11 +246,7 @@ class WhisperManager {
return path.join(__dirname, "..", "..", "whisper_bridge.py");
} else {
// In production, use the unpacked path
- return path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "whisper_bridge.py"
- );
+ return path.join(process.resourcesPath, "app.asar.unpacked", "whisper_bridge.py");
}
}
@@ -268,31 +262,27 @@ class WhisperManager {
}
async transcribeLocalWhisper(audioBlob, options = {}) {
- debugLogger.logWhisperPipeline('transcribeLocalWhisper - start', {
+ debugLogger.logWhisperPipeline("transcribeLocalWhisper - start", {
options,
audioBlobType: audioBlob?.constructor?.name,
- audioBlobSize: audioBlob?.byteLength || audioBlob?.size || 0
+ audioBlobSize: audioBlob?.byteLength || audioBlob?.size || 0,
});
-
+
// First check if FFmpeg is available
const ffmpegCheck = await this.checkFFmpegAvailability();
- debugLogger.logWhisperPipeline('FFmpeg availability check', ffmpegCheck);
-
+ debugLogger.logWhisperPipeline("FFmpeg availability check", ffmpegCheck);
+
if (!ffmpegCheck.available) {
- debugLogger.error('FFmpeg not available', ffmpegCheck);
- throw new Error(`FFmpeg not available: ${ffmpegCheck.error || 'Unknown error'}`);
+ debugLogger.error("FFmpeg not available", ffmpegCheck);
+ throw new Error(`FFmpeg not available: ${ffmpegCheck.error || "Unknown error"}`);
}
-
+
const tempAudioPath = await this.createTempAudioFile(audioBlob);
const model = options.model || "base";
const language = options.language || null;
try {
- const result = await this.runWhisperProcess(
- tempAudioPath,
- model,
- language
- );
+ const result = await this.runWhisperProcess(tempAudioPath, model, language);
return this.parseWhisperResult(result);
} finally {
await this.cleanupTempFile(tempAudioPath);
@@ -304,8 +294,8 @@ class WhisperManager {
const filename = `whisper_audio_${crypto.randomUUID()}.wav`;
const tempAudioPath = path.join(tempDir, filename);
- debugLogger.logAudioData('createTempAudioFile', audioBlob);
- debugLogger.log('Creating temp file at:', tempAudioPath);
+ debugLogger.logAudioData("createTempAudioFile", audioBlob);
+ debugLogger.log("Creating temp file at:", tempAudioPath);
let buffer;
if (audioBlob instanceof ArrayBuffer) {
@@ -317,29 +307,29 @@ class WhisperManager {
} else if (audioBlob && audioBlob.buffer) {
buffer = Buffer.from(audioBlob.buffer);
} else {
- debugLogger.error('Unsupported audio data type:', typeof audioBlob, audioBlob);
+ debugLogger.error("Unsupported audio data type:", typeof audioBlob, audioBlob);
throw new Error(`Unsupported audio data type: ${typeof audioBlob}`);
}
- debugLogger.log('Buffer created, size:', buffer.length);
+ debugLogger.log("Buffer created, size:", buffer.length);
// Validate buffer before writing
if (!buffer || buffer.length === 0) {
- debugLogger.error('Buffer is empty before writing');
+ debugLogger.error("Buffer is empty before writing");
throw new Error("Audio buffer is empty - no audio data received");
}
// Minimum viable audio file size (WAV header is 44 bytes minimum)
const MIN_AUDIO_SIZE = 44;
if (buffer.length < MIN_AUDIO_SIZE) {
- debugLogger.error('Buffer too small to be valid audio:', buffer.length, 'bytes');
+ debugLogger.error("Buffer too small to be valid audio:", buffer.length, "bytes");
throw new Error(`Audio data too small (${buffer.length} bytes) - recording may have failed`);
}
// Validate WAV header if present
const hasValidWavHeader = this.validateWavHeader(buffer);
if (!hasValidWavHeader) {
- debugLogger.log('No valid WAV header detected, buffer may need conversion');
+ debugLogger.log("No valid WAV header detected, buffer may need conversion");
// Don't throw error - FFmpeg can handle headerless audio data
}
@@ -352,17 +342,17 @@ class WhisperManager {
size: stats.size,
isFile: stats.isFile(),
permissions: stats.mode.toString(8),
- hasWavHeader: hasValidWavHeader
+ hasWavHeader: hasValidWavHeader,
};
- debugLogger.logWhisperPipeline('Temp audio file created', fileInfo);
+ debugLogger.logWhisperPipeline("Temp audio file created", fileInfo);
if (stats.size === 0) {
- debugLogger.error('Audio file is empty after writing');
+ debugLogger.error("Audio file is empty after writing");
throw new Error("Audio file is empty - file write failed");
}
if (stats.size < MIN_AUDIO_SIZE) {
- debugLogger.error('Audio file too small after writing:', stats.size, 'bytes');
+ debugLogger.error("Audio file too small after writing:", stats.size, "bytes");
throw new Error(`Audio file too small (${stats.size} bytes) - recording failed`);
}
@@ -376,27 +366,27 @@ class WhisperManager {
}
// Check RIFF header
- const riff = buffer.toString('ascii', 0, 4);
- if (riff !== 'RIFF') {
+ const riff = buffer.toString("ascii", 0, 4);
+ if (riff !== "RIFF") {
return false;
}
// Check WAVE format
- const wave = buffer.toString('ascii', 8, 12);
- if (wave !== 'WAVE') {
+ const wave = buffer.toString("ascii", 8, 12);
+ if (wave !== "WAVE") {
return false;
}
// Check fmt subchunk
- const fmt = buffer.toString('ascii', 12, 16);
- if (fmt !== 'fmt ') {
+ const fmt = buffer.toString("ascii", 12, 16);
+ if (fmt !== "fmt ") {
return false;
}
- debugLogger.log('Valid WAV header detected');
+ debugLogger.log("Valid WAV header detected");
return true;
} catch (error) {
- debugLogger.error('WAV header validation error:', error.message);
+ debugLogger.error("WAV header validation error:", error.message);
return false;
}
}
@@ -410,7 +400,7 @@ class WhisperManager {
try {
ffmpegPath = require("ffmpeg-static");
- debugLogger.logFFmpegDebug('Initial ffmpeg-static path', ffmpegPath);
+ debugLogger.logFFmpegDebug("Initial ffmpeg-static path", ffmpegPath);
// Normalize path separators for cross-platform compatibility
ffmpegPath = path.normalize(ffmpegPath);
@@ -426,34 +416,38 @@ class WhisperManager {
try {
fs.accessSync(ffmpegPath, fs.constants.X_OK);
} catch (e) {
- debugLogger.error('FFmpeg exists but is not executable:', e.message);
- throw new Error('FFmpeg not executable');
+ debugLogger.error("FFmpeg exists but is not executable:", e.message);
+ throw new Error("FFmpeg not executable");
}
}
- debugLogger.log('Found bundled FFmpeg at:', ffmpegPath);
+ debugLogger.log("Found bundled FFmpeg at:", ffmpegPath);
} else if (process.env.NODE_ENV !== "development") {
const possiblePaths = [
ffmpegPath.replace(/app\.asar([/\\])/, "app.asar.unpacked$1"),
ffmpegPath.replace(/app\.asar/g, "app.asar.unpacked"),
ffmpegPath.replace(/.*app\.asar/, path.join(__dirname, "..", "..", "app.asar.unpacked")),
- process.resourcesPath ? path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "node_modules",
- "ffmpeg-static",
- process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
- ) : null,
- process.resourcesPath ? path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "node_modules",
- "ffmpeg-static",
- "bin",
- process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
- ) : null,
+ process.resourcesPath
+ ? path.join(
+ process.resourcesPath,
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
+ )
+ : null,
+ process.resourcesPath
+ ? path.join(
+ process.resourcesPath,
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ "bin",
+ process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
+ )
+ : null,
].filter(Boolean);
- debugLogger.log('FFmpeg not found at primary path, checking alternatives');
+ debugLogger.log("FFmpeg not found at primary path, checking alternatives");
for (const possiblePath of possiblePaths) {
const normalizedPath = path.normalize(possiblePath);
@@ -469,17 +463,17 @@ class WhisperManager {
}
}
ffmpegPath = normalizedPath;
- debugLogger.log('FFmpeg found at:', normalizedPath);
+ debugLogger.log("FFmpeg found at:", normalizedPath);
break;
}
}
if (!ffmpegPath || !fs.existsSync(ffmpegPath)) {
- debugLogger.log('Bundled FFmpeg not found, trying system FFmpeg');
- throw new Error('Bundled FFmpeg not found');
+ debugLogger.log("Bundled FFmpeg not found, trying system FFmpeg");
+ throw new Error("Bundled FFmpeg not found");
}
} catch (bundledError) {
- debugLogger.log('Bundled FFmpeg error:', bundledError.message);
+ debugLogger.log("Bundled FFmpeg error:", bundledError.message);
// Try system FFmpeg with enhanced Windows support
const systemCandidates = await this.getSystemFfmpegCandidates();
@@ -487,7 +481,7 @@ class WhisperManager {
for (const candidate of systemCandidates) {
try {
await runCommand(candidate, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
- debugLogger.log('Using system FFmpeg:', candidate);
+ debugLogger.log("Using system FFmpeg:", candidate);
ffmpegPath = candidate;
break;
} catch (error) {
@@ -496,7 +490,7 @@ class WhisperManager {
}
if (!ffmpegPath) {
- debugLogger.error('No FFmpeg found (bundled or system)');
+ debugLogger.error("No FFmpeg found (bundled or system)");
return null;
}
}
@@ -561,16 +555,21 @@ class WhisperManager {
return new Promise(async (resolve, reject) => {
const ffmpegPath = await this.getFFmpegPath();
if (!ffmpegPath) {
- reject(new Error('FFmpeg not found. Please ensure FFmpeg is installed or bundled correctly.'));
+ reject(
+ new Error("FFmpeg not found. Please ensure FFmpeg is installed or bundled correctly.")
+ );
return;
}
let effectiveFfmpegPath = ffmpegPath;
- if (effectiveFfmpegPath.includes("app.asar") && !effectiveFfmpegPath.includes("app.asar.unpacked")) {
+ if (
+ effectiveFfmpegPath.includes("app.asar") &&
+ !effectiveFfmpegPath.includes("app.asar.unpacked")
+ ) {
const unpackedPath = effectiveFfmpegPath.replace("app.asar", "app.asar.unpacked");
if (fs.existsSync(unpackedPath)) {
effectiveFfmpegPath = unpackedPath;
- debugLogger.log('Using unpacked FFmpeg path:', unpackedPath);
+ debugLogger.log("Using unpacked FFmpeg path:", unpackedPath);
}
}
@@ -582,7 +581,7 @@ class WhisperManager {
FFMPEG_BINARY: absoluteFFmpegPath,
};
- debugLogger.logFFmpegDebug('Setting FFmpeg env vars', absoluteFFmpegPath);
+ debugLogger.logFFmpegDebug("Setting FFmpeg env vars", absoluteFFmpegPath);
// Add ffmpeg directory to PATH if we have a valid path
if (ffmpegPath) {
@@ -594,7 +593,7 @@ class WhisperManager {
enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;
}
}
-
+
// Add common system paths for macOS GUI launches
if (process.platform === "darwin") {
const commonPaths = [
@@ -604,15 +603,15 @@ class WhisperManager {
"/usr/bin",
"/bin",
"/usr/sbin",
- "/sbin"
+ "/sbin",
];
-
+
const currentPath = enhancedEnv.PATH || "";
- const pathsToAdd = commonPaths.filter(p => !currentPath.includes(p));
-
+ const pathsToAdd = commonPaths.filter((p) => !currentPath.includes(p));
+
if (pathsToAdd.length > 0) {
enhancedEnv.PATH = `${currentPath}:${pathsToAdd.join(":")}`;
- debugLogger.log('Added system paths for GUI launch');
+ debugLogger.log("Added system paths for GUI launch");
}
}
@@ -631,21 +630,21 @@ class WhisperManager {
// Set timeout for longer recordings
const timeout = setTimeout(() => {
if (!isResolved) {
- killProcess(whisperProcess, 'SIGTERM');
+ killProcess(whisperProcess, "SIGTERM");
reject(new Error("Whisper transcription timed out (20 minutes)"));
}
}, TIMEOUTS.TRANSCRIPTION);
whisperProcess.stdout.on("data", (data) => {
stdout += data.toString();
- debugLogger.logProcessOutput('Whisper', 'stdout', data);
+ debugLogger.logProcessOutput("Whisper", "stdout", data);
});
whisperProcess.stderr.on("data", (data) => {
const stderrText = data.toString();
stderr += stderrText;
- debugLogger.logProcessOutput('Whisper', 'stderr', data);
+ debugLogger.logProcessOutput("Whisper", "stderr", data);
});
whisperProcess.on("close", (code) => {
@@ -653,14 +652,14 @@ class WhisperManager {
isResolved = true;
clearTimeout(timeout);
- debugLogger.logWhisperPipeline('Process closed', {
+ debugLogger.logWhisperPipeline("Process closed", {
code,
stdoutLength: stdout.length,
- stderrLength: stderr.length
+ stderrLength: stderr.length,
});
if (code === 0) {
- debugLogger.log('Transcription successful');
+ debugLogger.log("Transcription successful");
resolve(stdout);
} else {
// Better error message for FFmpeg issues
@@ -671,8 +670,7 @@ class WhisperManager {
stderr.includes("No such file or directory") ||
stderr.includes("FFmpeg not found")
) {
- errorMessage +=
- "\n\nFFmpeg issue detected. Try restarting the app or reinstalling.";
+ errorMessage += "\n\nFFmpeg issue detected. Try restarting the app or reinstalling.";
}
reject(new Error(errorMessage));
@@ -706,7 +704,7 @@ class WhisperManager {
}
parseWhisperResult(stdout) {
- debugLogger.logWhisperPipeline('Parsing result', { stdoutLength: stdout.length });
+ debugLogger.logWhisperPipeline("Parsing result", { stdoutLength: stdout.length });
try {
// Clean stdout by removing any non-JSON content
const lines = stdout.split("\n").filter((line) => line.trim());
@@ -726,13 +724,13 @@ class WhisperManager {
}
const result = JSON.parse(jsonLine);
-
+
if (!result.text || result.text.trim().length === 0) {
return { success: false, message: "No audio detected" };
}
return { success: true, text: result.text.trim() };
} catch (parseError) {
- debugLogger.error('Failed to parse Whisper output');
+ debugLogger.error("Failed to parse Whisper output");
throw new Error(`Failed to parse Whisper output: ${parseError.message}`);
}
}
@@ -746,11 +744,7 @@ class WhisperManager {
}
async findPythonExecutable(options = {}) {
- const {
- allowVenv = true,
- allowBundled = true,
- allowOverride = true,
- } = options;
+ const { allowVenv = true, allowBundled = true, allowOverride = true } = options;
if (this.pythonCmd) {
const cachedSource = this.getPythonSource(this.pythonCmd);
@@ -846,7 +840,9 @@ class WhisperManager {
const version = await this.getPythonVersion(resolvedPath);
if (this.isPythonVersionSupported(version)) {
this.pythonCmd = resolvedPath;
- debugLogger.log(`Found Python: ${resolvedPath} (version ${version.major}.${version.minor})`);
+ debugLogger.log(
+ `Found Python: ${resolvedPath} (version ${version.major}.${version.minor})`
+ );
return resolvedPath;
}
} catch (error) {
@@ -866,14 +862,14 @@ class WhisperManager {
}
const candidates = [];
- debugLogger.logWindowsPythonSearch?.('Starting registry search', { method: 'registry' });
+ debugLogger.logWindowsPythonSearch?.("Starting registry search", { method: "registry" });
try {
// Query Windows Registry for Python installations
const registryKeys = [
- 'HKLM\\SOFTWARE\\Python\\PythonCore',
- 'HKCU\\SOFTWARE\\Python\\PythonCore',
- 'HKLM\\SOFTWARE\\Wow6432Node\\Python\\PythonCore',
+ "HKLM\\SOFTWARE\\Python\\PythonCore",
+ "HKCU\\SOFTWARE\\Python\\PythonCore",
+ "HKLM\\SOFTWARE\\Wow6432Node\\Python\\PythonCore",
];
for (const registryKey of registryKeys) {
@@ -881,8 +877,8 @@ class WhisperManager {
debugLogger.log(`Querying registry key: ${registryKey}`);
// List all Python versions in registry
- const { output } = await runCommand('reg', ['query', registryKey], {
- timeout: TIMEOUTS.QUICK_CHECK
+ const { output } = await runCommand("reg", ["query", registryKey], {
+ timeout: TIMEOUTS.QUICK_CHECK,
});
// Parse version folders (e.g., "3.11", "3.12")
@@ -891,20 +887,24 @@ class WhisperManager {
if (versionMatches) {
for (const match of versionMatches) {
- const version = match.replace('PythonCore\\', '');
+ const version = match.replace("PythonCore\\", "");
// Query InstallPath for this version
try {
const installPathKey = `${registryKey}\\${version}\\InstallPath`;
- const { output: pathOutput } = await runCommand('reg', ['query', installPathKey, '/ve'], {
- timeout: TIMEOUTS.QUICK_CHECK
- });
+ const { output: pathOutput } = await runCommand(
+ "reg",
+ ["query", installPathKey, "/ve"],
+ {
+ timeout: TIMEOUTS.QUICK_CHECK,
+ }
+ );
// Extract path from registry output
const pathMatch = pathOutput.match(/REG_SZ\s+(.+)/);
if (pathMatch && pathMatch[1]) {
const installPath = pathMatch[1].trim();
- const pythonExe = path.join(installPath, 'python.exe');
+ const pythonExe = path.join(installPath, "python.exe");
debugLogger.log(`Checking Python ${version} at: ${pythonExe}`);
@@ -925,12 +925,12 @@ class WhisperManager {
}
}
} catch (error) {
- debugLogger.log('Registry query failed:', error.message);
+ debugLogger.log("Registry query failed:", error.message);
}
- debugLogger.logWindowsPythonSearch?.('Registry search complete', {
+ debugLogger.logWindowsPythonSearch?.("Registry search complete", {
foundCount: candidates.length,
- candidates
+ candidates,
});
return candidates;
@@ -943,12 +943,12 @@ class WhisperManager {
try {
// Use 'where' command to find executable in PATH
- const { output } = await runCommand('where', [command], {
- timeout: TIMEOUTS.QUICK_CHECK
+ const { output } = await runCommand("where", [command], {
+ timeout: TIMEOUTS.QUICK_CHECK,
});
// 'where' returns multiple paths, take the first one
- const paths = output.trim().split('\n');
+ const paths = output.trim().split("\n");
if (paths.length > 0) {
const resolvedPath = paths[0].trim();
if (fs.existsSync(resolvedPath)) {
@@ -968,8 +968,7 @@ class WhisperManager {
const versionSuffixes = ["313", "312", "311", "310", "39", "38"];
const systemDrive = process.env.SystemDrive || "C:";
- const windowsDir =
- process.env.WINDIR || path.join(systemDrive, "Windows");
+ const windowsDir = process.env.WINDIR || path.join(systemDrive, "Windows");
candidates.push("py");
candidates.push("py.exe");
@@ -982,11 +981,7 @@ class WhisperManager {
const baseDirs = [];
if (process.env.LOCALAPPDATA) {
baseDirs.push(path.join(process.env.LOCALAPPDATA, "Programs", "Python"));
- const windowsApps = path.join(
- process.env.LOCALAPPDATA,
- "Microsoft",
- "WindowsApps"
- );
+ const windowsApps = path.join(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps");
candidates.push(path.join(windowsApps, "python.exe"));
candidates.push(path.join(windowsApps, "python3.exe"));
}
@@ -1026,7 +1021,7 @@ class WhisperManager {
if (!this.isPythonVersionSupported(version)) {
throw new Error(
`OPENWHISPR_PYTHON points to an invalid or unsupported Python. ` +
- `Ensure it exists and is Python 3.x, or unset the variable.`
+ `Ensure it exists and is Python 3.x, or unset the variable.`
);
}
if (progressCallback) {
@@ -1066,7 +1061,9 @@ class WhisperManager {
try {
const pythonPath = await this.findPythonExecutable();
const version = await this.getPythonVersion(pythonPath);
- const normalizedVersion = version ? parseFloat(`${version.major}.${version.minor}`) : undefined;
+ const normalizedVersion = version
+ ? parseFloat(`${version.major}.${version.minor}`)
+ : undefined;
return {
installed: !!version,
@@ -1082,15 +1079,13 @@ class WhisperManager {
async getPythonVersion(pythonPath) {
return new Promise((resolve) => {
// Use shell: false on Windows to ensure exact path is used
- const spawnOptions = process.platform === "win32"
- ? { windowsHide: true, shell: false }
- : {};
+ const spawnOptions = process.platform === "win32" ? { windowsHide: true, shell: false } : {};
const testProcess = spawn(pythonPath, ["--version"], spawnOptions);
let output = "";
- testProcess.stdout.on("data", (data) => output += data);
- testProcess.stderr.on("data", (data) => output += data);
+ testProcess.stdout.on("data", (data) => (output += data));
+ testProcess.stderr.on("data", (data) => (output += data));
testProcess.on("close", (code) => {
if (code === 0) {
@@ -1123,10 +1118,7 @@ class WhisperManager {
const pythonCmd = await this.findPythonExecutable();
const result = await new Promise((resolve) => {
- const checkProcess = spawn(pythonCmd, [
- "-c",
- 'import whisper; print("OK")',
- ]);
+ const checkProcess = spawn(pythonCmd, ["-c", 'import whisper; print("OK")']);
let output = "";
checkProcess.stdout.on("data", (data) => {
@@ -1160,7 +1152,7 @@ class WhisperManager {
}
async checkFFmpegAvailability() {
- debugLogger.logWhisperPipeline('checkFFmpegAvailability - start', {});
+ debugLogger.logWhisperPipeline("checkFFmpegAvailability - start", {});
try {
const now = Date.now();
@@ -1176,10 +1168,10 @@ class WhisperManager {
const whisperScriptPath = this.getWhisperScriptPath();
const ffmpegPath = await this.getFFmpegPath();
if (!ffmpegPath) {
- debugLogger.log('FFmpeg not found by resolver');
+ debugLogger.log("FFmpeg not found by resolver");
const result = {
available: false,
- error: "FFmpeg not found"
+ error: "FFmpeg not found",
};
this.ffmpegAvailabilityCache = {
result,
@@ -1188,22 +1180,18 @@ class WhisperManager {
return result;
}
- debugLogger.log('FFmpeg resolved for availability check:', ffmpegPath);
+ debugLogger.log("FFmpeg resolved for availability check:", ffmpegPath);
const result = await new Promise((resolve) => {
const env = {
...process.env,
FFMPEG_PATH: ffmpegPath || "",
FFMPEG_EXECUTABLE: ffmpegPath || "",
- FFMPEG_BINARY: ffmpegPath || ""
+ FFMPEG_BINARY: ffmpegPath || "",
};
- const checkProcess = spawn(pythonCmd, [
- whisperScriptPath,
- "--mode",
- "check-ffmpeg",
- ], {
- env: env
+ const checkProcess = spawn(pythonCmd, [whisperScriptPath, "--mode", "check-ffmpeg"], {
+ env: env,
});
let output = "";
@@ -1218,26 +1206,26 @@ class WhisperManager {
});
checkProcess.on("close", (code) => {
- debugLogger.logWhisperPipeline('FFmpeg check process closed', {
+ debugLogger.logWhisperPipeline("FFmpeg check process closed", {
code,
outputLength: output.length,
- stderrLength: stderr.length
+ stderrLength: stderr.length,
});
-
+
if (code === 0) {
try {
const result = JSON.parse(output);
- debugLogger.log('FFmpeg check result:', result);
+ debugLogger.log("FFmpeg check result:", result);
resolve(result);
} catch (parseError) {
- debugLogger.error('Failed to parse FFmpeg check result:', parseError);
+ debugLogger.error("Failed to parse FFmpeg check result:", parseError);
resolve({
available: false,
error: "Failed to parse FFmpeg check result",
});
}
} else {
- debugLogger.error('FFmpeg check failed with code:', code, 'stderr:', stderr);
+ debugLogger.error("FFmpeg check failed with code:", code, "stderr:", stderr);
resolve({
available: false,
error: stderr || "FFmpeg check failed",
@@ -1266,11 +1254,9 @@ class WhisperManager {
}
upgradePip(pythonCmd) {
- return runCommand(
- pythonCmd,
- ["-m", "pip", "install", "--upgrade", "pip"],
- { timeout: TIMEOUTS.PIP_UPGRADE }
- );
+ return runCommand(pythonCmd, ["-m", "pip", "install", "--upgrade", "pip"], {
+ timeout: TIMEOUTS.PIP_UPGRADE,
+ });
}
async installWhisper() {
@@ -1283,7 +1269,7 @@ class WhisperManager {
if (!this.isPythonVersionSupported(version)) {
throw new Error(
`OPENWHISPR_PYTHON points to an invalid or unsupported Python: ${overridePath}. ` +
- `Ensure it exists and is Python 3.x, or unset the variable to use the managed environment.`
+ `Ensure it exists and is Python 3.x, or unset the variable to use the managed environment.`
);
}
pythonCmd = overridePath;
@@ -1310,7 +1296,9 @@ class WhisperManager {
};
try {
- const result = await runCommand(pythonCmd, buildInstallArgs(), { timeout: TIMEOUTS.DOWNLOAD });
+ const result = await runCommand(pythonCmd, buildInstallArgs(), {
+ timeout: TIMEOUTS.DOWNLOAD,
+ });
this.whisperInstalled = null;
return result;
} catch (error) {
@@ -1318,7 +1306,9 @@ class WhisperManager {
if (this.isTomlResolverError(cleanMessage)) {
try {
- const result = await runCommand(pythonCmd, buildInstallArgs({ legacy: true }), { timeout: TIMEOUTS.DOWNLOAD });
+ const result = await runCommand(pythonCmd, buildInstallArgs({ legacy: true }), {
+ timeout: TIMEOUTS.DOWNLOAD,
+ });
this.whisperInstalled = null;
return result;
} catch (legacyError) {
@@ -1336,13 +1326,7 @@ class WhisperManager {
const pythonCmd = await this.findPythonExecutable();
const whisperScriptPath = this.getWhisperScriptPath();
- const args = [
- whisperScriptPath,
- "--mode",
- "download",
- "--model",
- modelName,
- ];
+ const args = [whisperScriptPath, "--mode", "download", "--model", modelName];
return new Promise((resolve, reject) => {
const downloadProcess = spawn(pythonCmd, args);
@@ -1381,10 +1365,10 @@ class WhisperManager {
});
const timeout = setTimeout(() => {
- killProcess(downloadProcess, 'SIGTERM');
+ killProcess(downloadProcess, "SIGTERM");
setTimeout(() => {
if (!downloadProcess.killed) {
- killProcess(downloadProcess, 'SIGKILL');
+ killProcess(downloadProcess, "SIGKILL");
}
}, 5000);
reject(new Error("Model download timed out (10 minutes)"));
@@ -1400,11 +1384,7 @@ class WhisperManager {
resolve(result);
} catch (parseError) {
console.error("Failed to parse download result:", parseError);
- reject(
- new Error(
- `Failed to parse download result: ${parseError.message}`
- )
- );
+ reject(new Error(`Failed to parse download result: ${parseError.message}`));
}
} else {
// Handle cancellation cases (SIGTERM, SIGKILL, or null exit codes)
@@ -1433,13 +1413,10 @@ class WhisperManager {
async cancelDownload() {
if (this.currentDownloadProcess) {
try {
- killProcess(this.currentDownloadProcess, 'SIGTERM');
+ killProcess(this.currentDownloadProcess, "SIGTERM");
setTimeout(() => {
- if (
- this.currentDownloadProcess &&
- !this.currentDownloadProcess.killed
- ) {
- killProcess(this.currentDownloadProcess, 'SIGKILL');
+ if (this.currentDownloadProcess && !this.currentDownloadProcess.killed) {
+ killProcess(this.currentDownloadProcess, "SIGKILL");
}
}, 3000);
return { success: true, message: "Download cancelled" };
@@ -1502,17 +1479,11 @@ class WhisperManager {
}
async listWhisperModels() {
- return this.runWhisperBridgeCommand(
- ["--mode", "list"],
- "Model list"
- );
+ return this.runWhisperBridgeCommand(["--mode", "list"], "Model list");
}
async deleteWhisperModel(modelName) {
- return this.runWhisperBridgeCommand(
- ["--mode", "delete", "--model", modelName],
- "Model delete"
- );
+ return this.runWhisperBridgeCommand(["--mode", "delete", "--model", modelName], "Model delete");
}
}
diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.js
index daa52e51e..5ecce805a 100644
--- a/src/helpers/windowConfig.js
+++ b/src/helpers/windowConfig.js
@@ -15,16 +15,16 @@ const MAIN_WINDOW_CONFIG = {
frame: false,
alwaysOnTop: true,
resizable: false,
- transparent: process.platform !== 'win32',
- ...(process.platform === 'win32' ? { backgroundColor: '#1a1a1a' } : {}),
+ transparent: process.platform !== "win32",
+ ...(process.platform === "win32" ? { backgroundColor: "#1a1a1a" } : {}),
show: false, // Start hidden, show after setup
skipTaskbar: false, // Keep visible in Dock/taskbar so app stays discoverable
focusable: true,
- visibleOnAllWorkspaces: process.platform !== 'win32',
+ visibleOnAllWorkspaces: process.platform !== "win32",
fullScreenable: false,
hasShadow: false, // Remove shadow for cleaner look
acceptsFirstMouse: true, // Accept clicks even when not focused
- type: process.platform === 'darwin' ? 'panel' : 'normal', // Panel on macOS preserves floating behavior
+ type: process.platform === "darwin" ? "panel" : "normal", // Panel on macOS preserves floating behavior
};
// Control panel window configuration
@@ -44,14 +44,16 @@ const CONTROL_PANEL_CONFIG = {
resizable: true,
show: false,
// macOS-specific options
- ...(process.platform === 'darwin' ? {
- titleBarStyle: "hiddenInset",
- trafficLightPosition: { x: 20, y: 20 },
- frame: false,
- } : {
- // Windows/Linux: use standard frame for reliability
- frame: true,
- }),
+ ...(process.platform === "darwin"
+ ? {
+ titleBarStyle: "hiddenInset",
+ trafficLightPosition: { x: 20, y: 20 },
+ frame: false,
+ }
+ : {
+ // Windows/Linux: use standard frame for reliability
+ frame: true,
+ }),
transparent: false,
backgroundColor: "#ffffff",
minimizable: true,
@@ -61,7 +63,7 @@ const CONTROL_PANEL_CONFIG = {
skipTaskbar: false, // Ensure control panel stays in taskbar
alwaysOnTop: false, // Control panel should not be always on top
visibleOnAllWorkspaces: false, // Control panel should stay in its workspace
- type: 'normal', // Ensure it's a normal window, not a panel
+ type: "normal", // Ensure it's a normal window, not a panel
};
// Window positioning utilities
@@ -69,20 +71,14 @@ class WindowPositionUtil {
static getMainWindowPosition(display) {
const { width, height } = MAIN_WINDOW_CONFIG;
const MARGIN = 20;
- const x = Math.max(
- 0,
- display.bounds.x + display.workArea.width - width - MARGIN
- );
+ const x = Math.max(0, display.bounds.x + display.workArea.width - width - MARGIN);
const workArea = display.workArea || display.bounds;
- const y = Math.max(
- 0,
- workArea.y + workArea.height - height - MARGIN
- );
+ const y = Math.max(0, workArea.y + workArea.height - height - MARGIN);
return { x, y, width, height };
}
static setupAlwaysOnTop(window) {
- if (process.platform === 'darwin') {
+ if (process.platform === "darwin") {
// macOS: Use panel level for proper floating behavior
// This ensures the window stays on top across spaces and fullscreen apps
window.setAlwaysOnTop(true, "floating", 1);
@@ -91,24 +87,24 @@ class WindowPositionUtil {
skipTransformProcessType: true, // Keep Dock/Command-Tab behaviour
});
window.setFullScreenable(false);
-
+
// Ensure window level is maintained
if (window.isVisible()) {
window.setAlwaysOnTop(true, "floating", 1);
}
- } else if (process.platform === 'win32') {
+ } else if (process.platform === "win32") {
window.setAlwaysOnTop(true, "pop-up-menu");
} else {
// Linux and other platforms
window.setAlwaysOnTop(true, "screen-saver");
}
-
+
// Bring window to front if visible
if (window.isVisible()) {
window.moveTop();
}
}
-
+
static setupControlPanel(window) {
// Control panel should behave like a normal application window
// This is only called once during window creation
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index 9e748617c..c3cf5c5c8 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -3,11 +3,7 @@ const HotkeyManager = require("./hotkeyManager");
const DragManager = require("./dragManager");
const MenuManager = require("./menuManager");
const DevServerManager = require("./devServerManager");
-const {
- MAIN_WINDOW_CONFIG,
- CONTROL_PANEL_CONFIG,
- WindowPositionUtil,
-} = require("./windowConfig");
+const { MAIN_WINDOW_CONFIG, CONTROL_PANEL_CONFIG, WindowPositionUtil } = require("./windowConfig");
class WindowManager {
constructor() {
@@ -62,16 +58,8 @@ class WindowManager {
if (!isMainFrame) {
return;
}
- console.error(
- "Failed to load main window:",
- errorCode,
- errorDescription,
- validatedURL
- );
- if (
- process.env.NODE_ENV === "development" &&
- validatedURL.includes("localhost:5174")
- ) {
+ console.error("Failed to load main window:", errorCode, errorDescription, validatedURL);
+ if (process.env.NODE_ENV === "development" && validatedURL.includes("localhost:5174")) {
// Retry connection to dev server
setTimeout(async () => {
const isReady = await DevServerManager.waitForDevServer();
@@ -81,23 +69,15 @@ class WindowManager {
}
}, 2000);
} else {
- this.showLoadFailureDialog(
- "Dictation panel",
- errorCode,
- errorDescription,
- validatedURL
- );
+ this.showLoadFailureDialog("Dictation panel", errorCode, errorDescription, validatedURL);
}
}
);
- this.mainWindow.webContents.on(
- "did-finish-load",
- () => {
- this.mainWindow.setTitle("Voice Recorder");
- this.enforceMainWindowOnTop();
- }
- );
+ this.mainWindow.webContents.on("did-finish-load", () => {
+ this.mainWindow.setTitle("Voice Recorder");
+ this.enforceMainWindowOnTop();
+ });
}
setMainWindowInteractivity(shouldCapture) {
@@ -174,9 +154,7 @@ class WindowManager {
return;
}
if (!this.controlPanelWindow.isVisible()) {
- console.warn(
- "Control panel did not become visible in time; forcing show"
- );
+ console.warn("Control panel did not become visible in time; forcing show");
this.controlPanelWindow.show();
this.controlPanelWindow.focus();
}
@@ -232,19 +210,9 @@ class WindowManager {
return;
}
clearVisibilityTimer();
- console.error(
- "Failed to load control panel:",
- errorCode,
- errorDescription,
- validatedURL
- );
+ console.error("Failed to load control panel:", errorCode, errorDescription, validatedURL);
if (process.env.NODE_ENV !== "development") {
- this.showLoadFailureDialog(
- "Control panel",
- errorCode,
- errorDescription,
- validatedURL
- );
+ this.showLoadFailureDialog("Control panel", errorCode, errorDescription, validatedURL);
}
if (!this.controlPanelWindow.isVisible()) {
this.controlPanelWindow.show();
@@ -262,9 +230,7 @@ class WindowManager {
if (process.env.NODE_ENV === "development") {
const isReady = await DevServerManager.waitForDevServer();
if (!isReady) {
- console.error(
- "Dev server not ready for control panel, loading anyway..."
- );
+ console.error("Dev server not ready for control panel, loading anyway...");
}
}
this.controlPanelWindow.loadURL(appUrl);
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 66748ec98..1d673c0b3 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -36,10 +36,7 @@ export const useAudioRecording = (toast, options = {}) => {
audioManagerRef.current.saveTranscription(result.text);
// Show success notification if local fallback was used
- if (
- result.source === "openai" &&
- localStorage.getItem("useLocalWhisper") === "true"
- ) {
+ if (result.source === "openai" && localStorage.getItem("useLocalWhisper") === "true") {
toast({
title: "Fallback Mode",
description: "Local Whisper failed. Used OpenAI API instead.",
@@ -55,11 +52,7 @@ export const useAudioRecording = (toast, options = {}) => {
const handleToggle = () => {
const currentState = audioManagerRef.current.getState();
- if (
- !recording &&
- !currentState.isRecording &&
- !currentState.isProcessing
- ) {
+ if (!recording && !currentState.isRecording && !currentState.isProcessing) {
audioManagerRef.current.startRecording();
recording = true;
} else if (currentState.isRecording) {
@@ -77,15 +70,12 @@ export const useAudioRecording = (toast, options = {}) => {
const handleNoAudioDetected = () => {
toast({
title: "No Audio Detected",
- description:
- "The recording contained no detectable audio. Please try again.",
+ description: "The recording contained no detectable audio. Please try again.",
variant: "default",
});
};
- const disposeNoAudio = window.electronAPI.onNoAudioDetected?.(
- handleNoAudioDetected
- );
+ const disposeNoAudio = window.electronAPI.onNoAudioDetected?.(handleNoAudioDetected);
// Cleanup
return () => {
diff --git a/src/hooks/useClipboard.ts b/src/hooks/useClipboard.ts
index 9827f7cd5..b399f2d1c 100644
--- a/src/hooks/useClipboard.ts
+++ b/src/hooks/useClipboard.ts
@@ -2,9 +2,7 @@ import { useCallback } from "react";
export interface UseClipboardReturn {
pasteFromClipboard: (setter: (value: string) => void) => Promise<void>;
- pasteFromClipboardWithFallback: (
- setter: (value: string) => void
- ) => Promise<void>;
+ pasteFromClipboardWithFallback: (setter: (value: string) => void) => Promise<void>;
}
export interface UseClipboardProps {
@@ -14,22 +12,19 @@ export interface UseClipboardProps {
export const useClipboard = (
showAlertDialog?: UseClipboardProps["showAlertDialog"]
): UseClipboardReturn => {
- const pasteFromClipboard = useCallback(
- async (setter: (value: string) => void) => {
- try {
- const text = await window.electronAPI.readClipboard();
- if (text && text.trim()) {
- setter(text.trim());
- } else {
- throw new Error("Empty clipboard");
- }
- } catch (err) {
- console.error("Clipboard read failed:", err);
- throw err;
+ const pasteFromClipboard = useCallback(async (setter: (value: string) => void) => {
+ try {
+ const text = await window.electronAPI.readClipboard();
+ if (text && text.trim()) {
+ setter(text.trim());
+ } else {
+ throw new Error("Empty clipboard");
}
- },
- []
- );
+ } catch (err) {
+ console.error("Clipboard read failed:", err);
+ throw err;
+ }
+ }, []);
const pasteFromClipboardWithFallback = useCallback(
async (setter: (value: string) => void) => {
@@ -58,13 +53,10 @@ export const useClipboard = (
if (showAlertDialog) {
showAlertDialog({
title: "Clipboard Paste Failed",
- description:
- "Could not paste from clipboard. Please try typing or using Cmd+V/Ctrl+V.",
+ description: "Could not paste from clipboard. Please try typing or using Cmd+V/Ctrl+V.",
});
} else {
- alert(
- "Could not paste from clipboard. Please try typing or using Cmd+V/Ctrl+V."
- );
+ alert("Could not paste from clipboard. Please try typing or using Cmd+V/Ctrl+V.");
}
},
[showAlertDialog]
diff --git a/src/hooks/useDialogs.ts b/src/hooks/useDialogs.ts
index 8a72667ff..f9d4a2ddf 100644
--- a/src/hooks/useDialogs.ts
+++ b/src/hooks/useDialogs.ts
@@ -32,19 +32,13 @@ export function useDialogs() {
const [confirmDialog, setConfirmDialog] = useState<ConfirmDialogState>(defaultConfirmDialog);
const [alertDialog, setAlertDialog] = useState<AlertDialogState>(defaultAlertDialog);
- const showConfirmDialog = useCallback(
- (options: Omit<ConfirmDialogState, "open">) => {
- setConfirmDialog({ ...options, open: true });
- },
- []
- );
+ const showConfirmDialog = useCallback((options: Omit<ConfirmDialogState, "open">) => {
+ setConfirmDialog({ ...options, open: true });
+ }, []);
- const showAlertDialog = useCallback(
- (options: Omit<AlertDialogState, "open">) => {
- setAlertDialog({ ...options, open: true });
- },
- []
- );
+ const showAlertDialog = useCallback((options: Omit<AlertDialogState, "open">) => {
+ setAlertDialog({ ...options, open: true });
+ }, []);
const hideConfirmDialog = useCallback(() => {
setConfirmDialog(defaultConfirmDialog);
diff --git a/src/hooks/useLocalModels.ts b/src/hooks/useLocalModels.ts
index 13954b742..8863eb74c 100644
--- a/src/hooks/useLocalModels.ts
+++ b/src/hooks/useLocalModels.ts
@@ -40,41 +40,48 @@ export function useLocalModels() {
// Set up progress listener
const handleProgress = (_event: any, data: DownloadProgress) => {
- setProgressMap(prev => new Map(prev).set(data.modelId, data));
+ setProgressMap((prev) => new Map(prev).set(data.modelId, data));
};
- const disposeProgress = window.electronAPI.onModelDownloadProgress(
- handleProgress
- );
+ const disposeProgress = window.electronAPI.onModelDownloadProgress(handleProgress);
return () => {
disposeProgress?.();
};
}, [loadModels]);
- const downloadModel = useCallback(async (modelId: string) => {
- try {
- await window.electronAPI.modelDownload(modelId);
- await loadModels();
- } catch (err) {
- setError(`Failed to download model: ${(err as Error).message}`);
- throw err;
- }
- }, [loadModels]);
+ const downloadModel = useCallback(
+ async (modelId: string) => {
+ try {
+ await window.electronAPI.modelDownload(modelId);
+ await loadModels();
+ } catch (err) {
+ setError(`Failed to download model: ${(err as Error).message}`);
+ throw err;
+ }
+ },
+ [loadModels]
+ );
- const deleteModel = useCallback(async (modelId: string) => {
- try {
- await window.electronAPI.modelDelete(modelId);
- await loadModels();
- } catch (err) {
- setError(`Failed to delete model: ${(err as Error).message}`);
- throw err;
- }
- }, [loadModels]);
+ const deleteModel = useCallback(
+ async (modelId: string) => {
+ try {
+ await window.electronAPI.modelDelete(modelId);
+ await loadModels();
+ } catch (err) {
+ setError(`Failed to delete model: ${(err as Error).message}`);
+ throw err;
+ }
+ },
+ [loadModels]
+ );
- const getModelProgress = useCallback((modelId: string) => {
- return progressMap.get(modelId);
- }, [progressMap]);
+ const getModelProgress = useCallback(
+ (modelId: string) => {
+ return progressMap.get(modelId);
+ },
+ [progressMap]
+ );
const checkRuntimeAvailable = useCallback(async () => {
try {
@@ -85,14 +92,17 @@ export function useLocalModels() {
}
}, []);
- const modelsByProvider = models.reduce((acc, model) => {
- const providerId = model.id.split('-')[0] || 'other';
- if (!acc[providerId]) {
- acc[providerId] = [];
- }
- acc[providerId].push(model);
- return acc;
- }, {} as Record<string, ModelWithStatus[]>);
+ const modelsByProvider = models.reduce(
+ (acc, model) => {
+ const providerId = model.id.split("-")[0] || "other";
+ if (!acc[providerId]) {
+ acc[providerId] = [];
+ }
+ acc[providerId].push(model);
+ return acc;
+ },
+ {} as Record<string, ModelWithStatus[]>
+ );
return {
models,
diff --git a/src/hooks/usePermissions.ts b/src/hooks/usePermissions.ts
index 567c611a7..60c87f78c 100644
--- a/src/hooks/usePermissions.ts
+++ b/src/hooks/usePermissions.ts
@@ -78,11 +78,8 @@ export const usePermissions = (
showAlertDialog?: UsePermissionsProps["showAlertDialog"]
): UsePermissionsReturn => {
const [micPermissionGranted, setMicPermissionGranted] = useState(false);
- const [micPermissionError, setMicPermissionError] = useState<string | null>(
- null
- );
- const [accessibilityPermissionGranted, setAccessibilityPermissionGranted] =
- useState(false);
+ const [micPermissionError, setMicPermissionError] = useState<string | null>(null);
+ const [accessibilityPermissionGranted, setAccessibilityPermissionGranted] = useState(false);
const openMicPrivacySettings = useCallback(async () => {
try {
@@ -101,10 +98,7 @@ export const usePermissions = (
}, []);
const requestMicPermission = useCallback(async () => {
- if (
- !navigator?.mediaDevices ||
- typeof navigator.mediaDevices.getUserMedia !== "function"
- ) {
+ if (!navigator?.mediaDevices || typeof navigator.mediaDevices.getUserMedia !== "function") {
const message =
"Microphone APIs are unavailable in this environment. Please restart the app.";
setMicPermissionError(message);
@@ -165,9 +159,7 @@ export const usePermissions = (
"Please grant accessibility permissions in System Settings to enable automatic text pasting.",
});
} else {
- alert(
- "❌ Accessibility permissions needed! Please grant them in System Settings."
- );
+ alert("❌ Accessibility permissions needed! Please grant them in System Settings.");
}
}
}, [showAlertDialog]);
diff --git a/src/hooks/usePython.ts b/src/hooks/usePython.ts
index f693087b4..3b5e5e0b7 100644
--- a/src/hooks/usePython.ts
+++ b/src/hooks/usePython.ts
@@ -16,22 +16,22 @@ interface ShowAlertDialog {
}
const ERROR_MESSAGES: Record<string, string> = {
- 'Permission denied': 'Please run the application as administrator and try again.',
- 'access is denied': 'Please run the application as administrator and try again.',
- 'Network': 'Please check your internet connection and try again.',
- 'No supported package manager': 'Please install Python manually from python.org',
- 'not found in PATH': 'Python installed but not found in PATH. Please restart the application.',
+ "Permission denied": "Please run the application as administrator and try again.",
+ "access is denied": "Please run the application as administrator and try again.",
+ Network: "Please check your internet connection and try again.",
+ "No supported package manager": "Please install Python manually from python.org",
+ "not found in PATH": "Python installed but not found in PATH. Please restart the application.",
};
function getPythonInstallErrorMessage(error: Error): string {
- const errorMessage = error.message || '';
-
+ const errorMessage = error.message || "";
+
for (const [key, message] of Object.entries(ERROR_MESSAGES)) {
if (errorMessage.includes(key)) {
return message;
}
}
-
+
return `Python installation failed: ${errorMessage}`;
}
@@ -47,16 +47,16 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
if (isChecking) {
return pythonInfo || { installed: false };
}
-
+
try {
setIsChecking(true);
-
+
if (!window.electronAPI) {
return { installed: false };
}
-
+
const result = await window.electronAPI.checkPythonInstallation();
-
+
if (result) {
setPythonInstalled(result.installed);
setPythonInfo(result);
@@ -73,7 +73,6 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
}, [isChecking, pythonInfo]);
const installPython = useCallback(async () => {
-
if (!window.electronAPI) {
showAlertDialog({
title: "Installation Error",
@@ -81,10 +80,10 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
});
return;
}
-
+
let progressListener: ((event: any, data: PythonInstallProgress) => void) | null = null;
let disposeProgress: (() => void) | void;
-
+
try {
setInstallingPython(true);
setInstallProgress("Starting Python installation...");
@@ -99,16 +98,16 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
if (window.electronAPI.onPythonInstallProgress) {
disposeProgress = window.electronAPI.onPythonInstallProgress(progressListener);
}
-
+
const result = await window.electronAPI.installPython();
if (result?.success) {
setPythonInstalled(true);
setInstallProgress("Python installed successfully!");
-
+
// Re-check installation to get updated info
await checkPythonInstallation();
-
+
showAlertDialog({
title: "Python Installed",
description: `Python has been installed successfully using ${result.method}!`,
@@ -118,12 +117,12 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
return result;
} catch (error: any) {
const errorMessage = getPythonInstallErrorMessage(error);
-
+
showAlertDialog({
title: "Installation Failed",
description: errorMessage,
});
-
+
throw error;
} finally {
setInstallingPython(false);
@@ -138,7 +137,7 @@ export function usePython(showAlertDialog: ShowAlertDialog) {
const timer = setTimeout(() => {
checkPythonInstallation();
}, 100); // Small delay to ensure preload script is ready
-
+
return () => clearTimeout(timer);
}, [checkPythonInstallation]);
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 078e7bffd..3525034db 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -32,23 +32,15 @@ export interface ApiKeySettings {
}
export function useSettings() {
- const [useLocalWhisper, setUseLocalWhisper] = useLocalStorage(
- "useLocalWhisper",
- false,
- {
- serialize: String,
- deserialize: (value) => value === "true",
- }
- );
+ const [useLocalWhisper, setUseLocalWhisper] = useLocalStorage("useLocalWhisper", false, {
+ serialize: String,
+ deserialize: (value) => value === "true",
+ });
- const [whisperModel, setWhisperModel] = useLocalStorage(
- "whisperModel",
- "base",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [whisperModel, setWhisperModel] = useLocalStorage("whisperModel", "base", {
+ serialize: String,
+ deserialize: String,
+ });
const [allowOpenAIFallback, setAllowOpenAIFallback] = useLocalStorage(
"allowOpenAIFallback",
@@ -59,14 +51,10 @@ export function useSettings() {
}
);
- const [allowLocalFallback, setAllowLocalFallback] = useLocalStorage(
- "allowLocalFallback",
- false,
- {
- serialize: String,
- deserialize: (value) => value === "true",
- }
- );
+ const [allowLocalFallback, setAllowLocalFallback] = useLocalStorage("allowLocalFallback", false, {
+ serialize: String,
+ deserialize: (value) => value === "true",
+ });
const [fallbackWhisperModel, setFallbackWhisperModel] = useLocalStorage(
"fallbackWhisperModel",
@@ -77,14 +65,10 @@ export function useSettings() {
}
);
- const [preferredLanguage, setPreferredLanguage] = useLocalStorage(
- "preferredLanguage",
- "en",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [preferredLanguage, setPreferredLanguage] = useLocalStorage("preferredLanguage", "en", {
+ serialize: String,
+ deserialize: String,
+ });
const [cloudTranscriptionBaseUrl, setCloudTranscriptionBaseUrl] = useLocalStorage(
"cloudTranscriptionBaseUrl",
@@ -105,23 +89,15 @@ export function useSettings() {
);
// Reasoning settings
- const [useReasoningModel, setUseReasoningModel] = useLocalStorage(
- "useReasoningModel",
- true,
- {
- serialize: String,
- deserialize: (value) => value !== "false", // Default true
- }
- );
+ const [useReasoningModel, setUseReasoningModel] = useLocalStorage("useReasoningModel", true, {
+ serialize: String,
+ deserialize: (value) => value !== "false", // Default true
+ });
- const [reasoningModel, setReasoningModel] = useLocalStorage(
- "reasoningModel",
- "gpt-4o-mini",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [reasoningModel, setReasoningModel] = useLocalStorage("reasoningModel", "gpt-4o-mini", {
+ serialize: String,
+ deserialize: String,
+ });
// API keys
const [openaiApiKey, setOpenaiApiKey] = useLocalStorage("openaiApiKey", "", {
@@ -129,32 +105,20 @@ export function useSettings() {
deserialize: String,
});
- const [anthropicApiKey, setAnthropicApiKey] = useLocalStorage(
- "anthropicApiKey",
- "",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [anthropicApiKey, setAnthropicApiKey] = useLocalStorage("anthropicApiKey", "", {
+ serialize: String,
+ deserialize: String,
+ });
- const [geminiApiKey, setGeminiApiKey] = useLocalStorage(
- "geminiApiKey",
- "",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [geminiApiKey, setGeminiApiKey] = useLocalStorage("geminiApiKey", "", {
+ serialize: String,
+ deserialize: String,
+ });
- const [groqApiKey, setGroqApiKey] = useLocalStorage(
- "groqApiKey",
- "",
- {
- serialize: String,
- deserialize: String,
- }
- );
+ const [groqApiKey, setGroqApiKey] = useLocalStorage("groqApiKey", "", {
+ serialize: String,
+ deserialize: String,
+ });
// Hotkey
const [dictationKey, setDictationKey] = useLocalStorage("dictationKey", "", {
@@ -168,10 +132,8 @@ export function useSettings() {
// Batch operations
const updateTranscriptionSettings = useCallback(
(settings: Partial<TranscriptionSettings>) => {
- if (settings.useLocalWhisper !== undefined)
- setUseLocalWhisper(settings.useLocalWhisper);
- if (settings.whisperModel !== undefined)
- setWhisperModel(settings.whisperModel);
+ if (settings.useLocalWhisper !== undefined) setUseLocalWhisper(settings.useLocalWhisper);
+ if (settings.whisperModel !== undefined) setWhisperModel(settings.whisperModel);
if (settings.allowOpenAIFallback !== undefined)
setAllowOpenAIFallback(settings.allowOpenAIFallback);
if (settings.allowLocalFallback !== undefined)
@@ -198,8 +160,7 @@ export function useSettings() {
(settings: Partial<ReasoningSettings>) => {
if (settings.useReasoningModel !== undefined)
setUseReasoningModel(settings.useReasoningModel);
- if (settings.reasoningModel !== undefined)
- setReasoningModel(settings.reasoningModel);
+ if (settings.reasoningModel !== undefined) setReasoningModel(settings.reasoningModel);
if (settings.cloudReasoningBaseUrl !== undefined)
setCloudReasoningBaseUrl(settings.cloudReasoningBaseUrl);
// reasoningProvider is computed from reasoningModel, not stored separately
@@ -210,12 +171,9 @@ export function useSettings() {
const updateApiKeys = useCallback(
(keys: Partial<ApiKeySettings>) => {
if (keys.openaiApiKey !== undefined) setOpenaiApiKey(keys.openaiApiKey);
- if (keys.anthropicApiKey !== undefined)
- setAnthropicApiKey(keys.anthropicApiKey);
- if (keys.geminiApiKey !== undefined)
- setGeminiApiKey(keys.geminiApiKey);
- if (keys.groqApiKey !== undefined)
- setGroqApiKey(keys.groqApiKey);
+ if (keys.anthropicApiKey !== undefined) setAnthropicApiKey(keys.anthropicApiKey);
+ if (keys.geminiApiKey !== undefined) setGeminiApiKey(keys.geminiApiKey);
+ if (keys.groqApiKey !== undefined) setGroqApiKey(keys.groqApiKey);
},
[setOpenaiApiKey, setAnthropicApiKey, setGeminiApiKey, setGroqApiKey]
);
@@ -248,7 +206,7 @@ export function useSettings() {
setUseReasoningModel,
setReasoningModel,
setReasoningProvider: (provider: string) => {
- if (provider === 'custom') {
+ if (provider === "custom") {
return;
}
@@ -259,10 +217,7 @@ export function useSettings() {
groq: "qwen/qwen3-32b", // Groq's powerful reasoning model
local: "llama-3.2-3b",
};
- setReasoningModel(
- providerModels[provider as keyof typeof providerModels] ||
- "gpt-4o-mini"
- );
+ setReasoningModel(providerModels[provider as keyof typeof providerModels] || "gpt-4o-mini");
},
setOpenaiApiKey,
setAnthropicApiKey,
diff --git a/src/hooks/useWhisper.ts b/src/hooks/useWhisper.ts
index 825d61149..78e039e2b 100644
--- a/src/hooks/useWhisper.ts
+++ b/src/hooks/useWhisper.ts
@@ -28,8 +28,7 @@ export const useWhisper = (
const checkWhisperInstallation = useCallback(async () => {
try {
setCheckingWhisper(true);
- const result: WhisperCheckResult =
- await window.electronAPI.checkWhisperInstallation();
+ const result: WhisperCheckResult = await window.electronAPI.checkWhisperInstallation();
setWhisperInstalled(result.installed && result.working);
} catch (error) {
console.error("Error checking Whisper installation:", error);
@@ -44,8 +43,7 @@ export const useWhisper = (
setInstallingWhisper(true);
setInstallProgress("Starting Whisper installation...");
- const result: WhisperInstallResult =
- await window.electronAPI.installWhisper();
+ const result: WhisperInstallResult = await window.electronAPI.installWhisper();
if (result.success) {
setWhisperInstalled(true);
diff --git a/src/index.css b/src/index.css
index e2c70caed..c55fa8575 100644
--- a/src/index.css
+++ b/src/index.css
@@ -51,41 +51,90 @@
* {
@apply border-gray-200 outline-indigo-500/50;
}
-
+
body {
@apply bg-white text-gray-900;
margin: 0;
padding: 0;
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
- font-feature-settings: "liga" 1, "kern" 1;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
+ font-feature-settings:
+ "liga" 1,
+ "kern" 1;
text-rendering: optimizeLegibility;
}
-
+
/* Electron specific styles */
- html, body, #root {
+ html,
+ body,
+ #root {
background: transparent;
}
}
/* OpenWhispr Brand Typography */
.brand-heading {
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
font-weight: 600;
letter-spacing: -0.02em;
}
.brand-body {
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
line-height: 1.6;
}
.brand-script {
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
font-style: italic;
}
-h1, h2, h3, h4, h5, h6 {
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+h1,
+h2,
+h3,
+h4,
+h5,
+h6 {
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
font-weight: 600;
letter-spacing: -0.02em;
line-height: 1.2;
@@ -98,7 +147,15 @@ h1 {
/* Modern Button Styling - handled by button component */
button {
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
cursor: pointer;
}
@@ -113,86 +170,105 @@ svg:hover,
}
/* Embossed paper-like input styling */
-input, textarea {
+input,
+textarea {
border-radius: 8px;
transition: all 0.2s ease;
- font-family: 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ "Noto Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ Roboto,
+ "Helvetica Neue",
+ Arial,
+ sans-serif;
box-shadow: inset 0 1px 3px rgba(43, 31, 20, 0.1);
}
/* Light mode inputs - embossed parchment */
-:root input, :root textarea {
- background-color: #F9F6F1;
- border: 1px solid #DDD4C7;
- color: #2B1F14;
+:root input,
+:root textarea {
+ background-color: #f9f6f1;
+ border: 1px solid #ddd4c7;
+ color: #2b1f14;
}
-:root input:focus, :root textarea:focus {
- border-color: #C0A77D;
- box-shadow: 0 0 0 2px rgba(192, 167, 125, 0.2), inset 0 1px 3px rgba(43, 31, 20, 0.1);
- background-color: #FFFFFF;
+:root input:focus,
+:root textarea:focus {
+ border-color: #c0a77d;
+ box-shadow:
+ 0 0 0 2px rgba(192, 167, 125, 0.2),
+ inset 0 1px 3px rgba(43, 31, 20, 0.1);
+ background-color: #ffffff;
}
/* Dark mode inputs */
-.dark input, .dark textarea {
+.dark input,
+.dark textarea {
background-color: oklch(0.15 0 0);
border: 1px solid oklch(0.25 0 0);
color: oklch(0.9 0 0);
}
-.dark input:focus, .dark textarea:focus {
+.dark input:focus,
+.dark textarea:focus {
border-color: oklch(0.55 0.25 250);
box-shadow: 0 0 0 2px oklch(0.55 0.25 250 / 0.2);
}
/* Card styling - elevated parchment */
.card {
- background-color: #FFFFFF;
- border: 1px solid #DDD4C7;
+ background-color: #ffffff;
+ border: 1px solid #ddd4c7;
border-radius: 12px;
- box-shadow: 0 4px 8px rgba(43, 31, 20, 0.08), 0 1px 0 rgba(255, 255, 255, 0.5) inset;
+ box-shadow:
+ 0 4px 8px rgba(43, 31, 20, 0.08),
+ 0 1px 0 rgba(255, 255, 255, 0.5) inset;
transition: all 0.2s ease;
}
.card:hover {
- box-shadow: 0 8px 16px rgba(43, 31, 20, 0.1), 0 1px 0 rgba(255, 255, 255, 0.5) inset;
+ box-shadow:
+ 0 8px 16px rgba(43, 31, 20, 0.1),
+ 0 1px 0 rgba(255, 255, 255, 0.5) inset;
transform: translateY(-1px);
}
/* Link styling */
a {
- color: #2E3659;
+ color: #2e3659;
text-decoration: none;
transition: color 0.2s ease;
cursor: pointer;
}
a:hover {
- color: #4B2E2B;
+ color: #4b2e2b;
text-decoration: underline;
cursor: pointer;
}
/* Status indicators */
.status-active {
- color: #4B2E2B;
+ color: #4b2e2b;
font-weight: 600;
}
.text-brand-primary {
- color: #2B1F14;
+ color: #2b1f14;
}
.text-brand-accent {
- color: #4B2E2B;
+ color: #4b2e2b;
}
.text-brand-highlight {
- color: #C0A77D;
+ color: #c0a77d;
}
.text-brand-link {
- color: #2E3659;
+ color: #2e3659;
}
/* Additional CSS variables for theme support */
diff --git a/src/main.jsx b/src/main.jsx
index 16bd71ac9..54217c45e 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -12,19 +12,15 @@ function AppRouter() {
// Check if this is the control panel window
const isControlPanel =
- window.location.pathname.includes("control") ||
- window.location.search.includes("panel=true");
+ window.location.pathname.includes("control") || window.location.search.includes("panel=true");
// Check if this is the dictation panel (main app)
const isDictationPanel = !isControlPanel;
useEffect(() => {
// Check if onboarding has been completed
- const onboardingCompleted =
- localStorage.getItem("onboardingCompleted") === "true";
- const currentStep = parseInt(
- localStorage.getItem("onboardingCurrentStep") || "0"
- );
+ const onboardingCompleted = localStorage.getItem("onboardingCompleted") === "true";
+ const currentStep = parseInt(localStorage.getItem("onboardingCurrentStep") || "0");
if (isControlPanel && !onboardingCompleted) {
// Show onboarding for control panel if not completed
diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.ts
index 089211c22..bbc57558a 100644
--- a/src/models/ModelRegistry.ts
+++ b/src/models/ModelRegistry.ts
@@ -59,7 +59,7 @@ class ModelRegistry {
getModel(modelId: string): { model: ModelDefinition; provider: ModelProvider } | undefined {
for (const provider of this.providers.values()) {
- const model = provider.models.find(m => m.id === modelId);
+ const model = provider.models.find((m) => m.id === modelId);
if (model) {
return { model, provider };
}
@@ -69,64 +69,64 @@ class ModelRegistry {
getAllModels(): Array<ModelDefinition & { providerId: string }> {
const models: Array<ModelDefinition & { providerId: string }> = [];
-
+
for (const provider of this.providers.values()) {
for (const model of provider.models) {
models.push({
...model,
- providerId: provider.id
+ providerId: provider.id,
});
}
}
-
+
return models;
}
private registerDefaultProviders() {
// Qwen Provider
this.registerProvider({
- id: 'qwen',
- name: 'Qwen',
- baseUrl: 'https://huggingface.co',
+ id: "qwen",
+ name: "Qwen",
+ baseUrl: "https://huggingface.co",
models: [
{
- id: 'qwen2.5-0.5b-instruct-q5_k_m',
- name: 'Qwen2.5 0.5B',
- size: '0.4GB',
+ id: "qwen2.5-0.5b-instruct-q5_k_m",
+ name: "Qwen2.5 0.5B",
+ size: "0.4GB",
sizeBytes: 429496729,
- description: 'Smallest model, fast but limited capabilities',
- fileName: 'qwen2.5-0.5b-instruct-q5_k_m.gguf',
- quantization: 'q5_k_m',
+ description: "Smallest model, fast but limited capabilities",
+ fileName: "qwen2.5-0.5b-instruct-q5_k_m.gguf",
+ quantization: "q5_k_m",
contextLength: 32768,
},
{
- id: 'qwen2.5-1.5b-instruct-q5_k_m',
- name: 'Qwen2.5 1.5B',
- size: '1.3GB',
+ id: "qwen2.5-1.5b-instruct-q5_k_m",
+ name: "Qwen2.5 1.5B",
+ size: "1.3GB",
sizeBytes: 1395864371,
- description: 'Small model, good for basic tasks',
- fileName: 'qwen2.5-1.5b-instruct-q5_k_m.gguf',
- quantization: 'q5_k_m',
+ description: "Small model, good for basic tasks",
+ fileName: "qwen2.5-1.5b-instruct-q5_k_m.gguf",
+ quantization: "q5_k_m",
contextLength: 32768,
},
{
- id: 'qwen2.5-3b-instruct-q5_k_m',
- name: 'Qwen2.5 3B',
- size: '2.3GB',
+ id: "qwen2.5-3b-instruct-q5_k_m",
+ name: "Qwen2.5 3B",
+ size: "2.3GB",
sizeBytes: 2469606195,
- description: 'Balanced model for general use',
- fileName: 'qwen2.5-3b-instruct-q5_k_m.gguf',
- quantization: 'q5_k_m',
+ description: "Balanced model for general use",
+ fileName: "qwen2.5-3b-instruct-q5_k_m.gguf",
+ quantization: "q5_k_m",
contextLength: 32768,
},
{
- id: 'qwen2.5-7b-instruct-q5_k_m',
- name: 'Qwen2.5 7B',
- size: '5.4GB',
+ id: "qwen2.5-7b-instruct-q5_k_m",
+ name: "Qwen2.5 7B",
+ size: "5.4GB",
sizeBytes: 5798205849,
- description: 'Large model, high quality reasoning',
- fileName: 'qwen2.5-7b-instruct-q5_k_m.gguf',
- quantization: 'q5_k_m',
+ description: "Large model, high quality reasoning",
+ fileName: "qwen2.5-7b-instruct-q5_k_m.gguf",
+ quantization: "q5_k_m",
contextLength: 128000,
recommended: true,
},
@@ -140,44 +140,44 @@ ${text}<|im_end|>
`;
},
getDownloadUrl(model: ModelDefinition): string {
- return `${this.baseUrl}/Qwen/Qwen2.5-${model.name.split(' ')[1]}-Instruct-GGUF/resolve/main/${model.fileName}`;
- }
+ return `${this.baseUrl}/Qwen/Qwen2.5-${model.name.split(" ")[1]}-Instruct-GGUF/resolve/main/${model.fileName}`;
+ },
});
this.registerProvider({
- id: 'mistral',
- name: 'Mistral AI',
- baseUrl: 'https://huggingface.co',
+ id: "mistral",
+ name: "Mistral AI",
+ baseUrl: "https://huggingface.co",
models: [
{
- id: 'mistral-7b-instruct-v0.3-q4_k_m',
- name: 'Mistral 7B Instruct v0.3',
- size: '4.4GB',
+ id: "mistral-7b-instruct-v0.3-q4_k_m",
+ name: "Mistral 7B Instruct v0.3",
+ size: "4.4GB",
sizeBytes: 4724956928,
- description: 'Fast and efficient instruction model',
- fileName: 'Mistral-7B-Instruct-v0.3-Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "Fast and efficient instruction model",
+ fileName: "Mistral-7B-Instruct-v0.3-Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 32768,
recommended: true,
},
{
- id: 'mistral-7b-instruct-v0.3-q5_k_m',
- name: 'Mistral 7B Instruct v0.3 (Q5)',
- size: '5.1GB',
+ id: "mistral-7b-instruct-v0.3-q5_k_m",
+ name: "Mistral 7B Instruct v0.3 (Q5)",
+ size: "5.1GB",
sizeBytes: 5477387264,
- description: 'Higher quality instruction model',
- fileName: 'Mistral-7B-Instruct-v0.3-Q5_K_M.gguf',
- quantization: 'q5_k_m',
+ description: "Higher quality instruction model",
+ fileName: "Mistral-7B-Instruct-v0.3-Q5_K_M.gguf",
+ quantization: "q5_k_m",
contextLength: 32768,
},
{
- id: 'mistral-7b-v0.1-q4_k_m',
- name: 'Mistral 7B v0.1',
- size: '4.4GB',
+ id: "mistral-7b-v0.1-q4_k_m",
+ name: "Mistral 7B v0.1",
+ size: "4.4GB",
sizeBytes: 4724956928,
- description: 'Base model for general text',
- fileName: 'mistral-7b-v0.1.Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "Base model for general text",
+ fileName: "mistral-7b-v0.1.Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 32768,
},
],
@@ -185,48 +185,48 @@ ${text}<|im_end|>
return `[INST] ${systemPrompt}\n\n${text} [/INST]`;
},
getDownloadUrl(model: ModelDefinition): string {
- if (model.id.includes('v0.3')) {
+ if (model.id.includes("v0.3")) {
return `${this.baseUrl}/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/${model.fileName}`;
}
return `${this.baseUrl}/TheBloke/Mistral-7B-v0.1-GGUF/resolve/main/${model.fileName}`;
- }
+ },
});
// Llama Provider
this.registerProvider({
- id: 'llama',
- name: 'Meta Llama',
- baseUrl: 'https://huggingface.co',
+ id: "llama",
+ name: "Meta Llama",
+ baseUrl: "https://huggingface.co",
models: [
{
- id: 'llama-3.2-1b-instruct-q4_k_m',
- name: 'Llama 3.2 1B',
- size: '0.9GB',
+ id: "llama-3.2-1b-instruct-q4_k_m",
+ name: "Llama 3.2 1B",
+ size: "0.9GB",
sizeBytes: 966367642,
- description: 'Tiny model for edge devices',
- fileName: 'Llama-3.2-1B-Instruct-Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "Tiny model for edge devices",
+ fileName: "Llama-3.2-1B-Instruct-Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 131072,
},
{
- id: 'llama-3.2-3b-instruct-q4_k_m',
- name: 'Llama 3.2 3B',
- size: '2.0GB',
+ id: "llama-3.2-3b-instruct-q4_k_m",
+ name: "Llama 3.2 3B",
+ size: "2.0GB",
sizeBytes: 2147483648,
- description: 'Small but capable multilingual model',
- fileName: 'Llama-3.2-3B-Instruct-Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "Small but capable multilingual model",
+ fileName: "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 131072,
recommended: true,
},
{
- id: 'llama-3.1-8b-instruct-q4_k_m',
- name: 'Llama 3.1 8B',
- size: '4.9GB',
+ id: "llama-3.1-8b-instruct-q4_k_m",
+ name: "Llama 3.1 8B",
+ size: "4.9GB",
sizeBytes: 5260091802,
- description: 'Powerful model with great performance',
- fileName: 'Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "Powerful model with great performance",
+ fileName: "Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 131072,
},
],
@@ -240,27 +240,27 @@ ${text}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
`;
},
getDownloadUrl(model: ModelDefinition): string {
- if (model.id.includes('3.2')) {
- return `${this.baseUrl}/bartowski/Llama-3.2-${model.name.split(' ')[2]}-Instruct-GGUF/resolve/main/${model.fileName}`;
+ if (model.id.includes("3.2")) {
+ return `${this.baseUrl}/bartowski/Llama-3.2-${model.name.split(" ")[2]}-Instruct-GGUF/resolve/main/${model.fileName}`;
}
return `${this.baseUrl}/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/${model.fileName}`;
- }
+ },
});
// OpenAI OSS Provider
this.registerProvider({
- id: 'openai-oss',
- name: 'OpenAI OSS',
- baseUrl: 'https://huggingface.co',
+ id: "openai-oss",
+ name: "OpenAI OSS",
+ baseUrl: "https://huggingface.co",
models: [
{
- id: 'gpt-oss-20b-q4_k_m',
- name: 'GPT-OSS 20B',
- size: '12.1GB',
+ id: "gpt-oss-20b-q4_k_m",
+ name: "GPT-OSS 20B",
+ size: "12.1GB",
sizeBytes: 12999763968,
- description: 'OpenAI\'s open-source model for consumer hardware',
- fileName: 'openai_gpt-oss-20b-Q4_K_M.gguf',
- quantization: 'q4_k_m',
+ description: "OpenAI's open-source model for consumer hardware",
+ fileName: "openai_gpt-oss-20b-Q4_K_M.gguf",
+ quantization: "q4_k_m",
contextLength: 128000,
recommended: true,
},
@@ -276,9 +276,9 @@ ${text}<|im_end|>
},
getDownloadUrl(model: ModelDefinition): string {
return `${this.baseUrl}/bartowski/openai_gpt-oss-20b-GGUF/resolve/main/${model.fileName}`;
- }
+ },
});
}
}
-export const modelRegistry = ModelRegistry.getInstance();
\ No newline at end of file
+export const modelRegistry = ModelRegistry.getInstance();
diff --git a/src/models/modelRegistryData.json b/src/models/modelRegistryData.json
index 544032de5..72f820448 100644
--- a/src/models/modelRegistryData.json
+++ b/src/models/modelRegistryData.json
@@ -49,7 +49,7 @@
{
"id": "qwen2.5-7b-instruct-q5_k_m",
"name": "Qwen2.5 7B",
- "size": "5.4GB",
+ "size": "5.4GB",
"sizeBytes": 5798205849,
"description": "Large model, high quality reasoning (Q5_K_M quantization)",
"fileName": "qwen2.5-7b-instruct-q5_k_m.gguf",
@@ -59,4 +59,4 @@
]
}
]
-}
\ No newline at end of file
+}
diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.ts
index 2e29a1ba7..678fb3ea8 100644
--- a/src/services/BaseReasoningService.ts
+++ b/src/services/BaseReasoningService.ts
@@ -11,7 +11,7 @@ export abstract class BaseReasoningService {
* Get reasoning prompt
*/
protected getReasoningPrompt(
- text: string,
+ text: string,
agentName: string | null,
config: ReasoningConfig = {}
): string {
@@ -23,15 +23,15 @@ export abstract class BaseReasoningService {
let agentPrompt = DEFAULT_AGENT_PROMPT;
let regularPrompt = DEFAULT_REGULAR_PROMPT;
- if (typeof window !== 'undefined' && window.localStorage) {
- const customPrompts = window.localStorage.getItem('customPrompts');
+ if (typeof window !== "undefined" && window.localStorage) {
+ const customPrompts = window.localStorage.getItem("customPrompts");
if (customPrompts) {
try {
const parsed = JSON.parse(customPrompts);
agentPrompt = parsed.agent || DEFAULT_AGENT_PROMPT;
regularPrompt = parsed.regular || DEFAULT_REGULAR_PROMPT;
} catch (error) {
- console.error('Failed to parse custom prompts:', error);
+ console.error("Failed to parse custom prompts:", error);
}
}
}
@@ -39,11 +39,9 @@ export abstract class BaseReasoningService {
// Simple prompt construction
if (agentName && text.toLowerCase().includes(agentName.toLowerCase())) {
// Agent-based prompt - replace placeholders
- return agentPrompt
- .replace(/\{\{agentName\}\}/g, agentName)
- .replace(/\{\{text\}\}/g, text);
+ return agentPrompt.replace(/\{\{agentName\}\}/g, agentName).replace(/\{\{text\}\}/g, text);
}
-
+
// Regular prompt - replace placeholders
return regularPrompt.replace(/\{\{text\}\}/g, text);
}
@@ -74,4 +72,4 @@ export abstract class BaseReasoningService {
agentName?: string | null,
config?: ReasoningConfig
): Promise<string>;
-}
\ No newline at end of file
+}
diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.ts
index 0754c1f30..1ba36bc0c 100644
--- a/src/services/LocalReasoningService.ts
+++ b/src/services/LocalReasoningService.ts
@@ -21,9 +21,9 @@ class LocalReasoningService extends BaseReasoningService {
modelId,
agentName,
textLength: text.length,
- configKeys: Object.keys(config)
+ configKeys: Object.keys(config),
});
-
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
@@ -34,28 +34,30 @@ class LocalReasoningService extends BaseReasoningService {
try {
// Get prompt using the base class method
const reasoningPrompt = this.getReasoningPrompt(text, agentName, config);
-
+
logger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {
promptLength: reasoningPrompt.length,
- hasAgentName: !!agentName
+ hasAgentName: !!agentName,
});
// Get optimized config for reasoning use case
- const inferenceOptions = inferenceConfig.getConfigForUseCase('reasoning');
-
+ 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
- );
-
+ 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
+ contextSize: config.contextSize || TOKEN_LIMITS.REASONING_CONTEXT_SIZE,
});
// Run inference
@@ -65,27 +67,27 @@ class LocalReasoningService extends BaseReasoningService {
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 ? "..." : "")
+ 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
+ stack: (error as Error).stack,
});
-
+
console.error("LocalReasoningService error:", error);
throw error;
} finally {
@@ -108,7 +110,7 @@ class LocalReasoningService extends BaseReasoningService {
async getDownloadedModels() {
try {
const modelsWithStatus = await modelManager.getModelsWithStatus();
- return modelsWithStatus.filter(model => model.isDownloaded);
+ return modelsWithStatus.filter((model) => model.isDownloaded);
} catch (error) {
console.error("Failed to get downloaded models:", error);
return [];
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index e1c822d26..d0b920956 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -7,13 +7,13 @@ import logger from "../utils/logger";
export const DEFAULT_PROMPTS = {
agent: `You are {{agentName}}, a helpful AI assistant. Process and improve the following text, removing any reference to your name from the output:\n\n{{text}}\n\nImproved text:`,
- regular: `Process and improve the following text:\n\n{{text}}\n\nImproved text:`
+ regular: `Process and improve the following text:\n\n{{text}}\n\nImproved text:`,
};
class ReasoningService extends BaseReasoningService {
private apiKeyCache: SecureCache<string>;
private openAiEndpointPreference = new Map<string, "responses" | "chat">();
- private static readonly OPENAI_ENDPOINT_PREF_STORAGE_KEY = 'openAiEndpointPreference';
+ private static readonly OPENAI_ENDPOINT_PREF_STORAGE_KEY = "openAiEndpointPreference";
private cacheCleanupStop: (() => void) | undefined;
constructor() {
@@ -23,22 +23,23 @@ class ReasoningService extends BaseReasoningService {
}
private getConfiguredOpenAIBase(): string {
- if (typeof window === 'undefined' || !window.localStorage) {
+ if (typeof window === "undefined" || !window.localStorage) {
return API_ENDPOINTS.OPENAI_BASE;
}
try {
- const stored = window.localStorage.getItem('cloudReasoningBaseUrl') || '';
+ const stored = window.localStorage.getItem("cloudReasoningBaseUrl") || "";
const trimmed = stored.trim();
const candidate = trimmed || API_ENDPOINTS.OPENAI_BASE;
const normalized = normalizeBaseUrl(candidate) || API_ENDPOINTS.OPENAI_BASE;
// Security: Only allow HTTPS endpoints (except localhost for development)
- const isLocalhost = normalized.includes('://localhost') || normalized.includes('://127.0.0.1');
- if (!normalized.startsWith('https://') && !isLocalhost) {
- logger.logReasoning('OPENAI_BASE_REJECTED', {
- reason: 'Non-HTTPS endpoint rejected for security',
- attempted: normalized
+ const isLocalhost =
+ normalized.includes("://localhost") || normalized.includes("://127.0.0.1");
+ if (!normalized.startsWith("https://") && !isLocalhost) {
+ logger.logReasoning("OPENAI_BASE_REJECTED", {
+ reason: "Non-HTTPS endpoint rejected for security",
+ attempted: normalized,
});
return API_ENDPOINTS.OPENAI_BASE;
}
@@ -49,33 +50,35 @@ class ReasoningService extends BaseReasoningService {
}
}
- private getOpenAIEndpointCandidates(base: string): Array<{ url: string; type: 'responses' | 'chat' }> {
+ private getOpenAIEndpointCandidates(
+ base: string
+ ): Array<{ url: string; type: "responses" | "chat" }> {
const lower = base.toLowerCase();
- if (lower.endsWith('/responses') || lower.endsWith('/chat/completions')) {
- const type = lower.endsWith('/responses') ? 'responses' : 'chat';
+ if (lower.endsWith("/responses") || lower.endsWith("/chat/completions")) {
+ const type = lower.endsWith("/responses") ? "responses" : "chat";
return [{ url: base, type }];
}
const preference = this.getStoredOpenAiPreference(base);
- if (preference === 'chat') {
- return [{ url: buildApiUrl(base, '/chat/completions'), type: 'chat' }];
+ if (preference === "chat") {
+ return [{ url: buildApiUrl(base, "/chat/completions"), type: "chat" }];
}
- const candidates: Array<{ url: string; type: 'responses' | 'chat' }> = [
- { url: buildApiUrl(base, '/responses'), type: 'responses' },
- { url: buildApiUrl(base, '/chat/completions'), type: 'chat' },
+ const candidates: Array<{ url: string; type: "responses" | "chat" }> = [
+ { url: buildApiUrl(base, "/responses"), type: "responses" },
+ { url: buildApiUrl(base, "/chat/completions"), type: "chat" },
];
return candidates;
}
- private getStoredOpenAiPreference(base: string): 'responses' | 'chat' | undefined {
+ private getStoredOpenAiPreference(base: string): "responses" | "chat" | undefined {
if (this.openAiEndpointPreference.has(base)) {
return this.openAiEndpointPreference.get(base);
}
- if (typeof window === 'undefined' || !window.localStorage) {
+ if (typeof window === "undefined" || !window.localStorage) {
return undefined;
}
@@ -85,11 +88,11 @@ class ReasoningService extends BaseReasoningService {
return undefined;
}
const parsed = JSON.parse(raw);
- if (typeof parsed !== 'object' || parsed === null) {
+ if (typeof parsed !== "object" || parsed === null) {
return undefined;
}
const value = parsed[base];
- if (value === 'responses' || value === 'chat') {
+ if (value === "responses" || value === "chat") {
this.openAiEndpointPreference.set(base, value);
return value;
}
@@ -100,31 +103,34 @@ class ReasoningService extends BaseReasoningService {
return undefined;
}
- private rememberOpenAiPreference(base: string, preference: 'responses' | 'chat'): void {
+ private rememberOpenAiPreference(base: string, preference: "responses" | "chat"): void {
this.openAiEndpointPreference.set(base, preference);
- if (typeof window === 'undefined' || !window.localStorage) {
+ if (typeof window === "undefined" || !window.localStorage) {
return;
}
try {
const raw = window.localStorage.getItem(ReasoningService.OPENAI_ENDPOINT_PREF_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : {};
- const data = typeof parsed === 'object' && parsed !== null ? parsed : {};
+ const data = typeof parsed === "object" && parsed !== null ? parsed : {};
data[base] = preference;
- window.localStorage.setItem(ReasoningService.OPENAI_ENDPOINT_PREF_STORAGE_KEY, JSON.stringify(data));
+ window.localStorage.setItem(
+ ReasoningService.OPENAI_ENDPOINT_PREF_STORAGE_KEY,
+ JSON.stringify(data)
+ );
} catch {
// Ignore storage errors
}
}
- private async getApiKey(provider: 'openai' | 'anthropic' | 'gemini' | 'groq'): Promise<string> {
+ private async getApiKey(provider: "openai" | "anthropic" | "gemini" | "groq"): Promise<string> {
let apiKey = this.apiKeyCache.get(provider);
logger.logReasoning(`${provider.toUpperCase()}_KEY_RETRIEVAL`, {
provider,
fromCache: !!apiKey,
- cacheSize: this.apiKeyCache.size || 0
+ cacheSize: this.apiKeyCache.size || 0,
});
if (!apiKey) {
@@ -135,15 +141,15 @@ class ReasoningService extends BaseReasoningService {
gemini: () => window.electronAPI.getGeminiKey(),
groq: () => window.electronAPI.getGroqKey(),
};
- apiKey = await keyGetters[provider]() ?? undefined;
-
+ apiKey = (await keyGetters[provider]()) ?? undefined;
+
logger.logReasoning(`${provider.toUpperCase()}_KEY_FETCHED`, {
provider,
hasKey: !!apiKey,
keyLength: apiKey?.length || 0,
- keyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : 'none'
+ keyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : "none",
});
-
+
if (apiKey) {
this.apiKeyCache.set(provider, apiKey);
}
@@ -151,20 +157,20 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning(`${provider.toUpperCase()}_KEY_FETCH_ERROR`, {
provider,
error: (error as Error).message,
- stack: (error as Error).stack
+ stack: (error as Error).stack,
});
}
}
-
+
if (!apiKey) {
const errorMsg = `${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured`;
logger.logReasoning(`${provider.toUpperCase()}_KEY_MISSING`, {
provider,
- error: errorMsg
+ error: errorMsg,
});
throw new Error(errorMsg);
}
-
+
return apiKey;
}
@@ -181,83 +187,87 @@ class ReasoningService extends BaseReasoningService {
config: ReasoningConfig,
providerName: string
): Promise<string> {
- const systemPrompt = "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
+ const systemPrompt =
+ "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
const userPrompt = this.getReasoningPrompt(text, agentName, config);
const messages = [
{ role: "system", content: systemPrompt },
- { role: "user", content: userPrompt }
+ { role: "user", content: userPrompt },
];
const requestBody: any = {
model,
messages,
temperature: config.temperature ?? 0.3,
- max_tokens: config.maxTokens || Math.max(
- 4096,
- this.calculateMaxTokens(
- text.length,
- TOKEN_LIMITS.MIN_TOKENS,
- TOKEN_LIMITS.MAX_TOKENS,
- TOKEN_LIMITS.TOKEN_MULTIPLIER
- )
- ),
+ max_tokens:
+ config.maxTokens ||
+ Math.max(
+ 4096,
+ this.calculateMaxTokens(
+ text.length,
+ TOKEN_LIMITS.MIN_TOKENS,
+ TOKEN_LIMITS.MAX_TOKENS,
+ TOKEN_LIMITS.TOKEN_MULTIPLIER
+ )
+ ),
};
logger.logReasoning(`${providerName.toUpperCase()}_REQUEST`, {
endpoint,
model,
hasApiKey: !!apiKey,
- requestBody: JSON.stringify(requestBody).substring(0, 200)
+ requestBody: JSON.stringify(requestBody).substring(0, 200),
});
- const response = await withRetry(
- async () => {
- const res = await fetch(endpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiKey}`,
- },
- body: JSON.stringify(requestBody),
- });
+ const response = await withRetry(async () => {
+ const res = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify(requestBody),
+ });
- if (!res.ok) {
- const errorText = await res.text();
- let errorData: any = { error: res.statusText };
+ if (!res.ok) {
+ const errorText = await res.text();
+ let errorData: any = { error: res.statusText };
- try {
- errorData = JSON.parse(errorText);
- } catch {
- errorData = { error: errorText || res.statusText };
- }
+ try {
+ errorData = JSON.parse(errorText);
+ } catch {
+ errorData = { error: errorText || res.statusText };
+ }
- logger.logReasoning(`${providerName.toUpperCase()}_API_ERROR_DETAIL`, {
- status: res.status,
- statusText: res.statusText,
- error: errorData,
- errorMessage: errorData.error?.message || errorData.message || errorData.error,
- fullResponse: errorText.substring(0, 500)
- });
+ logger.logReasoning(`${providerName.toUpperCase()}_API_ERROR_DETAIL`, {
+ status: res.status,
+ statusText: res.statusText,
+ error: errorData,
+ errorMessage: errorData.error?.message || errorData.message || errorData.error,
+ fullResponse: errorText.substring(0, 500),
+ });
- const errorMessage = errorData.error?.message || errorData.message || errorData.error || `${providerName} API error: ${res.status}`;
- throw new Error(errorMessage);
- }
+ const errorMessage =
+ errorData.error?.message ||
+ errorData.message ||
+ errorData.error ||
+ `${providerName} API error: ${res.status}`;
+ throw new Error(errorMessage);
+ }
- const jsonResponse = await res.json();
+ const jsonResponse = await res.json();
- logger.logReasoning(`${providerName.toUpperCase()}_RAW_RESPONSE`, {
- hasResponse: !!jsonResponse,
- responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],
- hasChoices: !!jsonResponse?.choices,
- choicesLength: jsonResponse?.choices?.length || 0,
- fullResponse: JSON.stringify(jsonResponse).substring(0, 500)
- });
+ logger.logReasoning(`${providerName.toUpperCase()}_RAW_RESPONSE`, {
+ hasResponse: !!jsonResponse,
+ responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],
+ hasChoices: !!jsonResponse?.choices,
+ choicesLength: jsonResponse?.choices?.length || 0,
+ fullResponse: JSON.stringify(jsonResponse).substring(0, 500),
+ });
- return jsonResponse;
- },
- createApiRetryStrategy()
- );
+ return jsonResponse;
+ }, createApiRetryStrategy());
// Extract text from Chat Completions format
if (!response.choices || !response.choices[0]) {
@@ -265,7 +275,7 @@ class ReasoningService extends BaseReasoningService {
model,
response: JSON.stringify(response).substring(0, 500),
hasChoices: !!response.choices,
- choicesCount: response.choices?.length || 0
+ choicesCount: response.choices?.length || 0,
});
throw new Error(`Invalid response structure from ${providerName} API`);
}
@@ -278,7 +288,7 @@ class ReasoningService extends BaseReasoningService {
model,
finishReason: choice.finish_reason,
hasMessage: !!choice.message,
- response: JSON.stringify(choice).substring(0, 500)
+ response: JSON.stringify(choice).substring(0, 500),
});
throw new Error(`${providerName} returned empty response`);
}
@@ -287,7 +297,7 @@ class ReasoningService extends BaseReasoningService {
model,
responseLength: responseText.length,
tokensUsed: response.usage?.total_tokens || 0,
- success: true
+ success: true,
});
return responseText;
@@ -307,18 +317,18 @@ class ReasoningService extends BaseReasoningService {
agentName,
hasConfig: Object.keys(config).length > 0,
textLength: text.length,
- timestamp: new Date().toISOString()
+ timestamp: new Date().toISOString(),
});
try {
let result: string;
const startTime = Date.now();
-
+
logger.logReasoning("ROUTING_TO_PROVIDER", {
provider,
- model
+ model,
});
-
+
switch (provider) {
case "openai":
result = await this.processWithOpenAI(text, model, agentName, config);
@@ -338,24 +348,24 @@ class ReasoningService extends BaseReasoningService {
default:
throw new Error(`Unsupported reasoning provider: ${provider}`);
}
-
+
const processingTime = Date.now() - startTime;
-
+
logger.logReasoning("PROVIDER_SUCCESS", {
provider,
model,
processingTimeMs: processingTime,
resultLength: result.length,
- resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : "")
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),
});
-
+
return result;
} catch (error) {
logger.logReasoning("PROVIDER_ERROR", {
provider,
model,
error: (error as Error).message,
- stack: (error as Error).stack
+ stack: (error as Error).stack,
});
// Re-throw error with provider context
throw error;
@@ -371,30 +381,31 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning("OPENAI_START", {
model,
agentName,
- hasApiKey: false // Will update after fetching
+ hasApiKey: false, // Will update after fetching
});
-
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
- const apiKey = await this.getApiKey('openai');
-
+ const apiKey = await this.getApiKey("openai");
+
logger.logReasoning("OPENAI_API_KEY", {
hasApiKey: !!apiKey,
- keyLength: apiKey?.length || 0
+ keyLength: apiKey?.length || 0,
});
this.isProcessing = true;
try {
- const systemPrompt = "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
+ const systemPrompt =
+ "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
const userPrompt = this.getReasoningPrompt(text, agentName, config);
// Build input array for Responses API
const input = [
{ role: "system", content: systemPrompt },
- { role: "user", content: userPrompt }
+ { role: "user", content: userPrompt },
];
// Build request body for Responses API
@@ -406,7 +417,7 @@ class ReasoningService extends BaseReasoningService {
};
// Add temperature for older models (GPT-4 and earlier)
- const isOlderModel = model && (model.startsWith('gpt-4') || model.startsWith('gpt-3'));
+ const isOlderModel = model && (model.startsWith("gpt-4") || model.startsWith("gpt-3"));
if (isOlderModel) {
requestBody.temperature = config.temperature || 0.3;
}
@@ -420,69 +431,63 @@ class ReasoningService extends BaseReasoningService {
preference: this.getStoredOpenAiPreference(openAiBase) || null,
});
- const response = await withRetry(
- async () => {
- let lastError: Error | null = null;
+ const response = await withRetry(async () => {
+ let lastError: Error | null = null;
- for (const { url: endpoint, type } of endpointCandidates) {
- try {
- const res = await fetch(endpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiKey}`,
- },
- body: JSON.stringify(requestBody),
- });
+ for (const { url: endpoint, type } of endpointCandidates) {
+ try {
+ const res = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify(requestBody),
+ });
- if (!res.ok) {
- const errorData = await res.json().catch(() => ({ error: res.statusText }));
- const errorMessage =
- errorData.error?.message ||
- errorData.message ||
- `OpenAI API error: ${res.status}`;
-
- const isUnsupportedEndpoint =
- (res.status === 404 || res.status === 405) &&
- type === 'responses';
-
- if (isUnsupportedEndpoint) {
- lastError = new Error(errorMessage);
- this.rememberOpenAiPreference(openAiBase, 'chat');
- logger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
- attemptedEndpoint: endpoint,
- error: errorMessage,
- });
- continue;
- }
-
- throw new Error(errorMessage);
- }
+ if (!res.ok) {
+ const errorData = await res.json().catch(() => ({ error: res.statusText }));
+ const errorMessage =
+ errorData.error?.message || errorData.message || `OpenAI API error: ${res.status}`;
+
+ const isUnsupportedEndpoint =
+ (res.status === 404 || res.status === 405) && type === "responses";
- this.rememberOpenAiPreference(openAiBase, type);
- return res.json();
- } catch (error) {
- lastError = error as Error;
- if (type === 'responses') {
- logger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
+ if (isUnsupportedEndpoint) {
+ lastError = new Error(errorMessage);
+ this.rememberOpenAiPreference(openAiBase, "chat");
+ logger.logReasoning("OPENAI_ENDPOINT_FALLBACK", {
attemptedEndpoint: endpoint,
- error: (error as Error).message,
+ error: errorMessage,
});
continue;
}
- throw error;
+
+ throw new Error(errorMessage);
+ }
+
+ this.rememberOpenAiPreference(openAiBase, type);
+ return res.json();
+ } catch (error) {
+ lastError = error as Error;
+ if (type === "responses") {
+ logger.logReasoning("OPENAI_ENDPOINT_FALLBACK", {
+ attemptedEndpoint: endpoint,
+ error: (error as Error).message,
+ });
+ continue;
}
+ throw error;
}
+ }
- throw lastError || new Error('No OpenAI endpoint responded');
- },
- createApiRetryStrategy()
- );
+ throw lastError || new Error("No OpenAI endpoint responded");
+ }, createApiRetryStrategy());
// Detect the API response format (Responses API vs Chat Completions)
const isResponsesApi = Array.isArray(response?.output);
const isChatCompletions = Array.isArray(response?.choices);
-
+
// Log the raw response for debugging
logger.logReasoning("OPENAI_RAW_RESPONSE", {
model,
@@ -492,7 +497,7 @@ class ReasoningService extends BaseReasoningService {
outputTypes: isResponsesApi ? response.output.map((item: any) => item.type) : undefined,
hasChoices: isChatCompletions,
choicesLength: isChatCompletions ? response.choices.length : 0,
- usage: response.usage
+ usage: response.usage,
});
// Extract text from the Responses API or Chat Completions formats
@@ -543,31 +548,31 @@ class ReasoningService extends BaseReasoningService {
}
}
}
-
+
logger.logReasoning("OPENAI_RESPONSE", {
model,
responseLength: responseText.length,
tokensUsed: response.usage?.total_tokens || 0,
success: true,
- isEmpty: responseText.length === 0
+ isEmpty: responseText.length === 0,
});
-
+
// If we got an empty response, return the original text as fallback
if (!responseText) {
logger.logReasoning("OPENAI_EMPTY_RESPONSE_FALLBACK", {
model,
originalTextLength: text.length,
- reason: "Empty response from API"
+ reason: "Empty response from API",
});
return text; // Return original text if API returns nothing
}
-
+
return responseText;
} catch (error) {
logger.logReasoning("OPENAI_ERROR", {
model,
error: (error as Error).message,
- errorType: (error as Error).name
+ errorType: (error as Error).name,
});
throw error;
} finally {
@@ -584,42 +589,47 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning("ANTHROPIC_START", {
model,
agentName,
- environment: typeof window !== 'undefined' ? 'browser' : 'node'
+ environment: typeof window !== "undefined" ? "browser" : "node",
});
-
+
// Use IPC to communicate with main process for Anthropic API
- if (typeof window !== 'undefined' && window.electronAPI) {
+ if (typeof window !== "undefined" && window.electronAPI) {
const startTime = Date.now();
-
+
logger.logReasoning("ANTHROPIC_IPC_CALL", {
model,
- textLength: text.length
+ textLength: text.length,
});
-
- const result = await window.electronAPI.processAnthropicReasoning(text, model, agentName, config);
-
+
+ const result = await window.electronAPI.processAnthropicReasoning(
+ text,
+ model,
+ agentName,
+ config
+ );
+
const processingTime = Date.now() - startTime;
-
+
if (result.success) {
logger.logReasoning("ANTHROPIC_SUCCESS", {
model,
processingTimeMs: processingTime,
- resultLength: result.text.length
+ resultLength: result.text.length,
});
return result.text;
} else {
logger.logReasoning("ANTHROPIC_ERROR", {
model,
processingTimeMs: processingTime,
- error: result.error
+ error: result.error,
});
throw new Error(result.error);
}
} else {
logger.logReasoning("ANTHROPIC_UNAVAILABLE", {
- reason: 'Not in Electron environment'
+ reason: "Not in Electron environment",
});
- throw new Error('Anthropic reasoning is not available in this environment');
+ throw new Error("Anthropic reasoning is not available in this environment");
}
}
@@ -632,43 +642,43 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning("LOCAL_START", {
model,
agentName,
- environment: typeof window !== 'undefined' ? 'browser' : 'node'
+ environment: typeof window !== "undefined" ? "browser" : "node",
});
-
+
// Instead of importing directly, we'll use IPC to communicate with main process
// For local models, we need to use IPC to communicate with the main process
- if (typeof window !== 'undefined' && window.electronAPI) {
+ if (typeof window !== "undefined" && window.electronAPI) {
const startTime = Date.now();
-
+
logger.logReasoning("LOCAL_IPC_CALL", {
model,
- textLength: text.length
+ textLength: text.length,
});
-
+
const result = await window.electronAPI.processLocalReasoning(text, model, agentName, config);
-
+
const processingTime = Date.now() - startTime;
-
+
if (result.success) {
logger.logReasoning("LOCAL_SUCCESS", {
model,
processingTimeMs: processingTime,
- resultLength: result.text.length
+ resultLength: result.text.length,
});
return result.text;
} else {
logger.logReasoning("LOCAL_ERROR", {
model,
processingTimeMs: processingTime,
- error: result.error
+ error: result.error,
});
throw new Error(result.error);
}
} else {
logger.logReasoning("LOCAL_UNAVAILABLE", {
- reason: 'Not in Electron environment'
+ reason: "Not in Electron environment",
});
- throw new Error('Local reasoning is not available in this environment');
+ throw new Error("Local reasoning is not available in this environment");
}
}
@@ -681,109 +691,114 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning("GEMINI_START", {
model,
agentName,
- hasApiKey: false
+ hasApiKey: false,
});
-
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
- const apiKey = await this.getApiKey('gemini');
-
+ const apiKey = await this.getApiKey("gemini");
+
logger.logReasoning("GEMINI_API_KEY", {
hasApiKey: !!apiKey,
- keyLength: apiKey?.length || 0
+ keyLength: apiKey?.length || 0,
});
this.isProcessing = true;
try {
- const systemPrompt = "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
+ const systemPrompt =
+ "You are a dictation assistant. Clean up text by fixing grammar and punctuation. Output ONLY the cleaned text without any explanations, options, or commentary.";
const userPrompt = this.getReasoningPrompt(text, agentName, config);
const requestBody = {
- contents: [{
- parts: [{
- text: `${systemPrompt}\n\n${userPrompt}`
- }]
- }],
+ contents: [
+ {
+ parts: [
+ {
+ text: `${systemPrompt}\n\n${userPrompt}`,
+ },
+ ],
+ },
+ ],
generationConfig: {
temperature: config.temperature || 0.3,
- maxOutputTokens: config.maxTokens || Math.max(
- 2000, // Gemini 2.5 Pro needs more tokens for its thinking process
- this.calculateMaxTokens(
- text.length,
- TOKEN_LIMITS.MIN_TOKENS_GEMINI,
- TOKEN_LIMITS.MAX_TOKENS_GEMINI,
- TOKEN_LIMITS.TOKEN_MULTIPLIER
- )
- ),
+ maxOutputTokens:
+ config.maxTokens ||
+ Math.max(
+ 2000, // Gemini 2.5 Pro needs more tokens for its thinking process
+ this.calculateMaxTokens(
+ text.length,
+ TOKEN_LIMITS.MIN_TOKENS_GEMINI,
+ TOKEN_LIMITS.MAX_TOKENS_GEMINI,
+ TOKEN_LIMITS.TOKEN_MULTIPLIER
+ )
+ ),
},
};
let response: any;
try {
- response = await withRetry(
- async () => {
- logger.logReasoning("GEMINI_REQUEST", {
- endpoint: `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`,
- model,
- hasApiKey: !!apiKey,
- requestBody: JSON.stringify(requestBody).substring(0, 200)
- });
-
- const res = await fetch(
- `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "x-goog-api-key": apiKey,
- },
- body: JSON.stringify(requestBody),
- }
- );
+ response = await withRetry(async () => {
+ logger.logReasoning("GEMINI_REQUEST", {
+ endpoint: `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`,
+ model,
+ hasApiKey: !!apiKey,
+ requestBody: JSON.stringify(requestBody).substring(0, 200),
+ });
- if (!res.ok) {
- const errorText = await res.text();
- let errorData: any = { error: res.statusText };
-
- try {
- errorData = JSON.parse(errorText);
- } catch {
- errorData = { error: errorText || res.statusText };
- }
-
- logger.logReasoning("GEMINI_API_ERROR_DETAIL", {
- status: res.status,
- statusText: res.statusText,
- error: errorData,
- errorMessage: errorData.error?.message || errorData.message || errorData.error,
- fullResponse: errorText.substring(0, 500)
- });
-
- const errorMessage = errorData.error?.message || errorData.message || errorData.error || `Gemini API error: ${res.status}`;
- throw new Error(errorMessage);
+ const res = await fetch(`${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-goog-api-key": apiKey,
+ },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorText = await res.text();
+ let errorData: any = { error: res.statusText };
+
+ try {
+ errorData = JSON.parse(errorText);
+ } catch {
+ errorData = { error: errorText || res.statusText };
}
- const jsonResponse = await res.json();
-
- logger.logReasoning("GEMINI_RAW_RESPONSE", {
- hasResponse: !!jsonResponse,
- responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],
- hasCandidates: !!jsonResponse?.candidates,
- candidatesLength: jsonResponse?.candidates?.length || 0,
- fullResponse: JSON.stringify(jsonResponse).substring(0, 500)
+ logger.logReasoning("GEMINI_API_ERROR_DETAIL", {
+ status: res.status,
+ statusText: res.statusText,
+ error: errorData,
+ errorMessage: errorData.error?.message || errorData.message || errorData.error,
+ fullResponse: errorText.substring(0, 500),
});
-
- return jsonResponse;
- },
- createApiRetryStrategy()
- );
+
+ const errorMessage =
+ errorData.error?.message ||
+ errorData.message ||
+ errorData.error ||
+ `Gemini API error: ${res.status}`;
+ throw new Error(errorMessage);
+ }
+
+ const jsonResponse = await res.json();
+
+ logger.logReasoning("GEMINI_RAW_RESPONSE", {
+ hasResponse: !!jsonResponse,
+ responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],
+ hasCandidates: !!jsonResponse?.candidates,
+ candidatesLength: jsonResponse?.candidates?.length || 0,
+ fullResponse: JSON.stringify(jsonResponse).substring(0, 500),
+ });
+
+ return jsonResponse;
+ }, createApiRetryStrategy());
} catch (fetchError) {
logger.logReasoning("GEMINI_FETCH_ERROR", {
error: (fetchError as Error).message,
- stack: (fetchError as Error).stack
+ stack: (fetchError as Error).stack,
});
throw fetchError;
}
@@ -794,11 +809,11 @@ class ReasoningService extends BaseReasoningService {
model,
response: JSON.stringify(response).substring(0, 500),
hasCandidate: !!response.candidates,
- candidateCount: response.candidates?.length || 0
+ candidateCount: response.candidates?.length || 0,
});
throw new Error("Invalid response structure from Gemini API");
}
-
+
// Check if the response has actual content
const candidate = response.candidates[0];
if (!candidate.content?.parts?.[0]?.text) {
@@ -807,31 +822,33 @@ class ReasoningService extends BaseReasoningService {
finishReason: candidate.finishReason,
hasContent: !!candidate.content,
hasParts: !!candidate.content?.parts,
- response: JSON.stringify(candidate).substring(0, 500)
+ response: JSON.stringify(candidate).substring(0, 500),
});
-
+
// If finish reason is MAX_TOKENS, the model hit its limit
if (candidate.finishReason === "MAX_TOKENS") {
- throw new Error("Gemini reached token limit before generating response. Try a shorter input or increase max tokens.");
+ throw new Error(
+ "Gemini reached token limit before generating response. Try a shorter input or increase max tokens."
+ );
}
throw new Error("Gemini returned empty response");
}
-
+
const responseText = candidate.content.parts[0].text.trim();
-
+
logger.logReasoning("GEMINI_RESPONSE", {
model,
responseLength: responseText.length,
tokensUsed: response.usageMetadata?.totalTokenCount || 0,
- success: true
+ success: true,
});
-
+
return responseText;
} catch (error) {
logger.logReasoning("GEMINI_ERROR", {
model,
error: (error as Error).message,
- errorType: (error as Error).name
+ errorType: (error as Error).name,
});
throw error;
} finally {
@@ -851,17 +868,25 @@ class ReasoningService extends BaseReasoningService {
throw new Error("Already processing a request");
}
- const apiKey = await this.getApiKey('groq');
+ const apiKey = await this.getApiKey("groq");
this.isProcessing = true;
try {
- const endpoint = buildApiUrl(API_ENDPOINTS.GROQ_BASE, '/chat/completions');
- return await this.callChatCompletionsApi(endpoint, apiKey, model, text, agentName, config, "Groq");
+ const endpoint = buildApiUrl(API_ENDPOINTS.GROQ_BASE, "/chat/completions");
+ return await this.callChatCompletionsApi(
+ endpoint,
+ apiKey,
+ model,
+ text,
+ agentName,
+ config,
+ "Groq"
+ );
} catch (error) {
logger.logReasoning("GROQ_ERROR", {
model,
error: (error as Error).message,
- errorType: (error as Error).name
+ errorType: (error as Error).name,
});
throw error;
} finally {
@@ -883,7 +908,7 @@ class ReasoningService extends BaseReasoningService {
hasAnthropic: !!anthropicKey,
hasGemini: !!geminiKey,
hasGroq: !!groqKey,
- hasLocal: !!localAvailable
+ hasLocal: !!localAvailable,
});
return !!(openaiKey || anthropicKey || geminiKey || groqKey || localAvailable);
@@ -891,7 +916,7 @@ class ReasoningService extends BaseReasoningService {
logger.logReasoning("API_KEY_CHECK_ERROR", {
error: (error as Error).message,
stack: (error as Error).stack,
- name: (error as Error).name
+ name: (error as Error).name,
});
return false;
}
diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.js
index ad0eea501..87e979b78 100644
--- a/src/services/localReasoningBridge.js
+++ b/src/services/localReasoningBridge.js
@@ -10,10 +10,10 @@ class LocalReasoningService {
try {
// Check if llama.cpp is installed
await modelManager.ensureLlamaCpp();
-
+
// Check if at least one model is downloaded
const models = await modelManager.getAllModels();
- return models.some(model => model.isDownloaded);
+ return models.some((model) => model.isDownloaded);
} catch (error) {
return false;
}
@@ -24,9 +24,9 @@ class LocalReasoningService {
modelId,
agentName,
textLength: text.length,
- hasConfig: Object.keys(config).length > 0
+ hasConfig: Object.keys(config).length > 0,
});
-
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
@@ -37,16 +37,16 @@ class LocalReasoningService {
try {
// Get custom prompts from the request context
const customPrompts = config.customPrompts || null;
-
+
// Build the reasoning prompt
const reasoningPrompt = this.getReasoningPrompt(text, agentName, customPrompts);
-
+
debugLogger.logReasoning("LOCAL_BRIDGE_PROMPT", {
promptLength: reasoningPrompt.length,
hasAgentName: !!agentName,
- hasCustomPrompts: !!customPrompts
+ hasCustomPrompts: !!customPrompts,
});
-
+
const inferenceConfig = {
maxTokens: config.maxTokens || this.calculateMaxTokens(text.length),
temperature: config.temperature || 0.7,
@@ -55,37 +55,37 @@ class LocalReasoningService {
repeatPenalty: config.repeatPenalty || 1.1,
contextSize: config.contextSize || 4096,
threads: config.threads || 4,
- systemPrompt: "You are a helpful AI assistant that processes and improves text."
+ systemPrompt: "You are a helpful AI assistant that processes and improves text.",
};
-
+
debugLogger.logReasoning("LOCAL_BRIDGE_INFERENCE", {
modelId,
- config: inferenceConfig
+ config: inferenceConfig,
});
-
+
// Run inference
const result = await modelManager.runInference(modelId, reasoningPrompt, inferenceConfig);
-
+
const processingTime = Date.now() - startTime;
-
+
debugLogger.logReasoning("LOCAL_BRIDGE_SUCCESS", {
modelId,
processingTimeMs: processingTime,
resultLength: result.length,
- resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : "")
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),
});
return result;
} catch (error) {
const processingTime = Date.now() - startTime;
-
+
debugLogger.logReasoning("LOCAL_BRIDGE_ERROR", {
modelId,
processingTimeMs: processingTime,
error: error.message,
- stack: error.stack
+ stack: error.stack,
});
-
+
throw error;
} finally {
this.isProcessing = false;
@@ -113,11 +113,9 @@ class LocalReasoningService {
// Check if agent name is mentioned
if (agentName && text.toLowerCase().includes(agentName.toLowerCase())) {
- return agentPrompt
- .replace(/\{\{agentName\}\}/g, agentName)
- .replace(/\{\{text\}\}/g, text);
+ return agentPrompt.replace(/\{\{agentName\}\}/g, agentName).replace(/\{\{text\}\}/g, text);
}
-
+
return regularPrompt.replace(/\{\{text\}\}/g, text);
}
@@ -127,5 +125,5 @@ class LocalReasoningService {
}
module.exports = {
- default: new LocalReasoningService()
-};
\ No newline at end of file
+ default: new LocalReasoningService(),
+};
diff --git a/src/stores/transcriptionStore.ts b/src/stores/transcriptionStore.ts
index 5e6ee61b3..c7d6b262a 100644
--- a/src/stores/transcriptionStore.ts
+++ b/src/stores/transcriptionStore.ts
@@ -74,9 +74,7 @@ export async function initializeTranscriptions(limit = DEFAULT_LIMIT) {
export function addTranscription(item: TranscriptionItem) {
if (!item) return;
- const withoutDuplicate = transcriptions.filter(
- (existing) => existing.id !== item.id
- );
+ const withoutDuplicate = transcriptions.filter((existing) => existing.id !== item.id);
transcriptions = [item, ...withoutDuplicate].slice(0, currentLimit);
emit();
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 0a062e284..c6af4ead0 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -122,18 +122,12 @@ declare global {
onToggleDictation: (callback: () => void) => (() => void) | void;
// Database operations
- saveTranscription: (
- text: string
- ) => Promise<{ id: number; success: boolean }>;
+ saveTranscription: (text: string) => Promise<{ id: number; success: boolean }>;
getTranscriptions: (limit?: number) => Promise<TranscriptionItem[]>;
clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;
deleteTranscription: (id: number) => Promise<{ success: boolean }>;
- onTranscriptionAdded?: (
- callback: (item: TranscriptionItem) => void
- ) => (() => void) | void;
- onTranscriptionDeleted?: (
- callback: (payload: { id: number }) => void
- ) => (() => void) | void;
+ onTranscriptionAdded?: (callback: (item: TranscriptionItem) => void) => (() => void) | void;
+ onTranscriptionDeleted?: (callback: (payload: { id: number }) => void) => (() => void) | void;
onTranscriptionsCleared?: (
callback: (payload: { cleared: number }) => void
) => (() => void) | void;
@@ -162,9 +156,7 @@ declare global {
text?: string;
error?: string;
}>;
- onNoAudioDetected: (
- callback: (event: any, data?: any) => void
- ) => (() => void) | void;
+ onNoAudioDetected: (callback: (event: any, data?: any) => void) => (() => void) | void;
// Python operations
checkPythonInstallation: () => Promise<PythonInstallation>;
@@ -174,10 +166,7 @@ declare global {
) => (() => void) | void;
// Whisper operations
- transcribeLocalWhisper: (
- audioBlob: Blob | ArrayBuffer,
- options?: any
- ) => Promise<any>;
+ transcribeLocalWhisper: (audioBlob: Blob | ArrayBuffer, options?: any) => Promise<any>;
checkWhisperInstallation: () => Promise<WhisperCheckResult>;
installWhisper: () => Promise<WhisperInstallResult>;
onWhisperInstallProgress: (
@@ -189,9 +178,7 @@ declare global {
) => (() => void) | void;
checkModelStatus: (modelName: string) => Promise<WhisperModelResult>;
listWhisperModels: () => Promise<WhisperModelsListResult>;
- deleteWhisperModel: (
- modelName: string
- ) => Promise<WhisperModelDeleteResult>;
+ deleteWhisperModel: (modelName: string) => Promise<WhisperModelDeleteResult>;
cancelWhisperDownload: () => Promise<{
success: boolean;
message?: string;
@@ -205,17 +192,25 @@ declare global {
modelDelete: (modelId: string) => Promise<void>;
modelDeleteAll: () => Promise<{ success: boolean; error?: string; code?: string }>;
modelCheckRuntime: () => Promise<boolean>;
- onModelDownloadProgress: (
- callback: (event: any, data: any) => void
- ) => (() => void) | void;
-
+ onModelDownloadProgress: (callback: (event: any, data: any) => void) => (() => void) | void;
+
// Local reasoning
- processLocalReasoning: (text: string, modelId: string, agentName: string | null, config: any) => Promise<{ success: boolean; text?: string; error?: string }>;
+ processLocalReasoning: (
+ text: string,
+ modelId: string,
+ agentName: string | null,
+ config: any
+ ) => Promise<{ success: boolean; text?: string; error?: string }>;
checkLocalReasoningAvailable: () => Promise<boolean>;
-
+
// Anthropic reasoning
- processAnthropicReasoning: (text: string, modelId: string, agentName: string | null, config: any) => Promise<{ success: boolean; text?: string; error?: string }>;
-
+ processAnthropicReasoning: (
+ text: string,
+ modelId: string,
+ agentName: string | null,
+ config: any
+ ) => Promise<{ success: boolean; text?: string; error?: string }>;
+
// llama.cpp management
llamaCppCheck: () => Promise<{ isInstalled: boolean; version?: string }>;
llamaCppInstall: () => Promise<{ success: boolean; error?: string }>;
@@ -246,36 +241,26 @@ declare global {
getUpdateInfo: () => Promise<UpdateInfoResult | null>;
// Update event listeners
- onUpdateAvailable: (
- callback: (event: any, info: any) => void
- ) => (() => void) | void;
- onUpdateNotAvailable: (
- callback: (event: any, info: any) => void
- ) => (() => void) | void;
- onUpdateDownloaded: (
- callback: (event: any, info: any) => void
- ) => (() => void) | void;
+ onUpdateAvailable: (callback: (event: any, info: any) => void) => (() => void) | void;
+ onUpdateNotAvailable: (callback: (event: any, info: any) => void) => (() => void) | void;
+ onUpdateDownloaded: (callback: (event: any, info: any) => void) => (() => void) | void;
onUpdateDownloadProgress: (
callback: (event: any, progressObj: any) => void
) => (() => void) | void;
- onUpdateError: (
- callback: (event: any, error: any) => void
- ) => (() => void) | void;
+ onUpdateError: (callback: (event: any, error: any) => void) => (() => void) | void;
// Settings management (used by OnboardingFlow but not in preload.js)
saveSettings?: (settings: SaveSettings) => Promise<void>;
// External URL operations
- openExternal: (
- url: string
- ) => Promise<{ success: boolean; error?: string } | void>;
+ openExternal: (url: string) => Promise<{ success: boolean; error?: string } | void>;
// Event listener cleanup
removeAllListeners: (channel: string) => void;
// Hotkey management
updateHotkey: (key: string) => Promise<{ success: boolean; message: string }>;
-
+
// Gemini API key management
getGeminiKey: () => Promise<string | null>;
saveGeminiKey: (key: string) => Promise<void>;
@@ -293,7 +278,7 @@ declare global {
scope?: string;
source?: string;
}) => Promise<void>;
-
+
// FFmpeg availability
checkFFmpegAvailability: () => Promise<boolean>;
@@ -301,7 +286,7 @@ declare global {
openMicrophoneSettings?: () => Promise<{ success: boolean; error?: string }>;
openSoundInputSettings?: () => Promise<{ success: boolean; error?: string }>;
};
-
+
api?: {
sendDebugLog: (message: string) => void;
};
diff --git a/src/updater.js b/src/updater.js
index 58b61a790..c722ac03d 100644
--- a/src/updater.js
+++ b/src/updater.js
@@ -77,13 +77,15 @@ class UpdateManager {
this.lastUpdateInfo = null;
this.notifyRenderers("update-not-available", info);
},
- "error": (err) => {
+ error: (err) => {
console.error("❌ Auto-updater error:", err);
this.isDownloading = false;
this.notifyRenderers("update-error", err);
},
"download-progress": (progressObj) => {
- console.log(`📥 Download progress: ${progressObj.percent.toFixed(2)}% (${(progressObj.transferred / 1024 / 1024).toFixed(2)}MB / ${(progressObj.total / 1024 / 1024).toFixed(2)}MB)`);
+ console.log(
+ `📥 Download progress: ${progressObj.percent.toFixed(2)}% (${(progressObj.transferred / 1024 / 1024).toFixed(2)}MB / ${(progressObj.total / 1024 / 1024).toFixed(2)}MB)`
+ );
this.notifyRenderers("update-download-progress", progressObj);
},
"update-downloaded": (info) => {
@@ -99,7 +101,7 @@ class UpdateManager {
};
}
this.notifyRenderers("update-downloaded", info);
- }
+ },
};
// Register and track event listeners for cleanup
@@ -113,7 +115,11 @@ class UpdateManager {
if (this.mainWindow && !this.mainWindow.isDestroyed() && this.mainWindow.webContents) {
this.mainWindow.webContents.send(channel, data);
}
- if (this.controlPanelWindow && !this.controlPanelWindow.isDestroyed() && this.controlPanelWindow.webContents) {
+ if (
+ this.controlPanelWindow &&
+ !this.controlPanelWindow.isDestroyed() &&
+ this.controlPanelWindow.webContents
+ ) {
this.controlPanelWindow.webContents.send(channel, data);
}
}
@@ -136,7 +142,12 @@ class UpdateManager {
if (result && result.updateInfo) {
console.log("📋 Update available:", result.updateInfo.version);
- console.log("📦 Download size:", result.updateInfo.files?.map(f => `${(f.size / 1024 / 1024).toFixed(2)}MB`).join(", "));
+ console.log(
+ "📦 Download size:",
+ result.updateInfo.files
+ ?.map((f) => `${(f.size / 1024 / 1024).toFixed(2)}MB`)
+ .join(", ")
+ );
return {
updateAvailable: true,
version: result.updateInfo.version,
@@ -155,7 +166,7 @@ class UpdateManager {
console.error("❌ Update check error:", error);
throw error;
}
- }
+ },
},
{
channel: "download-update",
@@ -193,7 +204,7 @@ class UpdateManager {
console.error("❌ Update download error:", error);
throw error;
}
- }
+ },
},
{
channel: "install-update",
@@ -253,7 +264,7 @@ class UpdateManager {
console.error("❌ Update installation error:", error);
throw error;
}
- }
+ },
},
{
channel: "get-app-version",
@@ -265,7 +276,7 @@ class UpdateManager {
console.error("❌ Error getting app version:", error);
throw error;
}
- }
+ },
},
{
channel: "get-update-status",
@@ -280,7 +291,7 @@ class UpdateManager {
console.error("❌ Error getting update status:", error);
throw error;
}
- }
+ },
},
{
channel: "get-update-info",
@@ -291,8 +302,8 @@ class UpdateManager {
console.error("❌ Error getting update info:", error);
throw error;
}
- }
- }
+ },
+ },
];
// Register all handlers and track for cleanup
@@ -308,7 +319,7 @@ class UpdateManager {
// Wait a bit for the app to fully initialize
setTimeout(() => {
console.log("🔄 Checking for updates on startup...");
- autoUpdater.checkForUpdates().catch(err => {
+ autoUpdater.checkForUpdates().catch((err) => {
console.error("Startup update check failed:", err);
});
}, 3000); // Reduced from 5s to 3s for better UX
diff --git a/src/utils.js b/src/utils.js
index 9dfd1252a..cbe81dcf3 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -11,9 +11,7 @@ class AppUtils {
try {
const dbPath = path.join(
app.getPath("userData"),
- process.env.NODE_ENV === "development"
- ? "transcriptions-dev.db"
- : "transcriptions.db"
+ process.env.NODE_ENV === "development" ? "transcriptions-dev.db" : "transcriptions.db"
);
if (fs.existsSync(dbPath)) {
fs.unlinkSync(dbPath);
diff --git a/src/utils/SecureCache.ts b/src/utils/SecureCache.ts
index a9fba6c66..46daf3a0c 100644
--- a/src/utils/SecureCache.ts
+++ b/src/utils/SecureCache.ts
@@ -22,7 +22,7 @@ export class SecureCache<T> {
get(key: string): T | undefined {
const entry = this.cache.get(key);
-
+
if (!entry) {
return undefined;
}
@@ -63,4 +63,4 @@ export class SecureCache<T> {
const interval = setInterval(() => this.cleanup(), intervalMs);
return () => clearInterval(interval);
}
-}
\ No newline at end of file
+}
diff --git a/src/utils/formatBytes.ts b/src/utils/formatBytes.ts
index a05006e93..b01a22811 100644
--- a/src/utils/formatBytes.ts
+++ b/src/utils/formatBytes.ts
@@ -8,4 +8,4 @@ export function formatBytes(bytes: number, decimals = 2): string {
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
-}
\ No newline at end of file
+}
diff --git a/src/utils/languages.ts b/src/utils/languages.ts
index d1623dc47..0bdfc2ef1 100644
--- a/src/utils/languages.ts
+++ b/src/utils/languages.ts
@@ -129,7 +129,7 @@ export const REASONING_PROVIDERS = {
value: "gpt-4o",
label: "GPT-4o",
description: "Multimodal with vision support",
- }
+ },
],
},
anthropic: {
@@ -225,7 +225,7 @@ export const REASONING_PROVIDERS = {
// Dynamically populate local models from registry
const localModels = modelRegistry.getAllModels();
-REASONING_PROVIDERS.local.models = localModels.map(model => ({
+REASONING_PROVIDERS.local.models = localModels.map((model) => ({
value: model.id,
label: model.name,
description: `${model.description} (${model.size})`,
@@ -255,12 +255,24 @@ export const getModelProvider = (modelId: string): string => {
if (!model) {
if (modelId.includes("claude")) return "anthropic";
if (modelId.includes("gemini") && !modelId.includes("gemma")) return "gemini";
- if (modelId.includes("gpt") || modelId.includes("o3") || modelId.includes("o4") || modelId.includes("o1")) return "openai";
+ if (
+ modelId.includes("gpt") ||
+ modelId.includes("o3") ||
+ modelId.includes("o4") ||
+ modelId.includes("o1")
+ )
+ return "openai";
// Groq-specific models (these run on Groq cloud, not local)
- if (modelId.includes("qwen/") || modelId.includes("llama") || modelId.includes("mixtral") || modelId.includes("gemma")) return "groq";
+ if (
+ modelId.includes("qwen/") ||
+ modelId.includes("llama") ||
+ modelId.includes("mixtral") ||
+ modelId.includes("gemma")
+ )
+ return "groq";
// Other qwen, llama, mistral without slash are local
if (modelId.includes("qwen") || modelId.includes("mistral")) return "local";
}
return model?.provider || "openai";
-};
\ No newline at end of file
+};
diff --git a/src/utils/logger.ts b/src/utils/logger.ts
index 7c353e8c4..36c14bd93 100644
--- a/src/utils/logger.ts
+++ b/src/utils/logger.ts
@@ -87,20 +87,13 @@ const log = async (level: LogLevel, message: string, meta?: any, scope?: string)
};
const logger = {
- trace: (message: string, meta?: any, scope?: string) =>
- log("trace", message, meta, scope),
- debug: (message: string, meta?: any, scope?: string) =>
- log("debug", message, meta, scope),
- info: (message: string, meta?: any, scope?: string) =>
- log("info", message, meta, scope),
- warn: (message: string, meta?: any, scope?: string) =>
- log("warn", message, meta, scope),
- error: (message: string, meta?: any, scope?: string) =>
- log("error", message, meta, scope),
- fatal: (message: string, meta?: any, scope?: string) =>
- log("fatal", message, meta, scope),
- logReasoning: (stage: string, details?: any) =>
- log("debug", stage, details, "reasoning"),
+ trace: (message: string, meta?: any, scope?: string) => log("trace", message, meta, scope),
+ debug: (message: string, meta?: any, scope?: string) => log("debug", message, meta, scope),
+ info: (message: string, meta?: any, scope?: string) => log("info", message, meta, scope),
+ warn: (message: string, meta?: any, scope?: string) => log("warn", message, meta, scope),
+ error: (message: string, meta?: any, scope?: string) => log("error", message, meta, scope),
+ fatal: (message: string, meta?: any, scope?: string) => log("fatal", message, meta, scope),
+ logReasoning: (stage: string, details?: any) => log("debug", stage, details, "reasoning"),
refreshLogLevel: () => {
cachedLevel = null;
levelPromise = null;
diff --git a/src/utils/process.js b/src/utils/process.js
index 39f679ff9..b31dff321 100644
--- a/src/utils/process.js
+++ b/src/utils/process.js
@@ -6,15 +6,15 @@ const { spawn } = require("child_process");
* @param {ChildProcess} proc - The process to kill
* @param {string} signal - Signal name ('SIGTERM' or 'SIGKILL')
*/
-function killProcess(proc, signal = 'SIGTERM') {
+function killProcess(proc, signal = "SIGTERM") {
if (!proc || proc.exitCode !== null) return;
try {
- if (process.platform === 'win32') {
+ if (process.platform === "win32") {
// On Windows, just call kill() without a signal - it terminates the process
// For SIGKILL equivalent, we use taskkill /F for forceful termination
- if (signal === 'SIGKILL') {
- spawn('taskkill', ['/pid', proc.pid.toString(), '/f', '/t'], { detached: true });
+ if (signal === "SIGKILL") {
+ spawn("taskkill", ["/pid", proc.pid.toString(), "/f", "/t"], { detached: true });
} else {
proc.kill();
}
@@ -29,16 +29,16 @@ function killProcess(proc, signal = 'SIGTERM') {
// Timeout constants
const TIMEOUTS = {
- QUICK_CHECK: 5000, // 5 seconds for quick checks
- COMMAND: 30000, // 30 seconds for general commands
- INSTALL: 300000, // 5 minutes for installations
- DOWNLOAD: 600000, // 10 minutes for downloads
- PIP_UPGRADE: 60000, // 1 minute for pip upgrade
+ QUICK_CHECK: 5000, // 5 seconds for quick checks
+ COMMAND: 30000, // 30 seconds for general commands
+ INSTALL: 300000, // 5 minutes for installations
+ DOWNLOAD: 600000, // 10 minutes for downloads
+ PIP_UPGRADE: 60000, // 1 minute for pip upgrade
TRANSCRIPTION: 1200000, // 20 minutes for whisper transcription (long audio files)
};
// Command whitelist for shell operations
-const SAFE_SHELL_COMMANDS = new Set(['brew', 'apt', 'yum', 'pacman']);
+const SAFE_SHELL_COMMANDS = new Set(["brew", "apt", "yum", "pacman"]);
/**
* Validate command arguments for safety
@@ -52,11 +52,11 @@ function validateCommand(cmd, args, shell) {
if (shell && !SAFE_SHELL_COMMANDS.has(cmd)) {
throw new Error(`Shell execution not allowed for command: ${cmd}`);
}
-
+
// Check for dangerous characters in arguments
const dangerousChars = /[;&|`$<>]/;
- if (args.some(arg => dangerousChars.test(arg))) {
- throw new Error('Command arguments contain potentially dangerous characters');
+ if (args.some((arg) => dangerousChars.test(arg))) {
+ throw new Error("Command arguments contain potentially dangerous characters");
}
}
@@ -71,10 +71,10 @@ function validateCommand(cmd, args, shell) {
*/
async function runCommand(cmd, args = [], options = {}) {
const { timeout = TIMEOUTS.COMMAND, shell = false } = options;
-
+
// Validate command for security
validateCommand(cmd, args, shell);
-
+
return new Promise((resolve, reject) => {
let childProc;
let stdout = "";
@@ -96,10 +96,10 @@ async function runCommand(cmd, args = [], options = {}) {
}
if (childProc && !completed) {
completed = true;
- killProcess(childProc, 'SIGTERM');
+ killProcess(childProc, "SIGTERM");
// Force kill after 5 seconds if still running
setTimeout(() => {
- killProcess(childProc, 'SIGKILL');
+ killProcess(childProc, "SIGKILL");
}, 5000);
}
};
@@ -142,4 +142,4 @@ module.exports = {
runCommand,
killProcess,
TIMEOUTS,
-};
\ No newline at end of file
+};
diff --git a/src/utils/retry.ts b/src/utils/retry.ts
index 22f4396d0..3c0967068 100644
--- a/src/utils/retry.ts
+++ b/src/utils/retry.ts
@@ -8,10 +8,7 @@ export interface RetryOptions {
shouldRetry?: (error: any) => boolean;
}
-export async function withRetry<T>(
- fn: () => Promise<T>,
- options: RetryOptions = {}
-): Promise<T> {
+export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
const {
maxRetries = RETRY_CONFIG.MAX_RETRIES,
initialDelay = RETRY_CONFIG.INITIAL_DELAY,
@@ -28,13 +25,13 @@ export async function withRetry<T>(
return await fn();
} catch (error) {
lastError = error;
-
+
if (attempt === maxRetries || !shouldRetry(error)) {
throw error;
}
// Wait before retrying with exponential backoff
- await new Promise(resolve => setTimeout(resolve, delay));
+ await new Promise((resolve) => setTimeout(resolve, delay));
delay = Math.min(delay * backoffMultiplier, maxDelay);
}
}
@@ -48,7 +45,7 @@ export function createApiRetryStrategy() {
shouldRetry: (error: any) => {
// Retry on network errors or 5xx status codes
if (!error.response) return true; // Network error
-
+
const status = error.response?.status || error.status;
return status >= 500 && status < 600;
},
@@ -60,10 +57,10 @@ export function createFileRetryStrategy() {
return {
shouldRetry: (error: any) => {
// Retry on temporary file system errors
- const retriableErrors = ['EBUSY', 'ENOENT', 'EPERM', 'EAGAIN'];
+ const retriableErrors = ["EBUSY", "ENOENT", "EPERM", "EAGAIN"];
return retriableErrors.includes(error.code);
},
maxRetries: 2,
initialDelay: 500,
};
-}
\ No newline at end of file
+}