Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
Note taker (#261)
Gabriel Stein40043941534d
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex d72ca4032..14a872ed1 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -219,6 +219,13 @@ jobs:APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ - name: Upload arch-specific update metadata+ env:+ GH_TOKEN: ${{ secrets.GH_TOKEN }}+ run: |+ cp dist/latest-mac.yml "dist/latest-${{ matrix.arch }}-mac.yml"+ gh release upload "${{ github.ref_name }}" "dist/latest-${{ matrix.arch }}-mac.yml" --clobber+- name: Cleanup Certificatesif: always()run: |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 971bd5c58..6af9895e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,7 +48,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [1.4.8] - 2026-02-12### Added-+- **Referral Program**: Invite friends to earn free Pro months with referral dashboard, email invitations, invite tracking with status badges, and animated spectrogram share card with unique referral code+- **Notes System**: Added sidebar navigation with notes system and dictionary view for organizing transcriptions+- **Folder Organization**: Notes can be organized into custom folders with a default Personal folder, folder management UI, and folder-aware note filtering. Upload flow now includes folder selection- **Internationalization v1**: Full desktop localization across auth, settings, hooks, and UI with centralized renderer locale resources (#258)- **Chinese Language Split**: Split Chinese into Simplified (zh-CN) and Traditional (zh-TW) with tailored AI instructions and one-time migration for existing users (#267)- **Russian Interface Language**: Added Russian to interface language options@@ -76,6 +78,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Archive Extraction Retry**: Reuse existing archive on extraction retry with improved error handling- **Email Verification Polling**: Pass email param in verification polling and stop on 401 responses- **Auth Build Bundling**: Added @neondatabase/auth packages to rollup externals for correct production bundling (#256)+- **Neon Auth Build Config**: Fixed Vite build configuration for Neon Auth packages (#266)### Changeddiff --git a/CLAUDE.md b/CLAUDE.mdindex 7f85bddc2..075254c29 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -398,12 +398,37 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's## Development Guidelines+### Internationalization (i18n) — REQUIRED++All user-facing strings **must** use the i18n system. Never hardcode UI text in components.++**Setup**: react-i18next (v15) with i18next (v25). Translation files in `src/locales/{lang}/translation.json`.++**Supported languages**: en, es, fr, de, pt, it, ru, zh-CN, zh-TW++**How to use**:+```tsx+import { useTranslation } from "react-i18next";++const { t } = useTranslation();+// Simple: t("notes.list.title")+// With interpolation: t("notes.upload.using", { model: "Whisper" })+```++**Rules**:+1. Every new UI string must have a translation key in `en/translation.json` and all other language files+2. Use `useTranslation()` hook in components and hooks+3. Keep `{{variable}}` interpolation syntax for dynamic values+4. Do NOT translate: brand names (OpenWhispr, Pro), technical terms (Markdown, Signal ID), format names (MP3, WAV), AI system prompts+5. Group keys by feature area (e.g., `notes.editor.*`, `referral.toasts.*`)+### Adding New Features1. **New IPC Channel**: Add to both ipcHandlers.js and preload.js2. **New Setting**: Update useSettings.ts and SettingsPage.tsx3. **New UI Component**: Follow shadcn/ui patterns in src/components/ui4. **New Manager**: Create in src/helpers/, initialize in main.js+5. **New UI Strings**: Add translation keys to all 9 language files (see i18n section above)### Testing Checklist@@ -528,7 +553,7 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's- Streaming transcription support- Custom wake word detection-- Multi-language UI+- ~~Multi-language UI~~ (implemented — 9 languages via react-i18next)- Cloud model selection- Batch transcription- Export formats beyond clipboarddiff --git a/main.js b/main.jsindex 6f0a48889..917ee200b 100644--- a/main.js+++ b/main.js@@ -327,6 +327,7 @@ function navigateControlPanelWithVerifier(verifier) {windowManager.controlPanelWindow.focus();}+function handleOAuthDeepLink(deepLinkUrl) {try {const parsed = new URL(deepLinkUrl);@@ -524,18 +525,29 @@ async function startApp() {const POST_STOP_COOLDOWN_MS = 300;globeKeyManager.on("globe-down", async () => {+ const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();+ const mainWindowLive = isLiveWindow(windowManager.mainWindow);+ debugLogger?.debug("[Globe] globe-down received", {+ currentHotkey,+ mainWindowLive,+ activationMode: mainWindowLive ? windowManager.getActivationMode() : "n/a",+ });+// Forward to control panel for hotkey captureif (isLiveWindow(windowManager.controlPanelWindow)) {windowManager.controlPanelWindow.webContents.send("globe-key-pressed");}// Handle dictation if Globe is the current hotkey- if (hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey() === "GLOBE") {- if (isLiveWindow(windowManager.mainWindow)) {+ if (currentHotkey === "GLOBE") {+ if (mainWindowLive) {const activationMode = windowManager.getActivationMode();if (activationMode === "push") {const now = Date.now();- if (now - globeLastStopTime < POST_STOP_COOLDOWN_MS) return;+ if (now - globeLastStopTime < POST_STOP_COOLDOWN_MS) {+ debugLogger?.debug("[Globe] Ignored — cooldown active");+ return;+ }windowManager.showDictationPanel();const pressTime = now;globeKeyDownTime = pressTime;@@ -543,6 +555,7 @@ async function startApp() {setTimeout(async () => {if (globeKeyDownTime === pressTime && !globeKeyIsRecording) {globeKeyIsRecording = true;+ debugLogger?.debug("[Globe] Starting dictation (push hold)");windowManager.sendStartDictation();}}, MIN_HOLD_DURATION_MS);@@ -550,11 +563,17 @@ async function startApp() {windowManager.showDictationPanel();windowManager.mainWindow.webContents.send("toggle-dictation");}+ } else {+ debugLogger?.debug("[Globe] Ignored — mainWindow not live");}+ } else {+ debugLogger?.debug("[Globe] Ignored — hotkey is not GLOBE", { currentHotkey });}});globeKeyManager.on("globe-up", async () => {+ debugLogger?.debug("[Globe] globe-up received", { wasRecording: globeKeyIsRecording });+// Forward to control panel for hotkey capture (Fn key released)if (isLiveWindow(windowManager.controlPanelWindow)) {windowManager.controlPanelWindow.webContents.send("globe-key-released");@@ -568,6 +587,7 @@ async function startApp() {globeLastStopTime = Date.now();if (globeKeyIsRecording) {globeKeyIsRecording = false;+ debugLogger?.debug("[Globe] Stopping dictation (push release)");windowManager.sendStopDictation();}}@@ -615,20 +635,33 @@ async function startApp() {globeKeyManager.on("right-modifier-up", async (modifier) => {const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();- if (currentHotkey !== modifier) return;- if (!isLiveWindow(windowManager.mainWindow)) return;- const activationMode = windowManager.getActivationMode();- if (activationMode === "push") {- rightModDownTime = 0;- rightModLastStopTime = Date.now();- if (rightModIsRecording) {- rightModIsRecording = false;- windowManager.sendStopDictation();- } else {- windowManager.hideDictationPanel();+ if (currentHotkey === modifier) {+ if (!isLiveWindow(windowManager.mainWindow)) return;++ const activationMode = windowManager.getActivationMode();+ if (activationMode === "push") {+ rightModDownTime = 0;+ rightModLastStopTime = Date.now();+ if (rightModIsRecording) {+ rightModIsRecording = false;+ windowManager.sendStopDictation();+ } else {+ windowManager.hideDictationPanel();+ }}}++ const rightModToBase = {+ RightCommand: "command",+ RightOption: "option",+ RightControl: "control",+ RightShift: "shift",+ };+ const baseMod = rightModToBase[modifier];+ if (baseMod && windowManager?.handleMacPushModifierUp) {+ windowManager.handleMacPushModifierUp(baseMod);+ }});globeKeyManager.start();diff --git a/package-lock.json b/package-lock.jsonindex 3b54ab006..c540df7f8 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,6 +10,7 @@"hasInstallScript": true,"license": "MIT","dependencies": {+ "@neondatabase/auth": "^0.1.0-beta.21","@neondatabase/neon-js": "^0.1.0-beta.22","@radix-ui/react-accordion": "^1.1.2","@radix-ui/react-dialog": "^1.1.14",@@ -38,7 +39,8 @@"tar": "^7.4.3","tw-animate-css": "^1.3.4","unzipper": "^0.12.3",- "ws": "^8.19.0"+ "ws": "^8.19.0",+ "zustand": "^5.0.11"},"devDependencies": {"@electron/notarize": "^3.0.1",@@ -16793,6 +16795,35 @@"url": "https://github.com/sponsors/colinhacks"}},+ "node_modules/zustand": {+ "version": "5.0.11",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.11.tgz",+ "integrity": "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }+ },"node_modules/zwitch": {"version": "2.0.4","resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",diff --git a/package.json b/package.jsonindex 508f6db89..6d7cc4eed 100644--- a/package.json+++ b/package.json@@ -89,6 +89,7 @@"vite": "^6.3.5"},"dependencies": {+ "@neondatabase/auth": "^0.1.0-beta.21","@neondatabase/neon-js": "^0.1.0-beta.22","@radix-ui/react-accordion": "^1.1.2","@radix-ui/react-dialog": "^1.1.14",@@ -117,6 +118,7 @@"tar": "^7.4.3","tw-animate-css": "^1.3.4","unzipper": "^0.12.3",- "ws": "^8.19.0"+ "ws": "^8.19.0",+ "zustand": "^5.0.11"}}diff --git a/preload.js b/preload.jsindex 9ba7f58b1..35490546c 100644--- a/preload.js+++ b/preload.js@@ -1,4 +1,4 @@-const { contextBridge, ipcRenderer } = require("electron");+const { contextBridge, ipcRenderer, webUtils } = require("electron");/*** Helper to register an IPC listener and return a cleanup function.@@ -39,6 +39,68 @@ contextBridge.exposeInMainWorld("electronAPI", {getDictionary: () => ipcRenderer.invoke("db-get-dictionary"),setDictionary: (words) => ipcRenderer.invoke("db-set-dictionary", words),+ // Note functions+ saveNote: (title, content, noteType, sourceFile, audioDuration, folderId) =>+ ipcRenderer.invoke("db-save-note", title, content, noteType, sourceFile, audioDuration, folderId),+ getNote: (id) => ipcRenderer.invoke("db-get-note", id),+ getNotes: (noteType, limit, folderId) => ipcRenderer.invoke("db-get-notes", noteType, limit, folderId),+ updateNote: (id, updates) => ipcRenderer.invoke("db-update-note", id, updates),+ deleteNote: (id) => ipcRenderer.invoke("db-delete-note", id),+ exportNote: (noteId, format) => ipcRenderer.invoke("export-note", noteId, format),++ // Folder functions+ getFolders: () => ipcRenderer.invoke("db-get-folders"),+ createFolder: (name) => ipcRenderer.invoke("db-create-folder", name),+ deleteFolder: (id) => ipcRenderer.invoke("db-delete-folder", id),+ renameFolder: (id, name) => ipcRenderer.invoke("db-rename-folder", id, name),+ getFolderNoteCounts: () => ipcRenderer.invoke("db-get-folder-note-counts"),++ // Action functions+ getActions: () => ipcRenderer.invoke("db-get-actions"),+ getAction: (id) => ipcRenderer.invoke("db-get-action", id),+ createAction: (name, description, prompt, icon) =>+ ipcRenderer.invoke("db-create-action", name, description, prompt, icon),+ updateAction: (id, updates) => ipcRenderer.invoke("db-update-action", id, updates),+ deleteAction: (id) => ipcRenderer.invoke("db-delete-action", id),++ // Audio file operations+ selectAudioFile: () => ipcRenderer.invoke("select-audio-file"),+ transcribeAudioFile: (filePath, options) =>+ ipcRenderer.invoke("transcribe-audio-file", filePath, options),+ getPathForFile: (file) => webUtils.getPathForFile(file),++ onNoteAdded: (callback) => {+ const listener = (_event, note) => callback?.(note);+ ipcRenderer.on("note-added", listener);+ return () => ipcRenderer.removeListener("note-added", listener);+ },+ onNoteUpdated: (callback) => {+ const listener = (_event, note) => callback?.(note);+ ipcRenderer.on("note-updated", listener);+ return () => ipcRenderer.removeListener("note-updated", listener);+ },+ onNoteDeleted: (callback) => {+ const listener = (_event, data) => callback?.(data);+ ipcRenderer.on("note-deleted", listener);+ return () => ipcRenderer.removeListener("note-deleted", listener);+ },++ onActionCreated: (callback) => {+ const listener = (_event, action) => callback?.(action);+ ipcRenderer.on("action-created", listener);+ return () => ipcRenderer.removeListener("action-created", listener);+ },+ onActionUpdated: (callback) => {+ const listener = (_event, action) => callback?.(action);+ ipcRenderer.on("action-updated", listener);+ return () => ipcRenderer.removeListener("action-updated", listener);+ },+ onActionDeleted: (callback) => {+ const listener = (_event, data) => callback?.(data);+ ipcRenderer.on("action-deleted", listener);+ return () => ipcRenderer.removeListener("action-deleted", listener);+ },+onTranscriptionAdded: (callback) => {const listener = (_event, transcription) => callback?.(transcription);ipcRenderer.on("transcription-added", listener);@@ -230,9 +292,18 @@ contextBridge.exposeInMainWorld("electronAPI", {cloudTranscribe: (audioBuffer, opts) => ipcRenderer.invoke("cloud-transcribe", audioBuffer, opts),cloudReason: (text, opts) => ipcRenderer.invoke("cloud-reason", text, opts),cloudUsage: () => ipcRenderer.invoke("cloud-usage"),- cloudCheckout: () => ipcRenderer.invoke("cloud-checkout"),+ cloudCheckout: (plan) => ipcRenderer.invoke("cloud-checkout", plan),cloudBillingPortal: () => ipcRenderer.invoke("cloud-billing-portal"),+ // Cloud audio file transcription+ transcribeAudioFileCloud: (filePath) => ipcRenderer.invoke("transcribe-audio-file-cloud", filePath),+ transcribeAudioFileByok: (options) => ipcRenderer.invoke("transcribe-audio-file-byok", options),++ // Referral stats+ getReferralStats: () => ipcRenderer.invoke("get-referral-stats"),+ sendReferralInvite: (email) => ipcRenderer.invoke("send-referral-invite", email),+ getReferralInvites: () => ipcRenderer.invoke("get-referral-invites"),+// Assembly AI StreamingassemblyAiStreamingWarmup: (options) =>ipcRenderer.invoke("assemblyai-streaming-warmup", options),diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.cindex 23ef77a50..195ef150d 100644--- a/resources/linux-fast-paste.c+++ b/resources/linux-fast-paste.c@@ -21,7 +21,7 @@ static const char *terminal_classes[] = {"konsole", "gnome-terminal", "terminal", "kitty", "alacritty","terminator", "xterm", "urxvt", "rxvt", "tilix", "terminology","wezterm", "foot", "st", "yakuake", "ghostty", "guake", "tilda",- "hyper", "tabby", "sakura", "warp", NULL+ "hyper", "tabby", "sakura", "warp", "termius", NULL};static int is_terminal(const char *wm_class) {diff --git a/resources/windows-fast-paste.c b/resources/windows-fast-paste.cindex 2272800dc..cf08c737d 100644--- a/resources/windows-fast-paste.c+++ b/resources/windows-fast-paste.c@@ -6,6 +6,10 @@* - Ctrl+V for normal applications* - Ctrl+Shift+V for terminal emulators*+ * Terminal detection uses two strategies:+ * 1. Window class name (fast, works for native terminals)+ * 2. Executable name (fallback, catches Electron-based terminals like Termius)+ ** Compile with: cl /O2 windows-fast-paste.c /Fe:windows-fast-paste.exe user32.lib* Or with MinGW: gcc -O2 windows-fast-paste.c -o windows-fast-paste.exe -luser32*/@@ -29,6 +33,16 @@ static const char* TERMINAL_CLASSES[] = {NULL};+/* Electron-based terminals share Chrome_WidgetWin_1 as window class,+ so we detect them by executable name instead */+static const char* TERMINAL_EXES[] = {+ "termius.exe",+ "tabby.exe",+ "wave.exe",+ "rio.exe",+ NULL+};+static BOOL IsTerminalClass(const char* className) {for (int i = 0; TERMINAL_CLASSES[i] != NULL; i++) {if (_stricmp(className, TERMINAL_CLASSES[i]) == 0) {@@ -38,6 +52,38 @@ static BOOL IsTerminalClass(const char* className) {return FALSE;}+static BOOL GetExeName(HWND hwnd, char* exeName, DWORD exeNameSize) {+ DWORD pid = 0;+ GetWindowThreadProcessId(hwnd, &pid);+ if (pid == 0) return FALSE;++ HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);+ if (!hProcess) return FALSE;++ char exePath[MAX_PATH];+ DWORD pathLen = MAX_PATH;+ BOOL ok = QueryFullProcessImageNameA(hProcess, 0, exePath, &pathLen);+ CloseHandle(hProcess);++ if (!ok || pathLen == 0) return FALSE;++ const char* baseName = strrchr(exePath, '\\');+ baseName = baseName ? baseName + 1 : exePath;++ strncpy(exeName, baseName, exeNameSize - 1);+ exeName[exeNameSize - 1] = '\0';+ return TRUE;+}++static BOOL IsTerminalExe(const char* exeName) {+ for (int i = 0; TERMINAL_EXES[i] != NULL; i++) {+ if (_stricmp(exeName, TERMINAL_EXES[i]) == 0) {+ return TRUE;+ }+ }+ return FALSE;+}+static int SendPasteNormal(void) {INPUT inputs[4];ZeroMemory(inputs, sizeof(inputs));@@ -113,8 +159,18 @@ int main(int argc, char* argv[]) {BOOL isTerminal = IsTerminalClass(className);+ char exeName[MAX_PATH] = {0};+ BOOL gotExeName = GetExeName(hwnd, exeName, sizeof(exeName));++ if (!isTerminal && gotExeName) {+ isTerminal = IsTerminalExe(exeName);+ }+if (detectOnly) {printf("WINDOW_CLASS %s\n", className);+ if (gotExeName) {+ printf("EXE_NAME %s\n", exeName);+ }printf("IS_TERMINAL %s\n", isTerminal ? "true" : "false");fflush(stdout);return 0;diff --git a/src/App.jsx b/src/App.jsxindex ef651f1d2..bb266fd24 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -8,6 +8,7 @@ import { useHotkey } from "./hooks/useHotkey";import { useWindowDrag } from "./hooks/useWindowDrag";import { useAudioRecording } from "./hooks/useAudioRecording";import { useAuth } from "./hooks/useAuth";+import { useSettingsStore } from "./stores/settingsStore";// Sound Wave Icon Component (for idle/hover states)const SoundWaveIcon = ({ size = 16 }) => {@@ -33,7 +34,7 @@ const VoiceWaveIndicator = ({ isListening }) => {{[...Array(4)].map((_, i) => (<divkey={i}- className={`w-0.5 bg-white rounded-full transition-all duration-150 ${+ className={`w-0.5 bg-white rounded-full transition-[height] duration-150 ${isListening ? "animate-pulse h-4" : "h-2"}`}style={{@@ -83,10 +84,9 @@ export default function App() {const [dragStartPos, setDragStartPos] = useState(null);const [hasDragged, setHasDragged] = useState(false);- // Floating icon auto-hide setting (read from localStorage, synced via IPC)- const [floatingIconAutoHide, setFloatingIconAutoHide] = useState(- () => localStorage.getItem("floatingIconAutoHide") === "true"- );+ // Floating icon auto-hide setting (read from store, synced via IPC)+ const floatingIconAutoHide = useSettingsStore((s) => s.floatingIconAutoHide);+ const setFloatingIconAutoHide = useSettingsStore((s) => s.setFloatingIconAutoHide);const prevAutoHideRef = useRef(floatingIconAutoHide);const setWindowInteractivity = React.useCallback((shouldCapture) => {@@ -301,7 +301,7 @@ export default function App() {e.stopPropagation();isRecording ? cancelRecording() : cancelProcessing();}}- className="group/cancel w-5 h-5 rounded-full bg-surface-2/90 hover:bg-destructive border border-border hover:border-destructive/70 flex items-center justify-center transition-all duration-150 shadow-sm backdrop-blur-sm"+ className="group/cancel w-5 h-5 rounded-full bg-surface-2/90 hover:bg-destructive border border-border hover:border-destructive/70 flex items-center justify-center transition-colors duration-150 shadow-sm backdrop-blur-sm"><Xsize={10}diff --git a/src/components/AuthenticationStep.tsx b/src/components/AuthenticationStep.tsxindex 92527d7f1..bc5855ae7 100644--- a/src/components/AuthenticationStep.tsx+++ b/src/components/AuthenticationStep.tsx@@ -335,7 +335,7 @@ export default function AuthenticationStep({</div><div className="bg-warning/5 p-2.5 rounded border border-warning/20">- <p className="text-[10px] text-warning text-center leading-snug">+ <p className="text-xs text-warning text-center leading-snug">{t("auth.cloudNotConfigured")}</p></div>@@ -401,7 +401,7 @@ export default function AuthenticationStep({<buttontype="button"onClick={handleBack}- className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"><ChevronLeft className="w-3 h-3" />{t("auth.common.back")}@@ -445,7 +445,7 @@ export default function AuthenticationStep({/>{authMode === "sign-up" && (- <p className="text-[9px] text-muted-foreground/70 leading-tight">+ <p className="text-xs text-muted-foreground/70 leading-tight">{t("auth.passwordForm.passwordMinLength")}</p>)}@@ -454,7 +454,7 @@ export default function AuthenticationStep({<buttontype="button"onClick={handleForgotPassword}- className="text-[10px] text-primary hover:text-primary/80 transition-colors text-left"+ className="text-xs text-primary hover:text-primary/80 transition-colors text-left"disabled={isSubmitting}>{t("auth.passwordForm.forgotPassword")}@@ -464,7 +464,7 @@ export default function AuthenticationStep({{error && (<div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5"><AlertCircle className="w-3 h-3 text-destructive shrink-0" />- <p className="text-[10px] text-destructive leading-snug">{error}</p>+ <p className="text-xs text-destructive leading-snug">{error}</p></div>)}@@ -492,7 +492,7 @@ export default function AuthenticationStep({<buttontype="button"onClick={toggleAuthMode}- className="text-[10px] text-muted-foreground/70 hover:text-foreground transition-colors"+ className="text-xs text-muted-foreground/70 hover:text-foreground transition-colors"disabled={isSubmitting}>{authMode === "sign-in" ? (@@ -557,7 +557,7 @@ export default function AuthenticationStep({<div className="flex items-center gap-2"><div className="flex-1 h-px bg-border/50" />- <span className="text-[9px] font-medium text-muted-foreground/40 uppercase tracking-widest px-1">+ <span className="text-xs font-medium text-muted-foreground/40 uppercase tracking-widest px-1">{t("auth.common.or")}</span><div className="flex-1 h-px bg-border/50" />@@ -614,7 +614,7 @@ export default function AuthenticationStep({</button></div>- <p className="text-[10px] text-muted-foreground/80 leading-tight text-center">+ <p className="text-xs text-muted-foreground/80 leading-tight text-center">{t("auth.legal.prefix")}{" "}<ahref="https://openwhispr.com/terms"diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex c581826c8..598f90fa9 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -1,23 +1,7 @@import React, { Suspense, useState, useEffect, useRef, useCallback } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";-import {- Trash2,- Settings,- FileText,- Mic,- Download,- RefreshCw,- Loader2,- Sparkles,- Cloud,- X,- AlertTriangle,-} from "lucide-react";-import type { SettingsSectionType } from "./SettingsModal";-import TitleBar from "./TitleBar";-import SupportDropdown from "./ui/SupportDropdown";-import TranscriptionItem from "./ui/TranscriptionItem";+import { Download, RefreshCw, Loader2, AlertTriangle } from "lucide-react";import UpgradePrompt from "./UpgradePrompt";import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";@@ -31,11 +15,20 @@ import {useTranscriptions,initializeTranscriptions,removeTranscription as removeFromStore,- clearTranscriptions as clearStoreTranscriptions,} from "../stores/transcriptionStore";-import { formatHotkeyLabel } from "../utils/hotkeys";+import ControlPanelSidebar, { type ControlPanelView } from "./ControlPanelSidebar";+import WindowControls from "./WindowControls";+import { getCachedPlatform } from "../utils/platform";+import { setActiveNoteId, setActiveFolderId } from "../stores/noteStore";+import HistoryView from "./HistoryView";++const platform = getCachedPlatform();const SettingsModal = React.lazy(() => import("./SettingsModal"));+const ReferralModal = React.lazy(() => import("./ReferralModal"));+const PersonalNotesView = React.lazy(() => import("./notes/PersonalNotesView"));+const DictionaryView = React.lazy(() => import("./DictionaryView"));+const UploadAudioView = React.lazy(() => import("./notes/UploadAudioView"));export default function ControlPanel() {const { t } = useTranslation();@@ -45,16 +38,18 @@ export default function ControlPanel() {const [showUpgradePrompt, setShowUpgradePrompt] = useState(false);const [limitData, setLimitData] = useState<{ wordsUsed: number; limit: number } | null>(null);const hasShownUpgradePrompt = useRef(false);- const [settingsSection, setSettingsSection] = useState<SettingsSectionType | undefined>();+ const [settingsSection, setSettingsSection] = useState<string | undefined>();const [aiCTADismissed, setAiCTADismissed] = useState(() => localStorage.getItem("aiCTADismissed") === "true");+ const [showReferrals, setShowReferrals] = useState(false);const [showCloudMigrationBanner, setShowCloudMigrationBanner] = useState(false);+ const [activeView, setActiveView] = useState<ControlPanelView>("home");const cloudMigrationProcessed = useRef(false);const { hotkey } = useHotkey();const { toast } = useToast();const { useReasoningModel, setUseLocalWhisper, setCloudTranscriptionMode } = useSettings();- const { isSignedIn, isLoaded: authLoaded } = useAuth();+ const { isSignedIn, isLoaded: authLoaded, user } = useAuth();const usage = useUsage();const {@@ -182,34 +177,6 @@ export default function ControlPanel() {[toast, t]);- const clearHistory = useCallback(async () => {- showConfirmDialog({- title: t("controlPanel.history.clearTitle"),- description: t("controlPanel.history.clearDescription"),- onConfirm: async () => {- try {- const result = await window.electronAPI.clearTranscriptions();- clearStoreTranscriptions();- toast({- title: t("controlPanel.history.clearedTitle"),- description: t("controlPanel.history.clearedDescription", {- count: result.cleared,- }),- variant: "success",- duration: 3000,- });- } catch (error) {- toast({- title: t("controlPanel.history.couldNotClearTitle"),- description: t("controlPanel.history.couldNotClearDescription"),- variant: "destructive",- });- }- },- variant: "destructive",- });- }, [showConfirmDialog, toast, t]);-const deleteTranscription = useCallback(async (id: number) => {showConfirmDialog({@@ -306,7 +273,7 @@ export default function ControlPanel() {};return (- <div className="min-h-screen bg-background">+ <div className="h-screen bg-background flex flex-col"><ConfirmDialogopen={confirmDialog.open}onOpenChange={hideConfirmDialog}@@ -331,40 +298,6 @@ export default function ControlPanel() {limit={limitData?.limit}/>- <TitleBar- actions={- <>- {!updateStatus.isDevelopment &&- (updateStatus.updateAvailable ||- updateStatus.updateDownloaded ||- isDownloading ||- isInstalling) && (- <Button- variant={updateStatus.updateDownloaded ? "default" : "outline"}- size="sm"- onClick={handleUpdateClick}- disabled={isInstalling || isDownloading}- className="gap-1.5 text-xs"- >- {getUpdateButtonContent()}- </Button>- )}- <SupportDropdown />- <Button- variant="ghost"- size="icon"- onClick={() => {- setSettingsSection(undefined);- setShowSettings(true);- }}- className="text-foreground/70 hover:text-foreground hover:bg-foreground/10"- >- <Settings size={16} />- </Button>- </>- }- />-{showSettings && (<Suspense fallback={null}><SettingsModal@@ -378,180 +311,146 @@ export default function ControlPanel() {</Suspense>)}- <div className="p-4">- <div className="max-w-3xl mx-auto">- {usage?.isPastDue && (- <div className="mb-3 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/50 p-3">- <div className="flex items-start gap-3">- <div className="shrink-0 w-8 h-8 rounded-md bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">- <AlertTriangle size={16} className="text-amber-600 dark:text-amber-400" />- </div>- <div className="flex-1 min-w-0">- <p className="text-[13px] font-medium text-amber-900 dark:text-amber-200 mb-0.5">- {t("controlPanel.billing.pastDueTitle")}- </p>- <p className="text-[12px] text-amber-700 dark:text-amber-300/80 mb-2">- {t("controlPanel.billing.bannerDescription", {- limit: usage.limit.toLocaleString(),- })}- </p>- <Button- variant="default"- size="sm"- className="h-7 text-[11px]"- onClick={() => {- setSettingsSection("account");- setShowSettings(true);- }}- >- {t("controlPanel.billing.updatePayment")}- </Button>- </div>- </div>- </div>- )}+ {showReferrals && (+ <Suspense fallback={null}>+ <ReferralModal open={showReferrals} onOpenChange={setShowReferrals} />+ </Suspense>+ )}- <div className="flex items-center justify-between mb-3 px-1">- <div className="flex items-center gap-2">- <FileText size={14} className="text-primary" />- <h2 className="text-sm font-semibold text-foreground">- {t("controlPanel.history.title")}- </h2>- {history.length > 0 && (- <span className="text-[11px] text-muted-foreground tabular-nums">- ({history.length})- </span>- )}- </div>- {history.length > 0 && (+ <div className="flex flex-1 overflow-hidden">+ <ControlPanelSidebar+ activeView={activeView}+ onViewChange={setActiveView}+ onOpenSettings={() => {+ setSettingsSection(undefined);+ setShowSettings(true);+ }}+ onOpenReferrals={() => setShowReferrals(true)}+ onUpgrade={() => {+ setSettingsSection("plansBilling");+ setShowSettings(true);+ }}+ onUpgradeCheckout={() => usage?.openCheckout()}+ isOverLimit={usage?.isOverLimit ?? false}+ userName={user?.name}+ userEmail={user?.email}+ userImage={user?.image}+ isSignedIn={isSignedIn}+ authLoaded={authLoaded}+ isProUser={usage?.isSubscribed || usage?.isTrial}+ usageLoaded={usage?.hasLoaded ?? false}+ updateAction={+ !updateStatus.isDevelopment &&+ (updateStatus.updateAvailable ||+ updateStatus.updateDownloaded ||+ isDownloading ||+ isInstalling) ? (<Button- onClick={clearHistory}- variant="ghost"+ variant={updateStatus.updateDownloaded ? "default" : "outline"}size="sm"- className="h-7 px-2 text-[11px] text-muted-foreground hover:text-destructive hover:bg-destructive/10"+ onClick={handleUpdateClick}+ disabled={isInstalling || isDownloading}+ className="gap-1.5 text-xs w-full h-7">- <Trash2 size={12} className="mr-1" />- {t("controlPanel.history.clear")}+ {getUpdateButtonContent()}</Button>+ ) : undefined+ }+ />+ <main className="flex-1 flex flex-col overflow-hidden">+ <div+ className="flex items-center justify-end w-full h-10 shrink-0"+ style={{ WebkitAppRegion: "drag" } as React.CSSProperties}+ >+ {platform !== "darwin" && (+ <div className="pr-1" style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>+ <WindowControls />+ </div>)}</div>-- {showCloudMigrationBanner && (- <div className="mb-3 relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3">- <button- onClick={() => {- setShowCloudMigrationBanner(false);- localStorage.setItem("cloudMigrationShown", "true");- }}- className="absolute top-2 right-2 p-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"- >- <X size={14} />- </button>- <div className="flex items-start gap-3 pr-6">- <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/20 flex items-center justify-center">- <Cloud size={16} className="text-primary" />- </div>- <div className="flex-1 min-w-0">- <p className="text-[13px] font-medium text-foreground mb-0.5">- {t("controlPanel.cloudMigration.title")}- </p>- <p className="text-[12px] text-muted-foreground mb-2">- {t("controlPanel.cloudMigration.description")}- </p>- <Button- variant="default"- size="sm"- className="h-7 text-[11px]"- onClick={() => {- setShowCloudMigrationBanner(false);- localStorage.setItem("cloudMigrationShown", "true");- setSettingsSection("transcription");- setShowSettings(true);- }}- >- {t("controlPanel.cloudMigration.viewSettings")}- </Button>+ <div className="flex-1 overflow-y-auto pt-1">+ {usage?.isPastDue && activeView === "home" && (+ <div className="max-w-3xl mx-auto w-full mb-3">+ <div className="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/50 p-3">+ <div className="flex items-start gap-3">+ <div className="shrink-0 w-8 h-8 rounded-md bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">+ <AlertTriangle size={16} className="text-amber-600 dark:text-amber-400" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-amber-900 dark:text-amber-200 mb-0.5">+ {t("controlPanel.billing.pastDueTitle")}+ </p>+ <p className="text-xs text-amber-700 dark:text-amber-300/80 mb-2">+ {t("controlPanel.billing.bannerDescription", {+ limit: usage.limit.toLocaleString(),+ })}+ </p>+ <Button+ variant="default"+ size="sm"+ className="h-7 text-xs"+ onClick={() => {+ setSettingsSection("account");+ setShowSettings(true);+ }}+ >+ {t("controlPanel.billing.updatePayment")}+ </Button>+ </div>+ </div></div></div>- </div>- )}-- {!useReasoningModel && !aiCTADismissed && (- <div className="mb-3 relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3">- <button- onClick={() => {- localStorage.setItem("aiCTADismissed", "true");- setAiCTADismissed(true);+ )}+ {activeView === "home" && (+ <HistoryView+ history={history}+ isLoading={isLoading}+ hotkey={hotkey}+ showCloudMigrationBanner={showCloudMigrationBanner}+ setShowCloudMigrationBanner={setShowCloudMigrationBanner}+ aiCTADismissed={aiCTADismissed}+ setAiCTADismissed={setAiCTADismissed}+ useReasoningModel={useReasoningModel}+ copyToClipboard={copyToClipboard}+ deleteTranscription={deleteTranscription}+ onOpenSettings={(section) => {+ setSettingsSection(section);+ setShowSettings(true);}}- className="absolute top-2 right-2 p-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"- >- <X size={14} />- </button>- <div className="flex items-start gap-3 pr-6">- <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/20 flex items-center justify-center">- <Sparkles size={16} className="text-primary" />- </div>- <div className="flex-1 min-w-0">- <p className="text-[13px] font-medium text-foreground mb-0.5">- {t("controlPanel.aiCta.title")}- </p>- <p className="text-[12px] text-muted-foreground mb-2">- {t("controlPanel.aiCta.description")}- </p>- <Button- variant="default"- size="sm"- className="h-7 text-[11px]"- onClick={() => {- setSettingsSection("aiModels");- setShowSettings(true);- }}- >- {t("controlPanel.aiCta.enable")}- </Button>- </div>- </div>- </div>- )}-- <div className="rounded-lg border border-border bg-card/50 dark:bg-card/30 backdrop-blur-sm">- {isLoading ? (- <div className="flex items-center justify-center gap-2 py-8">- <Loader2 size={14} className="animate-spin text-primary" />- <span className="text-sm text-muted-foreground">{t("controlPanel.loading")}</span>- </div>- ) : history.length === 0 ? (- <div className="flex flex-col items-center justify-center py-12 px-4">- <div className="w-10 h-10 rounded-md bg-muted/50 dark:bg-white/4 flex items-center justify-center mb-3">- <Mic size={18} className="text-muted-foreground" />- </div>- <p className="text-sm text-muted-foreground mb-3">- {t("controlPanel.history.empty")}- </p>- <div className="flex items-center gap-2 text-[12px] text-muted-foreground">- <span>{t("controlPanel.history.press")}</span>- <kbd className="inline-flex items-center h-5 px-1.5 rounded-sm bg-surface-1 dark:bg-white/6 border border-border text-[11px] font-mono font-medium">- {formatHotkeyLabel(hotkey)}- </kbd>- <span>{t("controlPanel.history.toStart")}</span>- </div>- </div>- ) : (- <div className="divide-y divide-border/50 max-h-[calc(100vh-180px)] overflow-y-auto">- {history.map((item, index) => (- <TranscriptionItem- key={item.id}- item={item}- index={index}- total={history.length}- onCopy={copyToClipboard}- onDelete={deleteTranscription}- />- ))}- </div>+ />+ )}+ {activeView === "personal-notes" && (+ <Suspense fallback={null}>+ <PersonalNotesView+ onOpenSettings={(section) => {+ setSettingsSection(section);+ setShowSettings(true);+ }}+ />+ </Suspense>+ )}+ {activeView === "dictionary" && (+ <Suspense fallback={null}>+ <DictionaryView />+ </Suspense>+ )}+ {activeView === "upload" && (+ <Suspense fallback={null}>+ <UploadAudioView+ onNoteCreated={(noteId, folderId) => {+ setActiveNoteId(noteId);+ if (folderId) setActiveFolderId(folderId);+ setActiveView("personal-notes");+ }}+ onOpenSettings={(section) => {+ setSettingsSection(section);+ setShowSettings(true);+ }}+ />+ </Suspense>)}</div>- </div>+ </main></div></div>);diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsxnew file mode 100644index 000000000..0925b127e--- /dev/null+++ b/src/components/ControlPanelSidebar.tsx@@ -0,0 +1,270 @@+import React, { useState } from "react";+import {+ Home,+ NotebookPen,+ BookOpen,+ Upload,+ Gift,+ Settings,+ HelpCircle,+ UserCircle,+ X,+} from "lucide-react";+import logoIcon from "../assets/icon.png";+import { useTranslation } from "react-i18next";+import { cn } from "./lib/utils";+import SupportDropdown from "./ui/SupportDropdown";++export type ControlPanelView = "home" | "personal-notes" | "dictionary" | "upload";++interface ControlPanelSidebarProps {+ activeView: ControlPanelView;+ onViewChange: (view: ControlPanelView) => void;+ onOpenSettings: () => void;+ onOpenReferrals?: () => void;+ onUpgrade?: () => void;+ onUpgradeCheckout?: () => void;+ isOverLimit?: boolean;+ userName?: string | null;+ userEmail?: string | null;+ userImage?: string | null;+ isSignedIn?: boolean;+ authLoaded?: boolean;+ isProUser?: boolean;+ usageLoaded?: boolean;+ updateAction?: React.ReactNode;+}++export default function ControlPanelSidebar({+ activeView,+ onViewChange,+ onOpenSettings,+ onOpenReferrals,+ onUpgrade,+ onUpgradeCheckout,+ isOverLimit,+ userName,+ userEmail,+ userImage,+ isSignedIn,+ authLoaded,+ isProUser,+ usageLoaded,+ updateAction,+}: ControlPanelSidebarProps) {+ const { t } = useTranslation();+ const [upgradeDismissed, setUpgradeDismissed] = useState(+ () => localStorage.getItem("upgradeProDismissed") === "true"+ );++ const showLimitBanner = authLoaded && isSignedIn && !isProUser && isOverLimit;+ const showUpgradeBanner =+ !showLimitBanner &&+ authLoaded &&+ (!isSignedIn || usageLoaded !== false) &&+ !isProUser &&+ !upgradeDismissed;++ const navItems: {+ id: ControlPanelView;+ label: string;+ icon: React.ComponentType<{ size?: number; className?: string }>;+ }[] = [+ { id: "home", label: t("sidebar.home"), icon: Home },+ { id: "personal-notes", label: t("sidebar.notes"), icon: NotebookPen },+ { id: "upload", label: t("sidebar.upload"), icon: Upload },+ { id: "dictionary", label: t("sidebar.dictionary"), icon: BookOpen },+ ];++ return (+ <div className="w-48 shrink-0 border-r border-border/15 dark:border-white/6 flex flex-col bg-surface-1/60 dark:bg-surface-1">+ <div+ className="w-full h-10 shrink-0"+ style={{ WebkitAppRegion: "drag" } as React.CSSProperties}+ />++ <nav className="flex flex-col gap-0.5 px-2 pt-4 pb-2">+ {navItems.map((item) => {+ const Icon = item.icon;+ const isActive = activeView === item.id;++ return (+ <button+ key={item.id}+ onClick={() => onViewChange(item.id)}+ className={cn(+ "group relative flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md outline-none transition-colors duration-150 text-left",+ "focus-visible:ring-1 focus-visible:ring-primary/30",+ isActive+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4 active:bg-foreground/6"+ )}+ >+ {isActive && (+ <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-3.5 rounded-r-full bg-primary" />+ )}+ <Icon+ size={15}+ className={cn(+ "shrink-0 transition-colors duration-150",+ isActive+ ? "text-primary"+ : "text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/55 dark:group-hover:text-foreground/70"+ )}+ />+ <span+ className={cn(+ "text-xs transition-colors duration-150",+ isActive+ ? "text-foreground font-medium"+ : "text-foreground/80 group-hover:text-foreground dark:text-foreground/75 dark:group-hover:text-foreground/90"+ )}+ >+ {item.label}+ </span>+ </button>+ );+ })}+ </nav>++ <div className="flex-1" />++ {showLimitBanner && (+ <div className="px-2 pb-2">+ <div className="rounded-lg border border-destructive/25 bg-destructive/5 dark:bg-destructive/10 p-3">+ <div className="flex flex-col items-center text-center">+ <img src={logoIcon} alt="" className="w-7 h-7 rounded-md mb-2" />+ <p className="text-xs font-medium text-foreground mb-0.5">+ {t("sidebar.limitReached")}+ </p>+ <p className="text-[11px] leading-snug text-muted-foreground mb-2.5">+ {t("sidebar.limitReachedDescription")}+ </p>+ <button+ onClick={onUpgradeCheckout}+ className="w-full h-7 rounded-md bg-primary text-primary-foreground text-xs font-medium hover:bg-primary/90 transition-colors"+ >+ {t("sidebar.upgradeToPro")}+ </button>+ </div>+ </div>+ </div>+ )}++ {showUpgradeBanner && (+ <div className="px-2 pb-2">+ <div className="relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3">+ <button+ onClick={() => {+ setUpgradeDismissed(true);+ localStorage.setItem("upgradeProDismissed", "true");+ }}+ aria-label="Dismiss"+ className="absolute top-1.5 right-1.5 p-0.5 rounded-sm text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ >+ <X size={12} />+ </button>+ <div className="flex flex-col items-center text-center pt-1">+ <img src={logoIcon} alt="" className="w-7 h-7 rounded-md mb-2" />+ <p className="text-xs font-medium text-foreground mb-0.5">+ {t("sidebar.upgradeTitle")}+ </p>+ <p className="text-[11px] leading-snug text-muted-foreground mb-2.5">+ {t("sidebar.upgradeDescription")}+ </p>+ <button+ onClick={onUpgrade}+ className="w-full h-7 rounded-md bg-primary text-primary-foreground text-xs font-medium hover:bg-primary/90 transition-colors"+ >+ {t("sidebar.learnMore")}+ </button>+ </div>+ </div>+ </div>+ )}++ <div className="px-2 pb-2 space-y-0.5">+ {updateAction && (+ <div className="px-1 pb-1" style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>+ {updateAction}+ </div>+ )}++ {isSignedIn && onOpenReferrals && (+ <button+ onClick={onOpenReferrals}+ aria-label={t("sidebar.referral")}+ className="group flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md text-left outline-none hover:bg-foreground/4 dark:hover:bg-white/4 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150"+ >+ <Gift+ size={15}+ className="shrink-0 text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/50 dark:group-hover:text-foreground/65 transition-colors duration-150"+ />+ <span className="text-xs text-foreground/80 group-hover:text-foreground dark:text-foreground/70 dark:group-hover:text-foreground/85 transition-colors duration-150">+ {t("sidebar.referral")}+ </span>+ </button>+ )}++ <button+ onClick={onOpenSettings}+ aria-label={t("sidebar.settings")}+ className="group flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md text-left outline-none hover:bg-foreground/4 dark:hover:bg-white/4 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150"+ >+ <Settings+ size={15}+ className="shrink-0 text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/50 dark:group-hover:text-foreground/65 transition-colors duration-150"+ />+ <span className="text-xs text-foreground/80 group-hover:text-foreground dark:text-foreground/70 dark:group-hover:text-foreground/85 transition-colors duration-150">+ {t("sidebar.settings")}+ </span>+ </button>++ <SupportDropdown+ trigger={+ <button+ aria-label={t("sidebar.support")}+ className="group flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md text-left outline-none hover:bg-foreground/4 dark:hover:bg-white/4 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150"+ >+ <HelpCircle+ size={15}+ className="shrink-0 text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/50 dark:group-hover:text-foreground/65 transition-colors duration-150"+ />+ <span className="text-xs text-foreground/80 group-hover:text-foreground dark:text-foreground/70 dark:group-hover:text-foreground/85 transition-colors duration-150">+ {t("sidebar.support")}+ </span>+ </button>+ }+ />++ <div className="mx-1 h-px bg-border/10 dark:bg-white/6 my-1.5!" />++ <div className="flex items-center gap-2.5 px-2.5 py-1.5 rounded-md">+ {userImage ? (+ <img src={userImage} alt="" className="w-6 h-6 rounded-full shrink-0 object-cover" />+ ) : (+ <UserCircle size={18} className="shrink-0 text-foreground/50 dark:text-foreground/45" />+ )}+ <div className="flex-1 min-w-0">+ {isSignedIn && (userName || userEmail) ? (+ <>+ <p className="text-xs text-foreground/80 dark:text-foreground/80 truncate leading-tight">+ {userName || t("sidebar.defaultUser")}+ </p>+ {userEmail && (+ <p className="text-xs text-foreground/55 dark:text-foreground/55 truncate leading-tight">+ {userEmail}+ </p>+ )}+ </>+ ) : authLoaded && !isSignedIn ? (+ <p className="text-xs text-foreground/45 dark:text-foreground/55">+ {t("sidebar.notSignedIn")}+ </p>+ ) : null}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/DeveloperSection.tsx b/src/components/DeveloperSection.tsxindex 7c9ef05ab..9c6647c3e 100644--- a/src/components/DeveloperSection.tsx+++ b/src/components/DeveloperSection.tsx@@ -4,6 +4,7 @@ import { Button } from "./ui/button";import { FolderOpen, Copy, Check } from "lucide-react";import { useToast } from "./ui/Toast";import { Toggle } from "./ui/toggle";+import logger from "../utils/logger";export default function DeveloperSection() {const { t } = useTranslation();@@ -25,7 +26,7 @@ export default function DeveloperSection() {setDebugEnabled(state.enabled);setLogPath(state.logPath);} catch (error) {- console.error("Failed to load debug state:", error);+ logger.error("Failed to load debug state", { error }, "developer");toast({title: t("developerSection.toasts.loadFailed.title"),description: t("developerSection.toasts.loadFailed.description"),@@ -114,7 +115,7 @@ export default function DeveloperSection() {<h3 className="text-[15px] font-semibold text-foreground tracking-tight">{t("developerSection.title")}</h3>- <p className="text-[12px] text-muted-foreground mt-1 leading-relaxed">+ <p className="text-xs text-muted-foreground mt-1 leading-relaxed">{t("developerSection.description")}</p></div>@@ -125,7 +126,7 @@ export default function DeveloperSection() {<div className="flex items-center justify-between gap-6"><div className="min-w-0 flex-1"><div className="flex items-center gap-2">- <p className="text-[13px] font-medium text-foreground">+ <p className="text-xs font-medium text-foreground">{t("developerSection.debugMode.label")}</p><div@@ -134,7 +135,7 @@ export default function DeveloperSection() {}`}/></div>- <p className="text-[12px] text-muted-foreground mt-0.5 leading-relaxed">+ <p className="text-xs text-muted-foreground mt-0.5 leading-relaxed">{debugEnabled? t("developerSection.debugMode.enabledDescription"): t("developerSection.debugMode.disabledDescription")}@@ -153,11 +154,11 @@ export default function DeveloperSection() {{/* Log Path — only when active */}{debugEnabled && logPath && (<div className="px-5 py-4">- <p className="text-[11px] font-medium text-muted-foreground/60 uppercase tracking-wider mb-2">+ <p className="text-xs font-medium text-muted-foreground/60 uppercase tracking-wider mb-2">{t("developerSection.currentLogFile")}</p><div className="flex items-center gap-2">- <code className="flex-1 text-[11px] text-muted-foreground font-mono break-all leading-relaxed bg-muted/30 dark:bg-surface-raised/30 px-3 py-2 rounded-lg border border-border/30">+ <code className="flex-1 text-xs text-muted-foreground font-mono break-all leading-relaxed bg-muted/30 dark:bg-surface-raised/30 px-3 py-2 rounded-lg border border-border/30">{logPath}</code><Button@@ -207,7 +208,7 @@ export default function DeveloperSection() {].map((item) => (<div key={item} className="flex items-center gap-2"><div className="h-1 w-1 rounded-full bg-muted-foreground/30 shrink-0" />- <span className="text-[12px] text-muted-foreground">{item}</span>+ <span className="text-xs text-muted-foreground">{item}</span></div>))}</div>@@ -219,7 +220,7 @@ export default function DeveloperSection() {{debugEnabled && (<div className="rounded-xl border border-warning/20 bg-warning/5 dark:bg-warning/10"><div className="px-5 py-4">- <p className="text-[12px] text-muted-foreground leading-relaxed">+ <p className="text-xs text-muted-foreground leading-relaxed"><span className="font-medium text-warning">{t("developerSection.performanceNote.label")}</span>{" "}@@ -246,14 +247,14 @@ export default function DeveloperSection() {t("developerSection.sharing.steps.2"),].map((step, i) => (<div key={i} className="flex items-start gap-3">- <span className="shrink-0 text-[11px] font-mono text-muted-foreground/40 mt-0.5 w-4 text-right">+ <span className="shrink-0 text-xs font-mono text-muted-foreground/40 mt-0.5 w-4 text-right">{i + 1}</span>- <p className="text-[12px] text-muted-foreground leading-relaxed">{step}</p>+ <p className="text-xs text-muted-foreground leading-relaxed">{step}</p></div>))}</div>- <p className="text-[11px] text-muted-foreground/40 mt-4 pt-3 border-t border-border/20">+ <p className="text-xs text-muted-foreground/40 mt-4 pt-3 border-t border-border/20">{t("developerSection.sharing.footer")}</p></div>diff --git a/src/components/DictionaryView.tsx b/src/components/DictionaryView.tsxnew file mode 100644index 000000000..654854e5a--- /dev/null+++ b/src/components/DictionaryView.tsx@@ -0,0 +1,214 @@+import { useState, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { BookOpen, X, CornerDownLeft, Info } from "lucide-react";+import { Input } from "./ui/input";+import { ConfirmDialog } from "./ui/dialog";+import { useSettings } from "../hooks/useSettings";+import { getAgentName } from "../utils/agentName";++export default function DictionaryView() {+ const { t } = useTranslation();+ const { customDictionary, setCustomDictionary } = useSettings();+ const agentName = getAgentName();+ const [newWord, setNewWord] = useState("");+ const [confirmClear, setConfirmClear] = useState(false);+ const [showInfo, setShowInfo] = useState(false);++ const isEmpty = customDictionary.length === 0;++ const handleAdd = useCallback(() => {+ const words = newWord+ .split(",")+ .map((w) => w.trim())+ .filter((w) => w && !customDictionary.includes(w));+ if (words.length > 0) {+ setCustomDictionary([...customDictionary, ...words]);+ setNewWord("");+ }+ }, [newWord, customDictionary, setCustomDictionary]);++ const handleRemove = useCallback(+ (word: string) => {+ if (word === agentName) return;+ setCustomDictionary(customDictionary.filter((w) => w !== word));+ },+ [customDictionary, setCustomDictionary, agentName]+ );++ return (+ <div className="flex flex-col h-full">+ <ConfirmDialog+ open={confirmClear}+ onOpenChange={setConfirmClear}+ title={t("dictionary.clearTitle")}+ description={t("dictionary.clearDescription")}+ onConfirm={() => setCustomDictionary(customDictionary.filter((w) => w === agentName))}+ variant="destructive"+ />++ {isEmpty ? (+ /* ─── Empty state ─── */+ <div className="flex-1 flex flex-col items-center justify-center px-8 -mt-4">+ <div className="w-10 h-10 rounded-[10px] bg-gradient-to-b from-primary/8 to-primary/4 dark:from-primary/12 dark:to-primary/6 border border-primary/10 dark:border-primary/15 flex items-center justify-center mb-4">+ <BookOpen+ size={17}+ strokeWidth={1.5}+ className="text-primary/50 dark:text-primary/60"+ />+ </div>++ <h2 className="text-xs font-semibold text-foreground mb-1">{t("dictionary.title")}</h2>+ <p className="text-xs text-foreground/30 text-center leading-relaxed max-w-[240px] mb-6">+ {t("dictionary.description")}+ </p>++ <div className="w-full max-w-[260px] relative">+ <Input+ placeholder={t("dictionary.addPlaceholder")}+ value={newWord}+ onChange={(e) => setNewWord(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleAdd();+ }}+ className="w-full h-8 text-xs pr-8 placeholder:text-foreground/20"+ />+ {newWord.trim() ? (+ <button+ onClick={handleAdd}+ aria-label={t("dictionary.addWord")}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-primary/50 hover:text-primary transition-colors"+ >+ <CornerDownLeft size={11} />+ </button>+ ) : (+ <kbd className="absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-foreground/12 font-mono select-none pointer-events-none">+ ⏎+ </kbd>+ )}+ </div>++ <div className="flex items-center gap-1.5 mt-3">+ {["OpenWhispr", "Dr. Smith", "gRPC"].map((ex) => (+ <span+ key={ex}+ className="text-xs text-foreground/12 px-1.5 py-0.5 rounded-[4px] border border-dashed border-foreground/6 dark:border-white/5"+ >+ {ex}+ </span>+ ))}+ </div>++ <div className="mt-8 w-full max-w-[260px]">+ <button+ onClick={() => setShowInfo(!showInfo)}+ aria-expanded={showInfo}+ aria-label={t("dictionary.howItWorks")}+ className="flex items-center gap-1 text-xs text-foreground/15 hover:text-foreground/30 transition-colors mx-auto"+ >+ <Info size={9} />+ {t("dictionary.howItWorks")}+ </button>+ {showInfo && (+ <div className="mt-2.5 rounded-md bg-foreground/[0.02] dark:bg-white/[0.02] border border-foreground/5 dark:border-white/4 px-3 py-2.5">+ <p className="text-xs text-foreground/25 leading-[1.6]">+ {t("dictionary.howItWorksDetail")}+ </p>+ </div>+ )}+ </div>+ </div>+ ) : (+ /* ─── Populated state ─── */+ <>+ <div className="px-5 pt-4 pb-2.5 flex items-baseline justify-between">+ <div className="flex items-baseline gap-2">+ <h2 className="text-xs font-semibold text-foreground">{t("dictionary.title")}</h2>+ <span className="text-xs text-foreground/15 font-mono tabular-nums">+ {customDictionary.length}+ </span>+ </div>+ <button+ onClick={() => setConfirmClear(true)}+ aria-label={t("dictionary.clearAll")}+ className="text-xs text-foreground/15 hover:text-destructive/70 transition-colors"+ >+ {t("dictionary.clearAll")}+ </button>+ </div>++ <div className="px-5 pb-3">+ <div className="relative">+ <Input+ placeholder={t("dictionary.addPlaceholder")}+ value={newWord}+ onChange={(e) => setNewWord(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleAdd();+ }}+ className="w-full h-7 text-xs pr-8 placeholder:text-foreground/20"+ />+ {newWord.trim() ? (+ <button+ onClick={handleAdd}+ aria-label={t("dictionary.addWord")}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-primary/50 hover:text-primary transition-colors"+ >+ <CornerDownLeft size={10} />+ </button>+ ) : (+ <kbd className="absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-foreground/12 font-mono select-none pointer-events-none">+ ⏎+ </kbd>+ )}+ </div>+ </div>++ <div className="mx-5 h-px bg-border/8 dark:bg-white/3" />++ <div className="flex-1 overflow-y-auto px-5 py-3">+ <div className="flex flex-wrap gap-1.5">+ {customDictionary.map((word) => {+ const isAgentName = word === agentName;+ return (+ <span+ key={word}+ className={`group inline-flex items-center gap-1 py-[3px]+ rounded-[5px] text-xs+ border transition-colors duration-150+ ${+ isAgentName+ ? "pl-2.5 pr-2.5 bg-primary/10 dark:bg-primary/15 text-primary border-primary/20 dark:border-primary/30"+ : "pl-2.5 pr-1 bg-foreground/[0.02] dark:bg-white/[0.03] text-foreground/60 dark:text-foreground/50 border-foreground/8 dark:border-white/6 hover:border-foreground/15 dark:hover:border-white/12 hover:bg-foreground/[0.04] dark:hover:bg-white/[0.06] hover:text-foreground/80 dark:hover:text-foreground/70"+ }`}+ title={isAgentName ? t("dictionary.autoManaged") : undefined}+ >+ {word}+ {!isAgentName && (+ <button+ onClick={() => handleRemove(word)}+ aria-label={t("dictionary.removeWord", { word })}+ className="p-0.5 rounded-sm+ opacity-0 group-hover:opacity-100+ text-foreground/25 hover:!text-destructive/70+ transition-colors duration-150"+ >+ <X size={10} strokeWidth={2} />+ </button>+ )}+ </span>+ );+ })}+ </div>+ </div>++ <div className="px-5 pb-3 flex items-start gap-1.5">+ <Info size={9} className="text-foreground/10 mt-px shrink-0" />+ <p className="text-xs text-foreground/12 leading-relaxed">+ {t("dictionary.inputHint")}+ </p>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/src/components/EmailVerificationStep.tsx b/src/components/EmailVerificationStep.tsxindex cfc8669d3..a70385d6f 100644--- a/src/components/EmailVerificationStep.tsx+++ b/src/components/EmailVerificationStep.tsx@@ -41,7 +41,7 @@ export default function EmailVerificationStep({ email, onVerified }: EmailVerifi}} else if (res.status === 401 || res.status === 400) {if (pollRef.current) clearInterval(pollRef.current);- setError("Session expired. Please restart the sign-up process.");+ setError(t("auth.sessionExpired"));}} catch {// Network error — silently retry on next poll@@ -120,12 +120,12 @@ export default function EmailVerificationStep({ email, onVerified }: EmailVerifi<div className="flex items-center justify-center gap-1.5 py-1"><Loader2 className="w-3 h-3 animate-spin text-muted-foreground/50" />- <p className="text-[10px] text-muted-foreground/50">{t("emailVerification.waiting")}</p>+ <p className="text-xs text-muted-foreground/50">{t("emailVerification.waiting")}</p></div>{error && (<div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5">- <p className="text-[10px] text-destructive leading-snug">{error}</p>+ <p className="text-xs text-destructive leading-snug">{error}</p></div>)}diff --git a/src/components/ForgotPasswordView.tsx b/src/components/ForgotPasswordView.tsxindex af24889ea..011894625 100644--- a/src/components/ForgotPasswordView.tsx+++ b/src/components/ForgotPasswordView.tsx@@ -46,7 +46,7 @@ export default function ForgotPasswordView({return (<div className="space-y-3"><div className="bg-warning/5 p-2.5 rounded border border-warning/20">- <p className="text-[10px] text-warning text-center leading-snug">+ <p className="text-xs text-warning text-center leading-snug">{t("forgotPassword.notConfigured")}</p></div>@@ -75,7 +75,7 @@ export default function ForgotPasswordView({</div><div className="bg-muted/50 p-2.5 rounded border border-border/50">- <p className="text-[10px] text-muted-foreground text-center leading-snug">+ <p className="text-xs text-muted-foreground text-center leading-snug">{t("forgotPassword.success.help")}</p></div>@@ -105,7 +105,7 @@ export default function ForgotPasswordView({<buttontype="button"onClick={onBack}- className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"><ArrowLeft className="w-3 h-3" />{t("forgotPassword.back")}@@ -135,7 +135,7 @@ export default function ForgotPasswordView({{error && (<div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5"><AlertCircle className="w-3 h-3 text-destructive shrink-0" />- <p className="text-[10px] text-destructive leading-snug">{error}</p>+ <p className="text-xs text-destructive leading-snug">{error}</p></div>)}diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsxnew file mode 100644index 000000000..2914bcd2f--- /dev/null+++ b/src/components/HistoryView.tsx@@ -0,0 +1,272 @@+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "./ui/button";+import { Loader2, Sparkles, Cloud, X } from "lucide-react";+import TranscriptionItem from "./ui/TranscriptionItem";+import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";+import { formatHotkeyLabel } from "../utils/hotkeys";+import { formatDateGroup } from "../utils/dateFormatting";++interface HistoryViewProps {+ history: TranscriptionItemType[];+ isLoading: boolean;+ hotkey: string;+ showCloudMigrationBanner: boolean;+ setShowCloudMigrationBanner: (show: boolean) => void;+ aiCTADismissed: boolean;+ setAiCTADismissed: (dismissed: boolean) => void;+ useReasoningModel: boolean;+ copyToClipboard: (text: string) => void;+ deleteTranscription: (id: number) => void;+ onOpenSettings: (section?: string) => void;+}++export default function HistoryView({+ history,+ isLoading,+ hotkey,+ showCloudMigrationBanner,+ setShowCloudMigrationBanner,+ aiCTADismissed,+ setAiCTADismissed,+ useReasoningModel,+ copyToClipboard,+ deleteTranscription,+ onOpenSettings,+}: HistoryViewProps) {+ const { t } = useTranslation();++ const groupedHistory = useMemo(() => {+ if (history.length === 0) return [];++ const groups: { label: string; items: TranscriptionItemType[] }[] = [];+ let currentLabel: string | null = null;++ for (const item of history) {+ const label = formatDateGroup(item.timestamp, t);++ if (label !== currentLabel) {+ groups.push({ label, items: [item] });+ currentLabel = label;+ } else {+ groups[groups.length - 1].items.push(item);+ }+ }++ return groups;+ }, [history, t]);++ return (+ <div className="px-4 pt-4 pb-6">+ <div className="max-w-3xl mx-auto">+ {showCloudMigrationBanner && (+ <div className="mb-3 relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3">+ <button+ onClick={() => {+ setShowCloudMigrationBanner(false);+ localStorage.setItem("cloudMigrationShown", "true");+ }}+ aria-label={t("common.close")}+ className="absolute top-2 right-2 p-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ >+ <X size={14} />+ </button>+ <div className="flex items-start gap-3 pr-6">+ <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/20 flex items-center justify-center">+ <Cloud size={16} className="text-primary" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground mb-0.5">+ {t("controlPanel.cloudMigration.title")}+ </p>+ <p className="text-xs text-muted-foreground mb-2">+ {t("controlPanel.cloudMigration.description")}+ </p>+ <Button+ variant="default"+ size="sm"+ className="h-7 text-xs"+ onClick={() => {+ setShowCloudMigrationBanner(false);+ localStorage.setItem("cloudMigrationShown", "true");+ onOpenSettings("transcription");+ }}+ >+ {t("controlPanel.cloudMigration.viewSettings")}+ </Button>+ </div>+ </div>+ </div>+ )}++ {!useReasoningModel && !aiCTADismissed && (+ <div className="mb-3 relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3">+ <button+ onClick={() => {+ localStorage.setItem("aiCTADismissed", "true");+ setAiCTADismissed(true);+ }}+ aria-label={t("common.close")}+ className="absolute top-2 right-2 p-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 transition-colors"+ >+ <X size={14} />+ </button>+ <div className="flex items-start gap-3 pr-6">+ <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/20 flex items-center justify-center">+ <Sparkles size={16} className="text-primary" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground mb-0.5">+ {t("controlPanel.aiCta.title")}+ </p>+ <p className="text-xs text-muted-foreground mb-2">+ {t("controlPanel.aiCta.description")}+ </p>+ <Button+ variant="default"+ size="sm"+ className="h-7 text-xs"+ onClick={() => onOpenSettings("aiModels")}+ >+ {t("controlPanel.aiCta.enable")}+ </Button>+ </div>+ </div>+ </div>+ )}++ {isLoading ? (+ <div className="rounded-lg border border-border bg-card/50 dark:bg-card/60 backdrop-blur-sm">+ <div className="flex items-center justify-center gap-2 py-8">+ <Loader2 size={14} className="animate-spin text-primary" />+ <span className="text-sm text-muted-foreground">{t("controlPanel.loading")}</span>+ </div>+ </div>+ ) : history.length === 0 ? (+ <div className="rounded-lg border border-border bg-card/50 dark:bg-card/60 backdrop-blur-sm">+ <div className="flex flex-col items-center justify-center py-16 px-4">+ <svg+ className="text-foreground dark:text-white mb-5"+ width="64"+ height="64"+ viewBox="0 0 64 64"+ fill="none"+ >+ <rect+ x="24"+ y="6"+ width="16"+ height="28"+ rx="8"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.1}+ />+ <rect+ x="28"+ y="12"+ width="8"+ height="3"+ rx="1.5"+ fill="currentColor"+ fillOpacity={0.06}+ />+ <path+ d="M18 28c0 7.7 6.3 14 14 14s14-6.3 14-14"+ fill="none"+ stroke="currentColor"+ strokeOpacity={0.07}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <line+ x1="32"+ y1="42"+ x2="32"+ y2="50"+ stroke="currentColor"+ strokeOpacity={0.07}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <line+ x1="26"+ y1="50"+ x2="38"+ y2="50"+ stroke="currentColor"+ strokeOpacity={0.07}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <path+ d="M12 20a2 2 0 0 1 0 8"+ stroke="currentColor"+ strokeOpacity={0.04}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <path+ d="M8 18a2 2 0 0 1 0 12"+ stroke="currentColor"+ strokeOpacity={0.03}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <path+ d="M52 20a2 2 0 0 0 0 8"+ stroke="currentColor"+ strokeOpacity={0.04}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ <path+ d="M56 18a2 2 0 0 0 0 12"+ stroke="currentColor"+ strokeOpacity={0.03}+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ </svg>+ <h3 className="text-xs font-semibold text-foreground/70 dark:text-foreground/60 mb-2">+ {t("controlPanel.history.empty")}+ </h3>+ <div className="flex items-center gap-2 text-xs text-foreground/50 dark:text-foreground/25">+ <span>{t("controlPanel.history.press")}</span>+ <kbd className="inline-flex items-center h-5 px-1.5 rounded-sm bg-surface-1 dark:bg-white/6 border border-border/50 text-xs font-mono font-medium text-foreground/60 dark:text-foreground/40">+ {formatHotkeyLabel(hotkey)}+ </kbd>+ <span>{t("controlPanel.history.toStart")}</span>+ </div>+ </div>+ </div>+ ) : (+ <div>+ {groupedHistory.map((group, index) => (+ <div key={group.label}>+ <div+ className={`sticky top-0 z-10 bg-background px-1 pb-2 ${index === 0 ? "pt-1" : "pt-5"}`}+ >+ <span className="text-[11px] font-semibold text-muted-foreground dark:text-muted-foreground uppercase tracking-wide">+ {group.label}+ </span>+ </div>+ <div className="space-y-1.5">+ {group.items.map((item) => (+ <TranscriptionItem+ key={item.id}+ item={item}+ onCopy={copyToClipboard}+ onDelete={deleteTranscription}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 21b2aece2..5e896ff29 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -14,6 +14,7 @@ import {UserCircle,} from "lucide-react";import TitleBar from "./TitleBar";+import WindowControls from "./WindowControls";import PermissionCard from "./ui/PermissionCard";import SupportDropdown from "./ui/SupportDropdown";import MicPermissionWarning from "./ui/MicPermissionWarning";@@ -32,10 +33,10 @@ import { setAgentName as saveAgentName } from "../utils/agentName";import { formatHotkeyLabel, getDefaultHotkey } from "../utils/hotkeys";import { useAuth } from "../hooks/useAuth";import { HotkeyInput } from "./ui/HotkeyInput";-import HotkeyGuidanceAccordion from "./ui/HotkeyGuidanceAccordion";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";import { getValidationMessage } from "../utils/hotkeyValidator";import { getPlatform } from "../utils/platform";+import logger from "../utils/logger";import { ActivationModeSelector } from "./ui/ActivationModeSelector";import TranscriptionModelPicker from "./TranscriptionModelPicker";@@ -150,7 +151,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setActivationMode("tap");}} catch (error) {- console.error("Failed to check hotkey mode:", error);+ logger.error("Failed to check hotkey mode", { error }, "onboarding");}};checkHotkeyMode();@@ -171,7 +172,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {: await window.electronAPI?.checkModelStatus(modelToCheck);setIsModelDownloaded(result?.downloaded ?? false);} catch (error) {- console.error("Failed to check model status:", error);+ logger.error("Failed to check model status", { error }, "onboarding");setIsModelDownloaded(false);}};@@ -216,7 +217,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}}} catch (error) {- console.error("Failed to auto-register default hotkey:", error);+ logger.error("Failed to auto-register default hotkey", { error }, "onboarding");} finally {autoRegisterInFlightRef.current = false;}@@ -241,7 +242,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}return true;} catch (error) {- console.error("Failed to register onboarding hotkey", error);+ logger.error("Failed to register onboarding hotkey", { error }, "onboarding");showAlertDialog({title: t("onboarding.hotkey.couldNotRegisterTitle"),description: t("onboarding.hotkey.couldNotRegisterDescription"),@@ -266,7 +267,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {try {await window.electronAPI?.saveAllKeysToEnv?.();} catch (error) {- console.error("Failed to persist API keys:", error);+ logger.error("Failed to persist API keys", { error }, "onboarding");}return true;@@ -608,7 +609,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">{t("onboarding.activation.mode")}</span>- <p className="text-[11px] text-muted-foreground/70 mt-0.5">+ <p className="text-xs text-muted-foreground/70 mt-0.5">{activationMode === "tap"? t("onboarding.activation.tapDescription"): t("onboarding.activation.holdDescription")}@@ -629,7 +630,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">{t("onboarding.activation.test")}</span>- <span className="text-[10px] text-muted-foreground/60">+ <span className="text-xs text-muted-foreground/60">{activationMode === "tap" || isUsingGnomeHotkeys? t("onboarding.activation.hotkeyToStartStop", { hotkey: readableHotkey }): t("onboarding.activation.holdHotkey", { hotkey: readableHotkey })}@@ -673,6 +674,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return openaiApiKey.trim().length > 0;} else if (cloudTranscriptionProvider === "groq") {return groqApiKey.trim().length > 0;+ } else if (cloudTranscriptionProvider === "mistral") {+ return mistralApiKey.trim().length > 0;} else if (cloudTranscriptionProvider === "custom") {// Custom can work without API key for local endpointsreturn true;@@ -714,12 +717,15 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {};}, []);+ const onboardingPlatform =+ typeof window !== "undefined" && window.electronAPI?.getPlatform+ ? window.electronAPI.getPlatform()+ : "darwin";+return (<divclassName="h-screen flex flex-col bg-background"- style={{- paddingTop: "env(safe-area-inset-top, 0px)",- }}+ style={{ paddingTop: "env(safe-area-inset-top, 0px)" }}><ConfirmDialogopen={confirmDialog.open}@@ -739,14 +745,27 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {onOk={() => {}}/>- {/* Title Bar */}- <div className="shrink-0 z-10">- <TitleBar- showTitle={true}- className="bg-background backdrop-blur-xl border-b border-border shadow-sm"- actions={isSignedIn ? <SupportDropdown /> : undefined}- ></TitleBar>- </div>+ {/* Title Bar / drag region */}+ {currentStep === 0 ? (+ <div+ className="flex items-center justify-end w-full h-10 shrink-0"+ style={{ WebkitAppRegion: "drag" } as React.CSSProperties}+ >+ {onboardingPlatform !== "darwin" && (+ <div className="pr-1" style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>+ <WindowControls />+ </div>+ )}+ </div>+ ) : (+ <div className="shrink-0 z-10">+ <TitleBar+ showTitle={true}+ className="bg-background backdrop-blur-xl border-b border-border shadow-sm"+ actions={isSignedIn ? <SupportDropdown /> : undefined}+ ></TitleBar>+ </div>+ )}{/* Progress Bar - hidden on welcome/auth step */}{showProgress && (diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsxindex 86b167e40..486dc9eed 100644--- a/src/components/ReasoningModelSelector.tsx+++ b/src/components/ReasoningModelSelector.tsx@@ -8,6 +8,7 @@ import ModelCardList from "./ui/ModelCardList";import LocalModelPicker, { type LocalProvider } from "./LocalModelPicker";import { ProviderTabs } from "./ui/ProviderTabs";import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";+import logger from "../utils/logger";import { REASONING_PROVIDERS } from "../models/ModelRegistry";import { modelRegistry } from "../models/ModelRegistry";import { getProviderIcon, isMonochromeProvider } from "../utils/providerIcons";@@ -49,8 +50,6 @@ const resolveOwnedByIcon = (ownedBy?: string): { icon?: string; invertInDark: bo};interface ReasoningModelSelectorProps {- useReasoningModel: boolean;- setUseReasoningModel: (value: boolean) => void;reasoningModel: string;setReasoningModel: (model: string) => void;localReasoningProvider: string;@@ -71,8 +70,6 @@ interface ReasoningModelSelectorProps {}export default function ReasoningModelSelector({- useReasoningModel,- setUseReasoningModel,reasoningModel,setReasoningModel,localReasoningProvider,@@ -399,7 +396,7 @@ export default function ReasoningModelSelector({return downloaded;}} catch (error) {- console.error("Failed to load downloaded models:", error);+ logger.error("Failed to load downloaded models", { error }, "models");}return new Set<string>();}, []);@@ -499,303 +496,271 @@ export default function ReasoningModelSelector({return (<div className="space-y-4">- <div className="flex items-center justify-between p-3 bg-card border border-border rounded-lg">- <div>- <label className="text-sm font-medium text-foreground">- {t("reasoning.enableTitle")}- </label>- <p className="text-xs text-muted-foreground">{t("reasoning.enableDescription")}</p>- </div>- <button- onClick={() => setUseReasoningModel(!useReasoningModel)}- className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors duration-200 ${- useReasoningModel ? "bg-primary" : "bg-muted-foreground/25"- }`}- >- <span- className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition-transform duration-200 ${- useReasoningModel ? "translate-x-4.5" : "translate-x-0.75"- }`}- />- </button>+ <div className="space-y-2">+ <ProviderTabs+ providers={MODE_TABS}+ selectedId={selectedMode}+ onSelect={(id) => handleModeChange(id as "cloud" | "local")}+ renderIcon={renderModeIcon}+ colorScheme="purple"+ />+ <p className="text-xs text-muted-foreground text-center">+ {selectedMode === "local"+ ? t("reasoning.mode.localDescription")+ : t("reasoning.mode.cloudDescription")}+ </p></div>- {useReasoningModel && (- <>- <div className="space-y-2">+ {selectedMode === "cloud" ? (+ <div className="space-y-2">+ <div className="border border-border rounded-lg overflow-hidden"><ProviderTabs- providers={MODE_TABS}- selectedId={selectedMode}- onSelect={(id) => handleModeChange(id as "cloud" | "local")}- renderIcon={renderModeIcon}+ providers={cloudProviders}+ selectedId={selectedCloudProvider}+ onSelect={handleCloudProviderChange}colorScheme="purple"/>- <p className="text-xs text-muted-foreground text-center">- {selectedMode === "local"- ? t("reasoning.mode.localDescription")- : t("reasoning.mode.cloudDescription")}- </p>- </div>- {selectedMode === "cloud" ? (- <div className="space-y-2">- <div className="border border-border rounded-lg overflow-hidden">- <ProviderTabs- providers={cloudProviders}- selectedId={selectedCloudProvider}- onSelect={handleCloudProviderChange}- colorScheme="indigo"- />-- <div className="p-3">- {selectedCloudProvider === "custom" ? (- <>- {/* 1. Endpoint URL - TOP */}- <div className="space-y-2">- <h4 className="font-medium text-foreground">- {t("reasoning.custom.endpointTitle")}- </h4>- <Input- value={customBaseInput}- onChange={(event) => setCustomBaseInput(event.target.value)}- onBlur={handleBaseUrlBlur}- placeholder="https://api.openai.com/v1"- className="text-sm"- />- <p className="text-xs text-muted-foreground">- {t("reasoning.custom.endpointExamples")}{" "}- <code className="text-primary">http://localhost:11434/v1</code>{" "}- {t("reasoning.custom.ollama")},{" "}- <code className="text-primary">http://localhost:8080/v1</code>{" "}- {t("reasoning.custom.localAi")}.- </p>+ <div className="p-3">+ {selectedCloudProvider === "custom" ? (+ <>+ {/* 1. Endpoint URL - TOP */}+ <div className="space-y-2">+ <h4 className="font-medium text-foreground">+ {t("reasoning.custom.endpointTitle")}+ </h4>+ <Input+ value={customBaseInput}+ onChange={(event) => setCustomBaseInput(event.target.value)}+ onBlur={handleBaseUrlBlur}+ placeholder="https://api.openai.com/v1"+ className="text-sm"+ />+ <p className="text-xs text-muted-foreground">+ {t("reasoning.custom.endpointExamples")}{" "}+ <code className="text-primary">http://localhost:11434/v1</code>{" "}+ {t("reasoning.custom.ollama")},{" "}+ <code className="text-primary">http://localhost:8080/v1</code>{" "}+ {t("reasoning.custom.localAi")}.+ </p>+ </div>++ {/* 2. API Key - SECOND */}+ <div className="space-y-2 pt-3">+ <h4 className="font-medium text-foreground">+ {t("reasoning.custom.apiKeyOptional")}+ </h4>+ <ApiKeyInput+ apiKey={customReasoningApiKey}+ setApiKey={setCustomReasoningApiKey || (() => {})}+ label=""+ helpText={t("reasoning.custom.apiKeyHelp")}+ />+ </div>++ {/* 3. Model Selection - THIRD */}+ <div className="space-y-2 pt-3">+ <div className="flex items-center justify-between">+ <h4 className="text-sm font-medium text-foreground">+ {t("reasoning.availableModels")}+ </h4>+ <div className="flex gap-2">+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={handleResetCustomBase}+ className="text-xs"+ >+ {t("common.reset")}+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={handleRefreshCustomModels}+ disabled={+ customModelsLoading || (!trimmedCustomBase && !hasSavedCustomBase)+ }+ className="text-xs"+ >+ {customModelsLoading+ ? t("common.loading")+ : isCustomBaseDirty+ ? t("reasoning.custom.applyAndRefresh")+ : t("common.refresh")}+ </Button></div>-- {/* 2. API Key - SECOND */}- <div className="space-y-2 pt-3">- <h4 className="font-medium text-foreground">- {t("reasoning.custom.apiKeyOptional")}- </h4>- <ApiKeyInput- apiKey={customReasoningApiKey}- setApiKey={setCustomReasoningApiKey || (() => {})}- label=""- helpText={t("reasoning.custom.apiKeyHelp")}- />- </div>-- {/* 3. Model Selection - THIRD */}- <div className="space-y-2 pt-3">- <div className="flex items-center justify-between">- <h4 className="text-sm font-medium text-foreground">- {t("reasoning.availableModels")}- </h4>- <div className="flex gap-2">- <Button- type="button"- size="sm"- variant="outline"- onClick={handleResetCustomBase}- className="text-xs"- >- {t("common.reset")}- </Button>- <Button- type="button"- size="sm"- variant="outline"- onClick={handleRefreshCustomModels}- disabled={- customModelsLoading || (!trimmedCustomBase && !hasSavedCustomBase)- }- className="text-xs"- >- {customModelsLoading- ? t("common.loading")- : isCustomBaseDirty- ? t("reasoning.custom.applyAndRefresh")- : t("common.refresh")}- </Button>- </div>- </div>- <p className="text-xs text-muted-foreground">- {t("reasoning.custom.queryPrefix")}{" "}- <code>- {hasCustomBase- ? `${effectiveReasoningBase}/models`- : `${defaultOpenAIBase}/models`}- </code>{" "}- {t("reasoning.custom.querySuffix")}- </p>- {isCustomBaseDirty && (+ </div>+ <p className="text-xs text-muted-foreground">+ {t("reasoning.custom.queryPrefix")}{" "}+ <code>+ {hasCustomBase+ ? `${effectiveReasoningBase}/models`+ : `${defaultOpenAIBase}/models`}+ </code>{" "}+ {t("reasoning.custom.querySuffix")}+ </p>+ {isCustomBaseDirty && (+ <p className="text-xs text-primary">+ {t("reasoning.custom.modelsReloadHint")}+ </p>+ )}+ {!hasCustomBase && (+ <p className="text-xs text-warning">{t("reasoning.custom.enterEndpoint")}</p>+ )}+ {hasCustomBase && (+ <>+ {customModelsLoading && (<p className="text-xs text-primary">- {t("reasoning.custom.modelsReloadHint")}+ {t("reasoning.custom.fetchingModels")}</p>)}- {!hasCustomBase && (- <p className="text-xs text-warning">- {t("reasoning.custom.enterEndpoint")}- </p>- )}- {hasCustomBase && (- <>- {customModelsLoading && (- <p className="text-xs text-primary">- {t("reasoning.custom.fetchingModels")}- </p>- )}- {customModelsError && (- <p className="text-xs text-destructive">{customModelsError}</p>- )}- {!customModelsLoading &&- !customModelsError &&- customModelOptions.length === 0 && (- <p className="text-xs text-warning">- {t("reasoning.custom.noModels")}- </p>- )}- </>+ {customModelsError && (+ <p className="text-xs text-destructive">{customModelsError}</p>)}- <ModelCardList- models={selectedCloudModels}- selectedModel={reasoningModel}- onModelSelect={setReasoningModel}- />+ {!customModelsLoading &&+ !customModelsError &&+ customModelOptions.length === 0 && (+ <p className="text-xs text-warning">{t("reasoning.custom.noModels")}</p>+ )}+ </>+ )}+ <ModelCardList+ models={selectedCloudModels}+ selectedModel={reasoningModel}+ onModelSelect={setReasoningModel}+ />+ </div>+ </>+ ) : (+ <>+ {/* 1. API Key - TOP */}+ {selectedCloudProvider === "openai" && (+ <div className="space-y-2">+ <div className="flex items-baseline justify-between">+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>+ <a+ href="https://platform.openai.com/api-keys"+ target="_blank"+ rel="noopener noreferrer"+ onClick={createExternalLinkHandler(+ "https://platform.openai.com/api-keys"+ )}+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"+ >+ {t("reasoning.getApiKey")}+ </a>+ </div>+ <ApiKeyInput+ apiKey={openaiApiKey}+ setApiKey={setOpenaiApiKey}+ label=""+ helpText=""+ />+ </div>+ )}++ {selectedCloudProvider === "anthropic" && (+ <div className="space-y-2">+ <div className="flex items-baseline justify-between">+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>+ <a+ href="https://console.anthropic.com/settings/keys"+ target="_blank"+ rel="noopener noreferrer"+ onClick={createExternalLinkHandler(+ "https://console.anthropic.com/settings/keys"+ )}+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"+ >+ {t("reasoning.getApiKey")}+ </a></div>- </>- ) : (- <>- {/* 1. API Key - TOP */}- {selectedCloudProvider === "openai" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <a- href="https://platform.openai.com/api-keys"- target="_blank"- rel="noopener noreferrer"- onClick={createExternalLinkHandler(- "https://platform.openai.com/api-keys"- )}- className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"- >- {t("reasoning.getApiKey")}- </a>- </div>- <ApiKeyInput- apiKey={openaiApiKey}- setApiKey={setOpenaiApiKey}- label=""- helpText=""- />- </div>- )}-- {selectedCloudProvider === "anthropic" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <a- href="https://console.anthropic.com/settings/keys"- target="_blank"- rel="noopener noreferrer"- onClick={createExternalLinkHandler(- "https://console.anthropic.com/settings/keys"- )}- className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"- >- {t("reasoning.getApiKey")}- </a>- </div>- <ApiKeyInput- apiKey={anthropicApiKey}- setApiKey={setAnthropicApiKey}- placeholder="sk-ant-..."- label=""- helpText=""- />- </div>- )}-- {selectedCloudProvider === "gemini" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <a- href="https://aistudio.google.com/app/api-keys"- target="_blank"- rel="noopener noreferrer"- onClick={createExternalLinkHandler(- "https://aistudio.google.com/app/api-keys"- )}- className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"- >- {t("reasoning.getApiKey")}- </a>- </div>- <ApiKeyInput- apiKey={geminiApiKey}- setApiKey={setGeminiApiKey}- placeholder="AIza..."- label=""- helpText=""- />- </div>- )}-- {selectedCloudProvider === "groq" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <a- href="https://console.groq.com/keys"- target="_blank"- rel="noopener noreferrer"- onClick={createExternalLinkHandler("https://console.groq.com/keys")}- className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"- >- {t("reasoning.getApiKey")}- </a>- </div>- <ApiKeyInput- apiKey={groqApiKey}- setApiKey={setGroqApiKey}- placeholder="gsk_..."- label=""- helpText=""- />- </div>- )}-- {/* 2. Model Selection - BOTTOM */}- <div className="pt-3 space-y-2">- <h4 className="text-sm font-medium text-foreground">- {t("reasoning.selectModel")}- </h4>- <ModelCardList- models={selectedCloudModels}- selectedModel={reasoningModel}- onModelSelect={setReasoningModel}- />+ <ApiKeyInput+ apiKey={anthropicApiKey}+ setApiKey={setAnthropicApiKey}+ label=""+ helpText=""+ />+ </div>+ )}++ {selectedCloudProvider === "gemini" && (+ <div className="space-y-2">+ <div className="flex items-baseline justify-between">+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>+ <a+ href="https://aistudio.google.com/app/api-keys"+ target="_blank"+ rel="noopener noreferrer"+ onClick={createExternalLinkHandler(+ "https://aistudio.google.com/app/api-keys"+ )}+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"+ >+ {t("reasoning.getApiKey")}+ </a>+ </div>+ <ApiKeyInput+ apiKey={geminiApiKey}+ setApiKey={setGeminiApiKey}+ label=""+ helpText=""+ />+ </div>+ )}++ {selectedCloudProvider === "groq" && (+ <div className="space-y-2">+ <div className="flex items-baseline justify-between">+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>+ <a+ href="https://console.groq.com/keys"+ target="_blank"+ rel="noopener noreferrer"+ onClick={createExternalLinkHandler("https://console.groq.com/keys")}+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors"+ >+ {t("reasoning.getApiKey")}+ </a></div>- </>+ <ApiKeyInput+ apiKey={groqApiKey}+ setApiKey={setGroqApiKey}+ label=""+ helpText=""+ />+ </div>)}- </div>- </div>++ {/* 2. Model Selection - BOTTOM */}+ <div className="pt-3 space-y-2">+ <h4 className="text-sm font-medium text-foreground">+ {t("reasoning.selectModel")}+ </h4>+ <ModelCardList+ models={selectedCloudModels}+ selectedModel={reasoningModel}+ onModelSelect={setReasoningModel}+ />+ </div>+ </>+ )}</div>- ) : (- <LocalModelPicker- providers={localProviders}- selectedModel={reasoningModel}- selectedProvider={selectedLocalProvider}- onModelSelect={setReasoningModel}- onProviderSelect={handleLocalProviderChange}- modelType="llm"- colorScheme="purple"- onDownloadComplete={loadDownloadedModels}- />- )}- </>+ </div>+ </div>+ ) : (+ <LocalModelPicker+ providers={localProviders}+ selectedModel={reasoningModel}+ selectedProvider={selectedLocalProvider}+ onModelSelect={setReasoningModel}+ onProviderSelect={handleLocalProviderChange}+ modelType="llm"+ colorScheme="purple"+ onDownloadComplete={loadDownloadedModels}+ />)}</div>);diff --git a/src/components/ReferralDashboard.tsx b/src/components/ReferralDashboard.tsxnew file mode 100644index 000000000..2bac83d75--- /dev/null+++ b/src/components/ReferralDashboard.tsx@@ -0,0 +1,591 @@+import React, { useEffect, useState, useCallback, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Send, Mail, Copy, Check, Link, UserPlus, Gift, CheckCircle2, User } from "lucide-react";+import { Badge } from "./ui/badge";+import { Tabs, TabsList, TabsTrigger, TabsContent } from "./ui/tabs";+import { useToast } from "./ui/Toast";+import { cn } from "./lib/utils";+import { SpectrogramCard } from "./referral-cards/SpectrogramCard";+import logger from "../utils/logger";++const REFERRAL_WORD_GOAL = 2000;+const RE_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++interface ReferralStats {+ referralCode: string;+ referralLink: string;+ totalReferrals: number;+ completedReferrals: number;+ totalMonthsEarned: number;+ referrals: Referral[];+}++interface Referral {+ id: string;+ email: string;+ name: string;+ status: "pending" | "completed" | "rewarded";+ created_at: string;+ words_used: number;+}++interface ReferralInvite {+ id: string;+ recipientEmail: string;+ status: "sent" | "opened" | "converted" | "failed";+ sentAt: string;+ openedAt?: string;+ convertedAt?: string;+}++const statusVariants: Record<+ ReferralInvite["status"],+ "success" | "info" | "destructive" | "outline"+> = {+ converted: "success",+ opened: "info",+ failed: "destructive",+ sent: "outline",+};++function formatDate(dateStr: string) {+ const date = new Date(dateStr);+ return date.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ ...(date.getFullYear() !== new Date().getFullYear() && { year: "numeric" }),+ });+}++function AnimatedCounter({ value, delay = 0 }: { value: number; delay?: number }) {+ const [display, setDisplay] = useState(0);+ const rafRef = useRef<number>(0);++ useEffect(() => {+ if (value === 0) {+ setDisplay(0);+ return;+ }++ const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ if (prefersReduced) {+ setDisplay(value);+ return;+ }++ const duration = 800;+ let start: number | null = null;++ const timeout = setTimeout(() => {+ const animate = (timestamp: number) => {+ if (!start) start = timestamp;+ const progress = Math.min((timestamp - start) / duration, 1);+ const eased = 1 - Math.pow(1 - progress, 3);+ setDisplay(Math.round(eased * value));+ if (progress < 1) rafRef.current = requestAnimationFrame(animate);+ };+ rafRef.current = requestAnimationFrame(animate);+ }, delay);++ return () => {+ clearTimeout(timeout);+ cancelAnimationFrame(rafRef.current);+ };+ }, [value, delay]);++ return <span className="tabular-nums">{display}</span>;+}++function TiltCard({ children, className }: { children: React.ReactNode; className?: string }) {+ const cardRef = useRef<HTMLDivElement>(null);+ const rafRef = useRef<number>(0);+ const prefersReducedMotion = useRef(+ window.matchMedia("(prefers-reduced-motion: reduce)").matches+ );++ const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {+ const card = cardRef.current;+ if (!card) return;+ if (prefersReducedMotion.current) return;++ cancelAnimationFrame(rafRef.current);+ rafRef.current = requestAnimationFrame(() => {+ const rect = card.getBoundingClientRect();+ const centerX = rect.left + rect.width / 2;+ const centerY = rect.top + rect.height / 2;+ const nx = (e.clientX - centerX) / (rect.width / 2);+ const ny = (e.clientY - centerY) / (rect.height / 2);+ const tiltX = -ny * 4;+ const tiltY = nx * 4;+ const hx = ((e.clientX - rect.left) / rect.width) * 100;+ const hy = ((e.clientY - rect.top) / rect.height) * 100;++ card.style.setProperty("--tilt-x", `${tiltX}deg`);+ card.style.setProperty("--tilt-y", `${tiltY}deg`);+ card.style.setProperty("--highlight-x", `${hx}%`);+ card.style.setProperty("--highlight-y", `${hy}%`);+ card.style.setProperty("--highlight-opacity", "1");+ });+ }, []);++ const handleMouseLeave = useCallback(() => {+ const card = cardRef.current;+ if (!card) return;+ card.style.setProperty("--tilt-x", "0deg");+ card.style.setProperty("--tilt-y", "0deg");+ card.style.setProperty("--highlight-opacity", "0");+ }, []);++ return (+ <div+ ref={cardRef}+ onMouseMove={handleMouseMove}+ onMouseLeave={handleMouseLeave}+ className={cn("tilt-card", className)}+ >+ {children}+ </div>+ );+}++function StatGauge({+ value,+ label,+ delay = 0,+ highlight = false,+}: {+ value: number;+ label: string;+ delay?: number;+ highlight?: boolean;+}) {+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ const timer = setTimeout(() => setMounted(true), delay + 400);+ return () => clearTimeout(timer);+ }, [delay]);++ return (+ <div+ className={cn(+ "stat-gauge rounded-md px-3 py-2.5",+ "bg-foreground/3 border border-foreground/6",+ "backdrop-blur-sm"+ )}+ data-active={mounted && value > 0 ? "true" : "false"}+ >+ <div+ className={cn(+ "text-lg font-bold tabular-nums leading-none",+ highlight ? "text-success" : "text-foreground"+ )}+ >+ <AnimatedCounter value={value} delay={delay} />+ </div>+ <div className="text-xs text-foreground/30 mt-1 leading-tight">{label}</div>+ </div>+ );+}++export function ReferralDashboard() {+ const { t } = useTranslation();+ const [stats, setStats] = useState<ReferralStats | null>(null);+ const [invites, setInvites] = useState<ReferralInvite[]>([]);+ const [copied, setCopied] = useState(false);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [emailInput, setEmailInput] = useState("");+ const [sendingInvite, setSendingInvite] = useState(false);+ const { toast } = useToast();++ const fetchStats = useCallback(async () => {+ try {+ setLoading(true);+ setError(null);+ const data = await window.electronAPI?.getReferralStats?.();+ setStats(data ?? null);+ } catch (err) {+ logger.error("Failed to fetch referral stats", { error: err }, "referral");+ setError(t("referral.errors.unableToLoadStats"));+ } finally {+ setLoading(false);+ }+ }, [t]);++ const fetchInvites = useCallback(async () => {+ try {+ const result = await window.electronAPI?.getReferralInvites?.();+ setInvites(result?.invites ?? []);+ } catch (err) {+ logger.error("Failed to fetch referral invites", { error: err }, "referral");+ }+ }, []);++ useEffect(() => {+ fetchStats();+ fetchInvites();+ }, [fetchStats, fetchInvites]);++ const copyLink = async () => {+ if (!stats) return;+ try {+ await navigator.clipboard.writeText(stats.referralLink);+ setCopied(true);+ toast({+ title: t("referral.toasts.copiedTitle"),+ description: t("referral.toasts.copiedDescription"),+ variant: "success",+ duration: 2000,+ });+ setTimeout(() => setCopied(false), 2000);+ } catch (err) {+ logger.error("Failed to copy link", { error: err }, "referral");+ toast({+ title: t("referral.toasts.copyFailedTitle"),+ description: t("referral.toasts.copyFailedDescription"),+ variant: "destructive",+ });+ }+ };++ const sendInvite = async () => {+ if (!emailInput.trim()) return;++ if (!RE_EMAIL.test(emailInput.trim())) {+ toast({+ title: t("referral.toasts.invalidEmailTitle"),+ description: t("referral.toasts.invalidEmailDescription"),+ variant: "destructive",+ });+ return;+ }++ try {+ setSendingInvite(true);+ const result = await window.electronAPI?.sendReferralInvite?.(emailInput.trim());++ if (result?.success) {+ toast({+ title: t("referral.toasts.inviteSentTitle"),+ description: t("referral.toasts.inviteSentDescription", { email: emailInput }),+ variant: "success",+ });+ setEmailInput("");+ fetchInvites();+ } else {+ throw new Error("Failed to send invite");+ }+ } catch (err) {+ logger.error("Failed to send invite", { error: err }, "referral");+ toast({+ title: t("referral.toasts.sendFailedTitle"),+ description: t("referral.toasts.sendFailedDescription"),+ variant: "destructive",+ });+ } finally {+ setSendingInvite(false);+ }+ };++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter" && !sendingInvite) {+ sendInvite();+ }+ };++ if (loading) {+ return (+ <div className="bg-card px-7 pt-9 pb-6">+ <div className="h-5 w-36 rounded bg-foreground/4 animate-pulse" />+ <div className="h-3 w-44 rounded bg-foreground/3 animate-pulse mt-2" />+ <div className="h-16 rounded-lg bg-foreground/3 animate-pulse mt-5" />+ <div className="grid grid-cols-3 gap-2.5 mt-5">+ <div className="h-14 rounded-md bg-foreground/3 animate-pulse" />+ <div className="h-14 rounded-md bg-foreground/3 animate-pulse" />+ <div className="h-14 rounded-md bg-foreground/3 animate-pulse" />+ </div>+ <div className="h-px bg-foreground/4 mt-5" />+ <div className="h-3 w-20 rounded bg-foreground/3 animate-pulse mt-5" />+ <div className="h-8 rounded-md bg-foreground/3 animate-pulse mt-2" />+ </div>+ );+ }++ if (error || !stats) {+ return (+ <div className="flex flex-col items-center justify-center h-85 bg-card text-center px-6">+ <p className="text-xs text-foreground/40 mb-3">+ {error || t("referral.errors.unableToLoad")}+ </p>+ <button+ onClick={fetchStats}+ aria-label={t("referral.tryAgain")}+ className="px-3.5 py-1.5 rounded-md text-xs font-medium bg-foreground/7 text-foreground/55 border border-foreground/5 hover:bg-foreground/12 hover:text-foreground/90 transition-colors duration-200"+ >+ {t("referral.tryAgain")}+ </button>+ </div>+ );+ }++ return (+ <div className="relative bg-card">+ {/* Animated mesh gradient background */}+ <div className="referral-mesh-bg">+ <div+ className="absolute w-50 h-50 rounded-full blur-[80px] opacity-3"+ style={{+ background: "oklch(0.55 0.2 320)",+ top: "40%",+ left: "15%",+ animation: "mesh-drift 25s ease-in-out infinite alternate",+ animationDelay: "-8s",+ }}+ />+ </div>++ <div className="relative z-10 px-7 pt-7 pb-6">+ <h2 className="text-xl font-bold tracking-tight leading-tight text-foreground">+ {t("referral.title")}+ </h2>+ <p className="text-xs text-foreground/30 mt-1">{t("referral.subtitle")}</p>++ <Tabs defaultValue="refer" className="mt-4">+ <TabsList className="w-full justify-start bg-transparent! p-0! h-auto! gap-4 rounded-none! border-b border-foreground/6">+ <TabsTrigger+ value="refer"+ className="rounded-none! bg-transparent! shadow-none! px-0! pb-2! pt-0! text-xs border-b-2 border-transparent text-foreground/30 hover:text-foreground/50 data-[state=active]:bg-transparent! data-[state=active]:shadow-none! data-[state=active]:border-foreground/50 data-[state=active]:text-foreground"+ >+ {t("referral.tabs.refer")}+ </TabsTrigger>+ <TabsTrigger+ value="history"+ className="rounded-none! bg-transparent! shadow-none! px-0! pb-2! pt-0! text-xs border-b-2 border-transparent text-foreground/30 hover:text-foreground/50 data-[state=active]:bg-transparent! data-[state=active]:shadow-none! data-[state=active]:border-foreground/50 data-[state=active]:text-foreground"+ >+ {t("referral.tabs.pastInvites")} ({invites.length})+ </TabsTrigger>+ </TabsList>++ <TabsContent value="refer" className="mt-5">+ <div className="space-y-5">+ <TiltCard>+ <SpectrogramCard referralCode={stats.referralCode} />+ </TiltCard>++ <div className="space-y-1.5">+ <div className="flex items-center gap-2.5">+ <div className="w-5 h-5 rounded bg-foreground/4 flex items-center justify-center shrink-0">+ <Link className="w-2.5 h-2.5 text-foreground/30" />+ </div>+ <span className="text-xs text-foreground/40">+ {t("referral.howItWorks.shareLink")}+ </span>+ </div>+ <div className="flex items-center gap-2.5">+ <div className="w-5 h-5 rounded bg-foreground/4 flex items-center justify-center shrink-0">+ <UserPlus className="w-2.5 h-2.5 text-foreground/30" />+ </div>+ <span className="text-xs text-foreground/40">+ {t("referral.howItWorks.theySignUp")}+ <strong className="text-foreground/60">+ {t("referral.howItWorks.freeMonthOfPro")}+ </strong>+ </span>+ </div>+ <div className="flex items-center gap-2.5">+ <div className="w-5 h-5 rounded bg-foreground/4 flex items-center justify-center shrink-0">+ <Gift className="w-2.5 h-2.5 text-foreground/30" />+ </div>+ <span className="text-xs text-foreground/40">+ {t("referral.howItWorks.youGet")}+ <strong className="text-foreground/60">+ {t("referral.howItWorks.freeMonth")}+ </strong>+ {t("referral.howItWorks.whenTheyDictate")}+ </span>+ </div>+ </div>++ <div className="space-y-2">+ <h4 className="text-xs font-medium text-foreground/25 uppercase tracking-wider">+ {t("referral.inviteLink.title")}+ </h4>+ <div className="flex items-center gap-2">+ <div className="flex-1 flex items-center gap-2 h-8 px-3 rounded-md bg-foreground/4 border border-foreground/7 overflow-hidden">+ <Link className="w-3 h-3 text-foreground/20 shrink-0" />+ <span className="text-xs text-foreground/50 font-mono truncate select-all">+ {stats.referralLink}+ </span>+ </div>+ <button+ onClick={copyLink}+ aria-label={t("referral.inviteLink.copy")}+ className={cn(+ "shrink-0 h-8 px-3.5 rounded-md text-xs font-medium flex items-center gap-1.5 transition-[background-color,color,transform] duration-200 active:scale-[0.97]",+ copied+ ? "bg-emerald-500/15 text-emerald-400/80"+ : "bg-foreground/7 text-foreground/55 border border-foreground/5 hover:bg-foreground/12 hover:text-foreground/90"+ )}+ >+ {copied ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}+ {copied ? t("referral.inviteLink.copied") : t("referral.inviteLink.copy")}+ </button>+ </div>+ </div>++ <div className="space-y-2">+ <h4 className="text-xs font-medium text-foreground/25 uppercase tracking-wider">+ {t("referral.sendInvites.title")}+ </h4>+ <div className="flex items-center gap-2">+ <input+ type="email"+ placeholder={t("referral.sendInvites.placeholder")}+ value={emailInput}+ onChange={(e) => setEmailInput(e.target.value)}+ onKeyDown={handleKeyDown}+ disabled={sendingInvite}+ className="flex-1 h-8 px-3 text-xs rounded-md bg-foreground/4 border border-foreground/7 text-foreground/70 placeholder:text-foreground/20 focus:outline-none focus:border-foreground/15 focus:ring-1 focus:ring-foreground/10 disabled:opacity-50"+ />+ <button+ onClick={sendInvite}+ disabled={sendingInvite || !emailInput.trim()}+ aria-label={t("referral.sendInvites.send")}+ className="shrink-0 h-8 px-3.5 rounded-md text-xs font-medium flex items-center gap-1.5 transition-[background-color,color,transform] duration-200 bg-foreground/7 text-foreground/55 border border-foreground/5 hover:bg-foreground/12 hover:text-foreground/90 active:scale-[0.97] disabled:opacity-40 disabled:pointer-events-none"+ >+ {sendingInvite ? (+ <div className="w-3 h-3 border-1.5 border-current border-r-transparent rounded-full animate-spin" />+ ) : (+ <Send className="w-3 h-3" />+ )}+ {sendingInvite+ ? t("referral.sendInvites.sending")+ : t("referral.sendInvites.send")}+ </button>+ </div>+ </div>+ </div>+ </TabsContent>++ <TabsContent value="history" className="mt-5">+ <div className="grid grid-cols-3 gap-2.5">+ <StatGauge+ value={stats.totalReferrals}+ label={t("referral.stats.referred")}+ delay={0}+ />+ <StatGauge+ value={stats.completedReferrals}+ label={t("referral.stats.converted")}+ delay={150}+ />+ <StatGauge+ value={stats.totalMonthsEarned}+ label={t("referral.stats.monthsEarned")}+ delay={300}+ highlight={stats.totalMonthsEarned > 0}+ />+ </div>++ {/* Friends section — actual signups with word progress */}+ {stats.referrals && stats.referrals.length > 0 && (+ <div className="mt-5">+ <h4 className="text-xs font-medium text-foreground/25 uppercase tracking-wider mb-2">+ {t("referral.friends.title")}+ </h4>+ <div className="space-y-1.5">+ {stats.referrals.map((referral) => {+ const isComplete = referral.status === "rewarded";+ const wordsUsed = Math.min(referral.words_used, REFERRAL_WORD_GOAL);+ const progress = Math.round((wordsUsed / REFERRAL_WORD_GOAL) * 100);+ const displayName = referral.name || referral.email;++ return (+ <div+ key={referral.id}+ className="py-2 px-2.5 rounded-md bg-foreground/3 border border-foreground/5"+ >+ <div className="flex items-center justify-between mb-1.5">+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <User className="w-3 h-3 text-foreground/20 shrink-0" />+ <span className="text-xs text-foreground/60 truncate">+ {displayName}+ </span>+ </div>+ {isComplete ? (+ <div className="flex items-center gap-1 ml-2 shrink-0">+ <CheckCircle2 className="w-3 h-3 text-emerald-400/80" />+ <span className="text-xs text-emerald-400/80 font-medium">+ {t("referral.friends.completed")}+ </span>+ </div>+ ) : (+ <span className="text-xs text-foreground/30 tabular-nums ml-2 shrink-0">+ {wordsUsed.toLocaleString()} / {REFERRAL_WORD_GOAL.toLocaleString()}+ </span>+ )}+ </div>+ <div className="h-1 rounded-full bg-foreground/6 overflow-hidden">+ <div+ className={cn(+ "h-full rounded-full transition-[width] duration-500",+ isComplete ? "bg-emerald-400/60" : "bg-foreground/20"+ )}+ style={{ width: `${progress}%` }}+ />+ </div>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Sent Invites section */}+ {invites.length > 0 ? (+ <div className="mt-5">+ <h4 className="text-xs font-medium text-foreground/25 uppercase tracking-wider mb-2">+ {t("referral.friends.sentInvites")}+ </h4>+ <div className="space-y-1">+ {invites.map((invite) => {+ const variant = statusVariants[invite.status] ?? statusVariants.sent;+ const label = t(`referral.status.${invite.status}`);+ return (+ <div+ key={invite.id}+ className="flex items-center justify-between py-1.5 px-2.5 rounded-md bg-foreground/3 border border-foreground/5 hover:border-foreground/8 transition-colors"+ >+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <Mail className="w-3 h-3 text-foreground/20 shrink-0" />+ <span className="text-xs text-foreground/60 truncate">+ {invite.recipientEmail}+ </span>+ <span className="text-xs text-foreground/15 shrink-0">+ {formatDate(invite.sentAt)}+ </span>+ </div>+ <Badge variant={variant} className="ml-2 text-xs shrink-0">+ {label}+ </Badge>+ </div>+ );+ })}+ </div>+ </div>+ ) : !stats.referrals?.length ? (+ <div className="flex flex-col items-center justify-center py-12 text-center">+ <Mail className="w-5 h-5 text-foreground/10 mb-2" />+ <p className="text-xs text-foreground/25">{t("referral.empty.title")}</p>+ <p className="text-xs text-foreground/15 mt-0.5">+ {t("referral.empty.description")}+ </p>+ </div>+ ) : null}+ </TabsContent>+ </Tabs>+ </div>+ </div>+ );+}diff --git a/src/components/ReferralModal.tsx b/src/components/ReferralModal.tsxnew file mode 100644index 000000000..a5d0c1bab--- /dev/null+++ b/src/components/ReferralModal.tsx@@ -0,0 +1,53 @@+import React from "react";+import { useTranslation } from "react-i18next";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { X } from "lucide-react";+import { cn } from "./lib/utils";+import { ReferralDashboard } from "./ReferralDashboard";++interface ReferralModalProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function ReferralModal({ open, onOpenChange }: ReferralModalProps) {+ const { t } = useTranslation();+ return (+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay+ className={cn(+ "fixed inset-0 z-50 bg-black/60 backdrop-blur-lg",+ "data-[state=open]:animate-in data-[state=closed]:animate-out",+ "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"+ )}+ />+ <DialogPrimitive.Content+ className={cn(+ "fixed left-[50%] top-[50%] z-50 w-full max-w-[500px] min-h-130",+ "translate-x-[-50%] translate-y-[-50%]",+ "rounded-xl border overflow-hidden shadow-2xl duration-200",+ "bg-card border-border",+ "shadow-[0_24px_48px_-12px_oklch(0_0_0/0.12)] dark:shadow-[0_24px_48px_-12px_oklch(0_0_0/0.5)]",+ "data-[state=open]:animate-in data-[state=closed]:animate-out",+ "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ "data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",+ "data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]",+ "data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]"+ )}+ >+ <DialogPrimitive.Title className="sr-only">+ {t("referral.modalTitle")}+ </DialogPrimitive.Title>++ <DialogPrimitive.Close className="absolute right-3 top-3 z-20 rounded-full p-1.5 opacity-40 transition-[opacity,background-color] hover:opacity-80 hover:bg-foreground/10 focus:outline-none focus:ring-2 focus:ring-foreground/20 focus:ring-offset-0">+ <X className="h-4 w-4 text-foreground" />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>++ <ReferralDashboard />+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+}diff --git a/src/components/ResetPasswordView.tsx b/src/components/ResetPasswordView.tsxindex 51c4f5882..e853dbeed 100644--- a/src/components/ResetPasswordView.tsx+++ b/src/components/ResetPasswordView.tsx@@ -55,7 +55,7 @@ export default function ResetPasswordView({ token, onSuccess, onBack }: ResetPasreturn (<div className="space-y-3"><div className="bg-warning/5 p-2.5 rounded border border-warning/20">- <p className="text-[10px] text-warning text-center leading-snug">+ <p className="text-xs text-warning text-center leading-snug">{t("resetPassword.notConfigured")}</p></div>@@ -94,7 +94,7 @@ export default function ResetPasswordView({ token, onSuccess, onBack }: ResetPas<buttontype="button"onClick={onBack}- className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"><ArrowLeft className="w-3 h-3" />{t("resetPassword.backToSignIn")}@@ -132,14 +132,14 @@ export default function ResetPasswordView({ token, onSuccess, onBack }: ResetPasdisabled={isSubmitting}/>- <p className="text-[9px] text-muted-foreground/70 leading-tight">+ <p className="text-xs text-muted-foreground/70 leading-tight">{t("resetPassword.passwordMinLength")}</p>{error && (<div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5"><AlertCircle className="w-3 h-3 text-destructive shrink-0" />- <p className="text-[10px] text-destructive leading-snug">{error}</p>+ <p className="text-xs text-destructive leading-snug">{error}</p></div>)}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 8812686a9..b1f889b7a 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -4,23 +4,32 @@ import {Sliders,Mic,Brain,- User,- Sparkles,UserCircle,Wrench,- BookOpen,- ShieldCheck,- Lock,+ Keyboard,+ CreditCard,+ Shield,} from "lucide-react";import SidebarModal, { SidebarItem } from "./ui/SidebarModal";import SettingsPage, { SettingsSectionType } from "./SettingsPage";export type { SettingsSectionType };+// Maps old section IDs to new ones for backward-compatible deep-linking+const SECTION_ALIASES: Record<string, SettingsSectionType> = {+ aiModels: "intelligence",+ agentConfig: "intelligence",+ prompts: "intelligence",+ softwareUpdates: "system",+ privacy: "privacyData",+ permissions: "privacyData",+ developer: "system",+};+interface SettingsModalProps {open: boolean;onOpenChange: (open: boolean) => void;- initialSection?: SettingsSectionType;+ initialSection?: string;}export default function SettingsModal({ open, onOpenChange, initialSection }: SettingsModalProps) {@@ -32,7 +41,14 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Selabel: t("settingsModal.sections.account.label"),icon: UserCircle,description: t("settingsModal.sections.account.description"),- group: t("settingsModal.groups.profile"),+ group: t("settingsModal.groups.account"),+ },+ {+ id: "plansBilling",+ label: t("settingsModal.sections.plansBilling.label"),+ icon: CreditCard,+ description: t("settingsModal.sections.plansBilling.description"),+ group: t("settingsModal.groups.account"),},{id: "general",@@ -41,60 +57,39 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Sedescription: t("settingsModal.sections.general.description"),group: t("settingsModal.groups.app"),},+ {+ id: "hotkeys",+ label: t("settingsModal.sections.hotkeys.label"),+ icon: Keyboard,+ description: t("settingsModal.sections.hotkeys.description"),+ group: t("settingsModal.groups.app"),+ },{id: "transcription",label: t("settingsModal.sections.transcription.label"),icon: Mic,description: t("settingsModal.sections.transcription.description"),- group: t("settingsModal.groups.speech"),- },- {- id: "dictionary",- label: t("settingsModal.sections.dictionary.label"),- icon: BookOpen,- description: t("settingsModal.sections.dictionary.description"),- group: t("settingsModal.groups.speech"),+ group: t("settingsModal.groups.speechAi"),},{- id: "aiModels",- label: t("settingsModal.sections.aiModels.label"),+ id: "intelligence",+ label: t("settingsModal.sections.intelligence.label"),icon: Brain,- description: t("settingsModal.sections.aiModels.description"),- group: t("settingsModal.groups.intelligence"),- },- {- id: "agentConfig",- label: t("settingsModal.sections.agentConfig.label"),- icon: User,- description: t("settingsModal.sections.agentConfig.description"),- group: t("settingsModal.groups.intelligence"),- },- {- id: "prompts",- label: t("settingsModal.sections.prompts.label"),- icon: Sparkles,- description: t("settingsModal.sections.prompts.description"),- group: t("settingsModal.groups.intelligence"),- },- {- id: "privacy",- label: t("settingsModal.sections.privacy.label"),- icon: Lock,- description: t("settingsModal.sections.privacy.description"),- group: t("settingsModal.groups.system"),+ description: t("settingsModal.sections.intelligence.description"),+ group: t("settingsModal.groups.speechAi"),},{- id: "permissions",- label: t("settingsModal.sections.permissions.label"),- icon: ShieldCheck,- description: t("settingsModal.sections.permissions.description"),+ id: "privacyData",+ label: t("settingsModal.sections.privacyData.label"),+ icon: Shield,+ description: t("settingsModal.sections.privacyData.description"),group: t("settingsModal.groups.system"),},{- id: "developer",- label: t("settingsModal.sections.developer.label"),+ id: "system",+ label: t("settingsModal.sections.system.label"),icon: Wrench,- description: t("settingsModal.sections.developer.description"),+ description: t("settingsModal.sections.system.description"),group: t("settingsModal.groups.system"),},],@@ -103,10 +98,11 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Seconst [activeSection, setActiveSection] = React.useState<SettingsSectionType>("account");- // Navigate to initial section when modal opens+ // Navigate to initial section when modal opens, resolving legacy aliasesuseEffect(() => {if (open && initialSection) {- setActiveSection(initialSection);+ const resolved = (SECTION_ALIASES[initialSection] ?? initialSection) as SettingsSectionType;+ setActiveSection(resolved);}}, [open, initialSection]);diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 5ddb7c094..1fd9f7513 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -17,13 +17,15 @@ import {Monitor,Cloud,Key,+ ChevronDown,Sparkles,AlertTriangle,Loader2,+ Check,+ Mail,} from "lucide-react";import { useAuth } from "../hooks/useAuth";import { NEON_AUTH_URL, signOut } from "../lib/neonAuth";-import MarkdownRenderer from "./ui/MarkdownRenderer";import MicPermissionWarning from "./ui/MicPermissionWarning";import MicrophoneSettings from "./ui/MicrophoneSettings";import PermissionCard from "./ui/PermissionCard";@@ -41,12 +43,12 @@ import { useUpdater } from "../hooks/useUpdater";import PromptStudio from "./ui/PromptStudio";import ReasoningModelSelector from "./ReasoningModelSelector";-import { HotkeyInput } from "./ui/HotkeyInput";import HotkeyGuidanceAccordion from "./ui/HotkeyGuidanceAccordion";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";import { getValidationMessage } from "../utils/hotkeyValidator";import { getPlatform } from "../utils/platform";+import { getDefaultHotkey, formatHotkeyLabel } from "../utils/hotkeys";import { ActivationModeSelector } from "./ui/ActivationModeSelector";import { Toggle } from "./ui/toggle";import DeveloperSection from "./DeveloperSection";@@ -63,15 +65,13 @@ import { cn } from "./lib/utils";export type SettingsSectionType =| "account"+ | "plansBilling"| "general"+ | "hotkeys"| "transcription"- | "dictionary"- | "aiModels"- | "agentConfig"- | "prompts"- | "permissions"- | "privacy"- | "developer";+ | "intelligence"+ | "privacyData"+ | "system";interface SettingsPageProps {activeSection?: SettingsSectionType;@@ -119,9 +119,9 @@ function SettingsPanelRow({function SectionHeader({ title, description }: { title: string; description?: string }) {return (<div className="mb-3">- <h3 className="text-[13px] font-semibold text-foreground tracking-tight">{title}</h3>+ <h3 className="text-xs font-semibold text-foreground tracking-tight">{title}</h3>{description && (- <p className="text-[11px] text-muted-foreground/80 mt-0.5 leading-relaxed">{description}</p>+ <p className="text-xs text-muted-foreground/80 mt-0.5 leading-relaxed">{description}</p>)}</div>);@@ -191,7 +191,7 @@ function TranscriptionSection({setCloudTranscriptionBaseUrl,toast,}: TranscriptionSectionProps) {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const isCustomMode = cloudTranscriptionMode === "byok" || useLocalWhisper;const isCloudMode = isSignedIn && cloudTranscriptionMode === "openwhispr" && !useLocalWhisper;@@ -237,16 +237,16 @@ function TranscriptionSection({</div><div className="flex-1 min-w-0"><div className="flex items-center gap-2">- <span className="text-[12px] font-medium text-foreground">+ <span className="text-xs font-medium text-foreground">{t("settingsPage.transcription.openwhisprCloud")}</span>{isCloudMode && (- <span className="text-[10px] font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm">+ <span className="text-xs font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm">{t("common.active")}</span>)}</div>- <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ <p className="text-xs text-muted-foreground/80 mt-0.5">{t("settingsPage.transcription.openwhisprCloudDescription")}</p></div>@@ -297,16 +297,16 @@ function TranscriptionSection({</div><div className="flex-1 min-w-0"><div className="flex items-center gap-2">- <span className="text-[12px] font-medium text-foreground">+ <span className="text-xs font-medium text-foreground">{t("settingsPage.transcription.customSetup")}</span>{isCustomMode && (- <span className="text-[10px] font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm">+ <span className="text-xs font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm">{t("common.active")}</span>)}</div>- <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ <p className="text-xs text-muted-foreground/80 mt-0.5">{t("settingsPage.transcription.customSetupDescription")}</p></div>@@ -428,7 +428,7 @@ function AiModelsSection({showAlertDialog,toast,}: AiModelsSectionProps) {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const isCustomMode = cloudReasoningMode === "byok";const isCloudMode = isSignedIn && cloudReasoningMode === "openwhispr";@@ -486,16 +486,16 @@ function AiModelsSection({</div><div className="flex-1 min-w-0"><div className="flex items-center gap-2">- <span className="text-[12px] font-medium text-foreground">+ <span className="text-xs font-medium text-foreground">{t("settingsPage.aiModels.openwhisprCloud")}</span>{isCloudMode && (- <span className="text-[10px] font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm">+ <span className="text-xs font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm">{t("common.active")}</span>)}</div>- <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ <p className="text-xs text-muted-foreground/80 mt-0.5">{t("settingsPage.aiModels.openwhisprCloudDescription")}</p></div>@@ -544,16 +544,16 @@ function AiModelsSection({</div><div className="flex-1 min-w-0"><div className="flex items-center gap-2">- <span className="text-[12px] font-medium text-foreground">+ <span className="text-xs font-medium text-foreground">{t("settingsPage.aiModels.customSetup")}</span>{isCustomMode && (- <span className="text-[10px] font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm">+ <span className="text-xs font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm">{t("common.active")}</span>)}</div>- <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ <p className="text-xs text-muted-foreground/80 mt-0.5">{t("settingsPage.aiModels.customSetupDescription")}</p></div>@@ -578,8 +578,6 @@ function AiModelsSection({{/* Custom Setup model picker — shown when Custom Setup is active or not signed in */}{(isCustomMode || !isSignedIn) && (<ReasoningModelSelector- useReasoningModel={useReasoningModel}- setUseReasoningModel={setUseReasoningModel}reasoningModel={reasoningModel}setReasoningModel={setReasoningModel}localReasoningProvider={reasoningProvider}@@ -626,7 +624,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagecloudTranscriptionModel,cloudTranscriptionBaseUrl,cloudReasoningBaseUrl,- customDictionary,useReasoningModel,reasoningModel,reasoningProvider,@@ -651,7 +648,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagesetCloudTranscriptionModel,setCloudTranscriptionBaseUrl,setCloudReasoningBaseUrl,- setCustomDictionary,setUseReasoningModel,setReasoningModel,setReasoningProvider,@@ -679,6 +675,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagesetCloudBackupEnabled,telemetryEnabled,setTelemetryEnabled,+ customDictionary,+ setCustomDictionary,} = useSettings();const { t, i18n } = useTranslation();@@ -755,24 +753,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagereturn "linux";}, []);- const [newDictionaryWord, setNewDictionaryWord] = useState("");-- const handleAddDictionaryWord = useCallback(() => {- const word = newDictionaryWord.trim();- if (word && !customDictionary.includes(word)) {- setCustomDictionary([...customDictionary, word]);- setNewDictionaryWord("");- }- }, [newDictionaryWord, customDictionary, setCustomDictionary]);-- const handleRemoveDictionaryWord = useCallback(- (wordToRemove: string) => {- if (wordToRemove === agentName) return;- setCustomDictionary(customDictionary.filter((word) => word !== wordToRemove));- },- [customDictionary, setCustomDictionary, agentName]- );-const [autoStartEnabled, setAutoStartEnabled] = useState(false);const [autoStartLoading, setAutoStartLoading] = useState(true);@@ -940,6 +920,20 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageconst { isSignedIn, isLoaded, user } = useAuth();const [isSigningOut, setIsSigningOut] = useState(false);const [isOpeningBilling, setIsOpeningBilling] = useState(false);+ const [billingPeriod, setBillingPeriod] = useState<"monthly" | "annual">("monthly");++ useEffect(() => {+ if (usage?.billingInterval) {+ setBillingPeriod(usage.billingInterval);+ }+ }, [usage?.billingInterval]);++ const startOnboarding = useCallback(() => {+ localStorage.setItem("pendingCloudMigration", "true");+ localStorage.setItem("onboardingCurrentStep", "0");+ localStorage.removeItem("onboardingCompleted");+ window.location.reload();+ }, []);const handleSignOut = useCallback(async () => {setIsSigningOut(true);@@ -997,224 +991,16 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage)}</div><div className="min-w-0 flex-1">- <p className="text-[13px] font-medium text-foreground truncate">+ <p className="text-xs font-medium text-foreground truncate">{user.name || t("settingsPage.account.user")}</p>- <p className="text-[11px] text-muted-foreground truncate">{user.email}</p>+ <p className="text-xs text-muted-foreground truncate">{user.email}</p></div><Badge variant="success">{t("settingsPage.account.signedIn")}</Badge></div></SettingsPanelRow></SettingsPanel>- <SectionHeader title={t("settingsPage.account.planTitle")} />- {!usage || !usage.hasLoaded ? (- <SettingsPanel>- <SettingsPanelRow>- <div className="flex items-center justify-between">- <Skeleton className="h-4 w-24" />- <Skeleton className="h-5 w-16 rounded-full" />- </div>- </SettingsPanelRow>- <SettingsPanelRow>- <div className="space-y-2">- <Skeleton className="h-3 w-48" />- <Skeleton className="h-8 w-full rounded" />- </div>- </SettingsPanelRow>- </SettingsPanel>- ) : (- <SettingsPanel>- {usage.isPastDue && (- <SettingsPanelRow>- <Alert- variant="warning"- className="dark:bg-amber-950/50 dark:border-amber-800 dark:text-amber-200 dark:[&>svg]:text-amber-400"- >- <AlertTriangle className="h-4 w-4" />- <AlertTitle>{t("settingsPage.account.pastDue.title")}</AlertTitle>- <AlertDescription>- {t("settingsPage.account.pastDue.description")}- </AlertDescription>- </Alert>- </SettingsPanelRow>- )}-- <SettingsPanelRow>- <SettingsRow- label={- usage.isTrial- ? t("settingsPage.account.planLabels.trial")- : usage.isPastDue- ? t("settingsPage.account.planLabels.free")- : usage.isSubscribed- ? t("settingsPage.account.planLabels.pro")- : t("settingsPage.account.planLabels.free")- }- description={- usage.isTrial- ? t("settingsPage.account.planDescriptions.trial", {- days: usage.trialDaysLeft,- })- : usage.isPastDue- ? t("settingsPage.account.planDescriptions.pastDue", {- used: usage.wordsUsed.toLocaleString(i18n.language),- limit: usage.limit.toLocaleString(i18n.language),- })- : usage.isSubscribed- ? usage.currentPeriodEnd- ? t("settingsPage.account.planDescriptions.nextBilling", {- date: new Date(usage.currentPeriodEnd).toLocaleDateString(- i18n.language,- { month: "short", day: "numeric", year: "numeric" }- ),- })- : t("settingsPage.account.planDescriptions.unlimited")- : t("settingsPage.account.planDescriptions.freeUsage", {- used: usage.wordsUsed.toLocaleString(i18n.language),- limit: usage.limit.toLocaleString(i18n.language),- })- }- >- {usage.isTrial ? (- <Badge variant="info">{t("settingsPage.account.badges.trial")}</Badge>- ) : usage.isPastDue ? (- <Badge variant="destructive">- {t("settingsPage.account.badges.pastDue")}- </Badge>- ) : usage.isSubscribed ? (- <Badge variant="success">{t("settingsPage.account.badges.pro")}</Badge>- ) : usage.isOverLimit ? (- <Badge variant="warning">- {t("settingsPage.account.badges.limitReached")}- </Badge>- ) : (- <Badge variant="outline">{t("settingsPage.account.badges.free")}</Badge>- )}- </SettingsRow>- </SettingsPanelRow>-- {!usage.isSubscribed && !usage.isTrial && (- <SettingsPanelRow>- <div className="space-y-1.5">- <Progress- value={- usage.limit > 0- ? Math.min(100, (usage.wordsUsed / usage.limit) * 100)- : 0- }- className={cn(- "h-1.5",- usage.isOverLimit- ? "[&>div]:bg-destructive"- : usage.isApproachingLimit- ? "[&>div]:bg-warning"- : "[&>div]:bg-primary"- )}- />- <div className="flex items-center justify-between text-[11px] text-muted-foreground">- <span className="tabular-nums">- {usage.wordsUsed.toLocaleString(i18n.language)} /{" "}- {usage.limit.toLocaleString(i18n.language)}- </span>- {usage.isApproachingLimit && (- <span className="text-warning">- {t("settingsPage.account.wordsRemaining", {- remaining: usage.wordsRemaining.toLocaleString(i18n.language),- })}- </span>- )}- {!usage.isApproachingLimit && !usage.isOverLimit && (- <span>{t("settingsPage.account.rollingWeeklyLimit")}</span>- )}- </div>- </div>- </SettingsPanelRow>- )}-- <SettingsPanelRow>- {usage.isPastDue ? (- <Button- onClick={async () => {- setIsOpeningBilling(true);- try {- const result = await usage.openBillingPortal();- if (!result.success) {- toast({- title: t("settingsPage.account.billing.couldNotOpenTitle"),- description: t(- "settingsPage.account.billing.couldNotOpenDescription"- ),- variant: "destructive",- });- }- } finally {- setIsOpeningBilling(false);- }- }}- disabled={isOpeningBilling}- size="sm"- className="w-full"- >- {isOpeningBilling ? (- <>- <Loader2 size={14} className="animate-spin" />- {t("settingsPage.account.billing.opening")}- </>- ) : (- t("settingsPage.account.billing.updatePaymentMethod")- )}- </Button>- ) : usage.isSubscribed && !usage.isTrial ? (- <Button- onClick={async () => {- const result = await usage.openBillingPortal();- if (!result.success) {- toast({- title: t("settingsPage.account.billing.couldNotOpenTitle"),- description: t(- "settingsPage.account.billing.couldNotOpenDescription"- ),- variant: "destructive",- });- }- }}- variant="outline"- size="sm"- className="w-full"- disabled={usage.checkoutLoading}- >- {usage.checkoutLoading- ? t("settingsPage.account.billing.opening")- : t("settingsPage.account.billing.manageBilling")}- </Button>- ) : (- <Button- onClick={async () => {- const result = await usage.openCheckout();- if (!result.success) {- toast({- title: t("settingsPage.account.checkout.couldNotOpenTitle"),- description: t(- "settingsPage.account.checkout.couldNotOpenDescription"- ),- variant: "destructive",- });- }- }}- size="sm"- className="w-full"- disabled={usage.checkoutLoading}- >- {usage.checkoutLoading- ? t("settingsPage.account.checkout.opening")- : t("settingsPage.account.checkout.upgradeToPro")}- </Button>- )}- </SettingsPanelRow>- </SettingsPanel>- )}-<SettingsPanel><SettingsPanelRow><Button@@ -1253,23 +1039,14 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div><div className="min-w-0 flex-1 space-y-2.5"><div>- <p className="text-[13px] font-medium text-foreground">+ <p className="text-xs font-medium text-foreground">{t("settingsPage.account.trialCta.title")}</p>- <p className="text-[11px] text-muted-foreground leading-relaxed mt-0.5">+ <p className="text-xs text-muted-foreground leading-relaxed mt-0.5">{t("settingsPage.account.trialCta.description")}</p></div>- <Button- onClick={() => {- localStorage.setItem("pendingCloudMigration", "true");- localStorage.setItem("onboardingCurrentStep", "0");- localStorage.removeItem("onboardingCompleted");- window.location.reload();- }}- size="sm"- className="w-full"- >+ <Button onClick={startOnboarding} size="sm" className="w-full"><UserCircle className="mr-1.5 h-3.5 w-3.5" />{t("settingsPage.account.trialCta.button")}</Button>@@ -1293,202 +1070,489 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div>);- case "general":+ case "plansBilling":return (- <div className="space-y-6">- {/* Updates */}- <div>- <SectionHeader title={t("settingsPage.general.updates.title")} />- <SettingsPanel>- <SettingsPanelRow>- <SettingsRow- label={t("settingsPage.general.updates.currentVersion")}- description={- updateStatus.isDevelopment- ? t("settingsPage.general.updates.devMode")- : isUpdateAvailable- ? t("settingsPage.general.updates.newVersionAvailable")- : t("settingsPage.general.updates.latestVersion")- }- >- <div className="flex items-center gap-2.5">- <span className="text-[13px] tabular-nums text-muted-foreground font-mono">- {currentVersion || t("settingsPage.general.updates.versionPlaceholder")}- </span>- {updateStatus.isDevelopment ? (- <Badge variant="warning">- {t("settingsPage.general.updates.badges.dev")}- </Badge>- ) : isUpdateAvailable ? (- <Badge variant="success">- {t("settingsPage.general.updates.badges.update")}- </Badge>- ) : (- <Badge variant="outline">- {t("settingsPage.general.updates.badges.latest")}- </Badge>- )}+ <div className="space-y-5">+ {!NEON_AUTH_URL ? (+ <>+ <SectionHeader+ title={t("settingsPage.account.pricing.title")}+ description={t("settingsPage.account.notConfigured")}+ />+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.account.featuresDisabled")}+ description={t("settingsPage.account.featuresDisabledDescription")}+ >+ <Badge variant="warning">{t("settingsPage.account.disabled")}</Badge>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ ) : isLoaded ? (+ <>+ <SectionHeader title={t("settingsPage.account.pricing.title")} />+ <div className="space-y-2.5">+ <div className="flex justify-center">+ <div className="inline-flex rounded-md bg-muted/40 dark:bg-surface-2/40 p-0.5 border border-border/30 dark:border-border-subtle/40">+ <button+ onClick={() => setBillingPeriod("monthly")}+ className={cn(+ "px-3 py-1 text-[11px] font-medium rounded-[3px] transition-all duration-150",+ billingPeriod === "monthly"+ ? "bg-background dark:bg-surface-raised text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {t("settingsPage.account.pricing.monthly")}+ </button>+ <button+ onClick={() => setBillingPeriod("annual")}+ className={cn(+ "px-3 py-1 text-[11px] font-medium rounded-[3px] transition-all duration-150 flex items-center gap-1",+ billingPeriod === "annual"+ ? "bg-background dark:bg-surface-raised text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {t("settingsPage.account.pricing.annual")}+ <span className="text-[9px] font-semibold text-primary">+ {t("settingsPage.account.pricing.annualBadge")}+ </span>+ </button></div>- </SettingsRow>- </SettingsPanelRow>+ </div>- <SettingsPanelRow>- <div className="space-y-2.5">- <Button- onClick={async () => {- try {- const result = await checkForUpdates();- if (result?.updateAvailable) {- showAlertDialog({- title: t(- "settingsPage.general.updates.dialogs.updateAvailable.title"- ),- description: t(- "settingsPage.general.updates.dialogs.updateAvailable.description",- {- version:- result.version || t("settingsPage.general.updates.newVersion"),- }- ),- });- } else {- showAlertDialog({- title: t("settingsPage.general.updates.dialogs.noUpdates.title"),- description:- result?.message ||- t("settingsPage.general.updates.dialogs.noUpdates.description"),- });- }- } catch (error: any) {- showAlertDialog({- title: t("settingsPage.general.updates.dialogs.checkFailed.title"),- description: t(- "settingsPage.general.updates.dialogs.checkFailed.description"- ),- });- }- }}- disabled={checkingForUpdates || updateStatus.isDevelopment}- variant="outline"- className="w-full"- size="sm"+ <div className="grid grid-cols-3 gap-2">+ {/* Free */}+ <div+ className={cn(+ "rounded-md border p-2.5 flex flex-col",+ !usage?.isSubscribed && !usage?.isTrial+ ? "border-primary/30 bg-primary/3 dark:border-primary/20 dark:bg-primary/5"+ : "border-border/50 dark:border-border-subtle/60 bg-card/30 dark:bg-surface-2/30"+ )}>- <RefreshCw- size={13}- className={`mr-1.5 ${checkingForUpdates ? "animate-spin" : ""}`}- />- {checkingForUpdates- ? t("settingsPage.general.updates.checking")- : t("settingsPage.general.updates.checkForUpdates")}- </Button>-- {isUpdateAvailable && !updateStatus.updateDownloaded && (- <div className="space-y-2">+ <p className="text-[11px] font-semibold text-foreground">+ {t("settingsPage.account.pricing.free.name")}+ </p>+ <div className="flex items-baseline gap-0.5 mt-0.5">+ <span className="text-sm font-bold text-foreground">+ {t("settingsPage.account.pricing.free.price")}+ </span>+ <span className="text-[9px] text-muted-foreground">+ {t("settingsPage.account.pricing.free.period")}+ </span>+ </div>+ <p className="text-[9px] font-medium text-primary/80 mt-1.5">+ {t("settingsPage.account.pricing.free.trialNote")}+ </p>+ <ul className="space-y-0.5 mt-2 flex-1">+ {(+ t("settingsPage.account.pricing.free.features", {+ returnObjects: true,+ }) as string[]+ ).map((feature, i) => (+ <li+ key={i}+ className="flex items-start gap-1 text-[10px] text-muted-foreground leading-tight"+ >+ <Check size={9} className="mt-[2px] text-primary/70 shrink-0" />+ {feature}+ </li>+ ))}+ </ul>+ {isSignedIn && !usage?.isSubscribed && !usage?.isTrial ? (+ <div className="mt-2 text-center">+ <span className="text-[9px] font-medium text-primary/70">+ {t("settingsPage.account.pricing.currentPlan")}+ </span>+ </div>+ ) : !isSignedIn ? (<Button- onClick={async () => {- try {- await downloadUpdate();- } catch (error: any) {- showAlertDialog({- title: t(- "settingsPage.general.updates.dialogs.downloadFailed.title"- ),- description: t(- "settingsPage.general.updates.dialogs.downloadFailed.description"- ),- });- }- }}- disabled={downloadingUpdate}- variant="success"- className="w-full"+ onClick={startOnboarding}+ variant="outline"size="sm"+ className="mt-2 w-full h-6 text-[10px]">- <Download- size={13}- className={`mr-1.5 ${downloadingUpdate ? "animate-pulse" : ""}`}- />- {downloadingUpdate- ? t("settingsPage.general.updates.downloading", {- progress: Math.round(updateDownloadProgress),- })- : t("settingsPage.general.updates.downloadUpdate", {- version: updateInfo?.version || "",- })}+ {t("settingsPage.account.signedOutPlans.button")}</Button>+ ) : null}+ </div>- {downloadingUpdate && (- <div className="h-1 w-full overflow-hidden rounded-full bg-muted/50">- <div- className="h-full bg-success transition-all duration-200 rounded-full"- style={{- width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%`,- }}- />- </div>+ {/* Pro */}+ <div+ className={cn(+ "rounded-md border-2 p-2.5 flex flex-col",+ usage?.isSubscribed || usage?.isTrial+ ? "border-primary/40 bg-primary/5 dark:border-primary/30 dark:bg-primary/8"+ : "border-primary/20 bg-primary/2 dark:border-primary/15 dark:bg-primary/3"+ )}+ >+ <p className="text-[11px] font-semibold text-foreground">+ {t("settingsPage.account.pricing.pro.name")}+ </p>+ <div className="flex items-baseline gap-0.5 mt-0.5">+ <span className="text-sm font-bold text-foreground">+ {billingPeriod === "monthly"+ ? t("settingsPage.account.pricing.pro.monthlyPrice")+ : t("settingsPage.account.pricing.pro.annualPrice")}+ </span>+ <span className="text-[9px] text-muted-foreground">+ {billingPeriod === "monthly"+ ? t("settingsPage.account.pricing.pro.monthlyPeriod")+ : t("settingsPage.account.pricing.pro.annualPeriod")}+ </span>+ {billingPeriod === "annual" && (+ <span className="text-[9px] font-semibold text-primary ml-1">+ {t("settingsPage.account.pricing.annualBadge")}+ </span>)}</div>- )}-- {updateStatus.updateDownloaded && (- <Button- onClick={() => {- showConfirmDialog({- title: t("settingsPage.general.updates.dialogs.installUpdate.title"),- description: t(- "settingsPage.general.updates.dialogs.installUpdate.description",- { version: updateInfo?.version || "" }- ),- confirmText: t(- "settingsPage.general.updates.dialogs.installUpdate.confirmText"- ),- onConfirm: async () => {- try {- await installUpdateAction();- } catch (error: any) {- showAlertDialog({- title: t(- "settingsPage.general.updates.dialogs.installFailed.title"- ),+ <ul className="space-y-0.5 mt-2 flex-1">+ {(+ t("settingsPage.account.pricing.pro.features", {+ returnObjects: true,+ }) as string[]+ ).map((feature, i) => (+ <li+ key={i}+ className="flex items-start gap-1 text-[10px] text-muted-foreground leading-tight"+ >+ <Check size={9} className="mt-[2px] text-primary shrink-0" />+ {feature}+ </li>+ ))}+ </ul>+ {usage?.isSubscribed && !usage?.isTrial ? (+ billingPeriod === "annual" ? (+ <Button+ onClick={async () => {+ const result = await usage.openBillingPortal();+ if (!result.success) {+ toast({+ title: t("settingsPage.account.billing.couldNotOpenTitle"),description: t(- "settingsPage.general.updates.dialogs.installFailed.description"+ "settingsPage.account.billing.couldNotOpenDescription"),+ variant: "destructive",});}- },- });- }}- disabled={installInitiated}- className="w-full"+ }}+ variant="outline"+ size="sm"+ className="mt-2 w-full h-6 text-[10px]"+ disabled={usage?.checkoutLoading}+ >+ {t("settingsPage.account.pricing.pro.switchToAnnual")}+ </Button>+ ) : (+ <div className="mt-2 text-center">+ <span className="text-[9px] font-medium text-primary">+ {t("settingsPage.account.pricing.currentPlan")}+ </span>+ </div>+ )+ ) : usage?.isTrial ? (+ <div className="mt-2 text-center">+ <span className="text-[9px] font-medium text-primary">+ {t("settingsPage.account.pricing.currentPlan")}+ </span>+ </div>+ ) : (+ <Button+ onClick={() =>+ window.electronAPI?.openExternal?.(+ `https://openwhispr.com/get-started?plan=${billingPeriod}`+ )+ }+ size="sm"+ className="mt-2 w-full h-6 text-[10px]"+ >+ {t("settingsPage.account.pricing.pro.cta")}+ </Button>+ )}+ </div>++ {/* Enterprise */}+ <div className="rounded-md border border-border/50 dark:border-border-subtle/60 bg-card/30 dark:bg-surface-2/30 p-2.5 flex flex-col">+ <p className="text-[11px] font-semibold text-foreground">+ {t("settingsPage.account.pricing.enterprise.name")}+ </p>+ <div className="flex items-baseline gap-0.5 mt-0.5">+ <span className="text-sm font-bold text-foreground">+ {t("settingsPage.account.pricing.enterprise.price")}+ </span>+ </div>+ <ul className="space-y-0.5 mt-2 flex-1">+ {(+ t("settingsPage.account.pricing.enterprise.features", {+ returnObjects: true,+ }) as string[]+ ).map((feature, i) => (+ <li+ key={i}+ className="flex items-start gap-1 text-[10px] text-muted-foreground leading-tight"+ >+ <Check+ size={9}+ className="mt-[2px] text-purple-500 dark:text-purple-400 shrink-0"+ />+ {feature}+ </li>+ ))}+ </ul>+ <Button+ variant="outline"size="sm"+ className="mt-2 w-full h-6 text-[10px]"+ onClick={() =>+ window.electronAPI?.openExternal?.("mailto:[email protected]")+ }>- <RefreshCw- size={14}- className={`mr-2 ${installInitiated ? "animate-spin" : ""}`}- />- {installInitiated- ? t("settingsPage.general.updates.restarting")- : t("settingsPage.general.updates.installAndRestart")}+ <Mail size={10} />+ {t("settingsPage.account.pricing.enterprise.cta")}</Button>- )}+ </div></div>+ </div>- {updateInfo?.releaseNotes && (- <div className="mt-4 pt-4 border-t border-border/30">- <p className="text-[11px] font-medium text-muted-foreground uppercase tracking-wider mb-2">- {t("settingsPage.general.updates.whatsNew", {- version: updateInfo.version,- })}- </p>- <div className="text-[12px] text-muted-foreground">- <MarkdownRenderer content={updateInfo.releaseNotes} />- </div>+ {isSignedIn ? (+ <>+ <SectionHeader title={t("settingsPage.account.planTitle")} />+ {!usage || !usage.hasLoaded ? (+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center justify-between">+ <Skeleton className="h-4 w-24" />+ <Skeleton className="h-5 w-16 rounded-full" />+ </div>+ </SettingsPanelRow>+ <SettingsPanelRow>+ <div className="space-y-2">+ <Skeleton className="h-3 w-48" />+ <Skeleton className="h-8 w-full rounded" />+ </div>+ </SettingsPanelRow>+ </SettingsPanel>+ ) : (+ <SettingsPanel>+ {usage.isPastDue && (+ <SettingsPanelRow>+ <Alert+ variant="warning"+ className="dark:bg-amber-950/50 dark:border-amber-800 dark:text-amber-200 dark:[&>svg]:text-amber-400"+ >+ <AlertTriangle className="h-4 w-4" />+ <AlertTitle>{t("settingsPage.account.pastDue.title")}</AlertTitle>+ <AlertDescription>+ {t("settingsPage.account.pastDue.description")}+ </AlertDescription>+ </Alert>+ </SettingsPanelRow>+ )}++ <SettingsPanelRow>+ <SettingsRow+ label={+ usage.isTrial+ ? t("settingsPage.account.planLabels.trial")+ : usage.isPastDue+ ? t("settingsPage.account.planLabels.free")+ : usage.isSubscribed+ ? t("settingsPage.account.planLabels.pro")+ : t("settingsPage.account.planLabels.free")+ }+ description={+ usage.isTrial+ ? t("settingsPage.account.planDescriptions.trial", {+ days: usage.trialDaysLeft,+ })+ : usage.isPastDue+ ? t("settingsPage.account.planDescriptions.pastDue", {+ used: usage.wordsUsed.toLocaleString(i18n.language),+ limit: usage.limit.toLocaleString(i18n.language),+ })+ : usage.isSubscribed+ ? usage.currentPeriodEnd+ ? t("settingsPage.account.planDescriptions.nextBilling", {+ date: new Date(usage.currentPeriodEnd).toLocaleDateString(+ i18n.language,+ { month: "short", day: "numeric", year: "numeric" }+ ),+ })+ : t("settingsPage.account.planDescriptions.unlimited")+ : t("settingsPage.account.planDescriptions.freeUsage", {+ used: usage.wordsUsed.toLocaleString(i18n.language),+ limit: usage.limit.toLocaleString(i18n.language),+ })+ }+ >+ {usage.isTrial ? (+ <Badge variant="info">{t("settingsPage.account.badges.trial")}</Badge>+ ) : usage.isPastDue ? (+ <Badge variant="destructive">+ {t("settingsPage.account.badges.pastDue")}+ </Badge>+ ) : usage.isSubscribed ? (+ <Badge variant="success">+ {t("settingsPage.account.badges.pro")}+ </Badge>+ ) : usage.isOverLimit ? (+ <Badge variant="warning">+ {t("settingsPage.account.badges.limitReached")}+ </Badge>+ ) : (+ <Badge variant="outline">+ {t("settingsPage.account.badges.free")}+ </Badge>+ )}+ </SettingsRow>+ </SettingsPanelRow>++ {!usage.isSubscribed && !usage.isTrial && (+ <SettingsPanelRow>+ <div className="space-y-1.5">+ <Progress+ value={+ usage.limit > 0+ ? Math.min(100, (usage.wordsUsed / usage.limit) * 100)+ : 0+ }+ className={cn(+ "h-1.5",+ usage.isOverLimit+ ? "[&>div]:bg-destructive"+ : usage.isApproachingLimit+ ? "[&>div]:bg-warning"+ : "[&>div]:bg-primary"+ )}+ />+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span className="tabular-nums">+ {usage.wordsUsed.toLocaleString(i18n.language)} /{" "}+ {usage.limit.toLocaleString(i18n.language)}+ </span>+ {usage.isApproachingLimit && (+ <span className="text-warning">+ {t("settingsPage.account.wordsRemaining", {+ remaining: usage.wordsRemaining.toLocaleString(i18n.language),+ })}+ </span>+ )}+ {!usage.isApproachingLimit && !usage.isOverLimit && (+ <span>{t("settingsPage.account.rollingWeeklyLimit")}</span>+ )}+ </div>+ </div>+ </SettingsPanelRow>+ )}++ <SettingsPanelRow>+ {usage.isPastDue ? (+ <Button+ onClick={async () => {+ setIsOpeningBilling(true);+ try {+ const result = await usage.openBillingPortal();+ if (!result.success) {+ toast({+ title: t("settingsPage.account.billing.couldNotOpenTitle"),+ description: t(+ "settingsPage.account.billing.couldNotOpenDescription"+ ),+ variant: "destructive",+ });+ }+ } finally {+ setIsOpeningBilling(false);+ }+ }}+ disabled={isOpeningBilling}+ size="sm"+ className="w-full"+ >+ {isOpeningBilling ? (+ <>+ <Loader2 size={14} className="animate-spin" />+ {t("settingsPage.account.billing.opening")}+ </>+ ) : (+ t("settingsPage.account.billing.updatePaymentMethod")+ )}+ </Button>+ ) : usage.isSubscribed && !usage.isTrial ? (+ <Button+ onClick={async () => {+ const result = await usage.openBillingPortal();+ if (!result.success) {+ toast({+ title: t("settingsPage.account.billing.couldNotOpenTitle"),+ description: t(+ "settingsPage.account.billing.couldNotOpenDescription"+ ),+ variant: "destructive",+ });+ }+ }}+ variant="outline"+ size="sm"+ className="w-full"+ disabled={usage.checkoutLoading}+ >+ {usage.checkoutLoading+ ? t("settingsPage.account.billing.opening")+ : t("settingsPage.account.billing.manageBilling")}+ </Button>+ ) : (+ <Button+ onClick={async () => {+ const result = await usage.openCheckout(billingPeriod);+ if (!result.success) {+ toast({+ title: t("settingsPage.account.checkout.couldNotOpenTitle"),+ description: t(+ "settingsPage.account.checkout.couldNotOpenDescription"+ ),+ variant: "destructive",+ });+ }+ }}+ size="sm"+ className="w-full"+ disabled={usage.checkoutLoading}+ >+ {usage.checkoutLoading+ ? t("settingsPage.account.checkout.opening")+ : t("settingsPage.account.checkout.upgradeToPro")}+ </Button>+ )}+ </SettingsPanelRow>+ </SettingsPanel>+ )}+ </>+ ) : null}+ </>+ ) : (+ <>+ <SectionHeader title={t("settingsPage.account.pricing.title")} />+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center justify-between">+ <Skeleton className="h-4 w-32" />+ <Skeleton className="h-5 w-16 rounded-full" /></div>- )}- </SettingsPanelRow>- </SettingsPanel>- </div>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ )}+ </div>+ );+ case "general":+ return (+ <div className="space-y-6">{/* Appearance */}<div><SectionHeader@@ -1528,8 +1592,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagekey={option.value}onClick={() => setTheme(option.value)}className={`- flex items-center gap-1 px-2.5 py-1 rounded-[5px] text-[11px] font-medium- transition-all duration-100+ flex items-center gap-1 px-2.5 py-1 rounded-[5px] text-xs font-medium+ transition-colors duration-100${isSelected? "bg-background dark:bg-surface-raised text-foreground shadow-sm"@@ -1617,35 +1681,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</SettingsPanel></div>- {/* Dictation Hotkey */}- <div>- <SectionHeader- title={t("settingsPage.general.hotkey.title")}- description={t("settingsPage.general.hotkey.description")}- />- <SettingsPanel>- <SettingsPanelRow>- <HotkeyInput- value={dictationKey}- onChange={async (newHotkey) => {- await registerHotkey(newHotkey);- }}- disabled={isHotkeyRegistering}- validate={validateHotkeyForInput}- />- </SettingsPanelRow>-- {!isUsingGnomeHotkeys && (- <SettingsPanelRow>- <p className="text-[11px] font-medium text-muted-foreground/80 mb-2">- {t("settingsPage.general.hotkey.activationMode")}- </p>- <ActivationModeSelector value={activationMode} onChange={setActivationMode} />- </SettingsPanelRow>- )}- </SettingsPanel>- </div>-{/* Startup */}{platform !== "linux" && (<div>@@ -1687,6 +1722,51 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div>);+ case "hotkeys":+ return (+ <div className="space-y-6">+ {/* Dictation Hotkey */}+ <div>+ <SectionHeader+ title={t("settingsPage.general.hotkey.title")}+ description={t("settingsPage.general.hotkey.description")}+ />+ <SettingsPanel>+ <SettingsPanelRow>+ <HotkeyInput+ value={dictationKey}+ onChange={async (newHotkey) => {+ await registerHotkey(newHotkey);+ }}+ disabled={isHotkeyRegistering}+ validate={validateHotkeyForInput}+ />+ {dictationKey && dictationKey !== getDefaultHotkey() && (+ <button+ onClick={() => registerHotkey(getDefaultHotkey())}+ disabled={isHotkeyRegistering}+ className="mt-2 text-xs text-muted-foreground/70 hover:text-foreground transition-colors disabled:opacity-50"+ >+ {t("settingsPage.general.hotkey.resetToDefault", {+ hotkey: formatHotkeyLabel(getDefaultHotkey()),+ })}+ </button>+ )}+ </SettingsPanelRow>++ {!isUsingGnomeHotkeys && (+ <SettingsPanelRow>+ <p className="text-xs font-medium text-muted-foreground/80 mb-2">+ {t("settingsPage.general.hotkey.activationMode")}+ </p>+ <ActivationModeSelector value={activationMode} onChange={setActivationMode} />+ </SettingsPanelRow>+ )}+ </SettingsPanel>+ </div>+ </div>+ );+case "transcription":return (<TranscriptionSection@@ -1720,436 +1800,479 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage/>);- case "dictionary":+ case "intelligence":return (- <div className="space-y-5">- <SectionHeader- title={t("settingsPage.dictionary.title")}- description={t("settingsPage.dictionary.description")}+ <div className="space-y-6">+ {/* Text Cleanup (AI Models) */}+ <AiModelsSection+ isSignedIn={isSignedIn ?? false}+ cloudReasoningMode={cloudReasoningMode}+ setCloudReasoningMode={setCloudReasoningMode}+ useReasoningModel={useReasoningModel}+ setUseReasoningModel={(value) => {+ setUseReasoningModel(value);+ updateReasoningSettings({ useReasoningModel: value });+ }}+ reasoningModel={reasoningModel}+ setReasoningModel={setReasoningModel}+ reasoningProvider={reasoningProvider}+ setReasoningProvider={setReasoningProvider}+ cloudReasoningBaseUrl={cloudReasoningBaseUrl}+ setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ anthropicApiKey={anthropicApiKey}+ setAnthropicApiKey={setAnthropicApiKey}+ geminiApiKey={geminiApiKey}+ setGeminiApiKey={setGeminiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ customReasoningApiKey={customReasoningApiKey}+ setCustomReasoningApiKey={setCustomReasoningApiKey}+ showAlertDialog={showAlertDialog}+ toast={toast}/>- {/* Add Words */}- <SettingsPanel>- <SettingsPanelRow>- <div className="space-y-2">- <p className="text-[12px] font-medium text-foreground">- {t("settingsPage.dictionary.addWordOrPhrase")}- </p>- <div className="flex gap-2">- <Input- placeholder={t("settingsPage.dictionary.placeholder")}- value={newDictionaryWord}- onChange={(e) => setNewDictionaryWord(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- handleAddDictionaryWord();- }- }}- className="flex-1 h-8 text-[12px]"- />- <Button- onClick={handleAddDictionaryWord}- disabled={!newDictionaryWord.trim()}- size="sm"- className="h-8"- >- {t("settingsPage.dictionary.add")}- </Button>- </div>- <p className="text-[10px] text-muted-foreground/50">- {t("settingsPage.dictionary.pressEnterToAdd")}+ {/* Agent Config */}+ <div className="border-t border-border/40 pt-6">+ <SectionHeader+ title={t("settingsPage.agentConfig.title")}+ description={t("settingsPage.agentConfig.description")}+ />++ <div className="space-y-5">+ <div>+ <p className="text-xs font-medium text-foreground mb-3">+ {t("settingsPage.agentConfig.agentName")}</p>+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="space-y-3">+ <div className="flex gap-2">+ <Input+ placeholder={t("settingsPage.agentConfig.placeholder")}+ value={agentNameInput}+ onChange={(e) => setAgentNameInput(e.target.value)}+ className="flex-1 text-center text-base font-mono"+ />+ <Button+ onClick={() => {+ const trimmed = agentNameInput.trim();+ const oldName = agentName;+ setAgentName(trimmed);+ setAgentNameInput(trimmed);+ let dict = customDictionary.filter((w) => w !== oldName);+ if (trimmed && !dict.includes(trimmed)) dict = [trimmed, ...dict];+ setCustomDictionary(dict);+ showAlertDialog({+ title: t("settingsPage.agentConfig.dialogs.updatedTitle"),+ description: t(+ "settingsPage.agentConfig.dialogs.updatedDescription",+ {+ name: trimmed,+ }+ ),+ });+ }}+ disabled={!agentNameInput.trim()}+ size="sm"+ >+ {t("settingsPage.agentConfig.save")}+ </Button>+ </div>+ <p className="text-xs text-muted-foreground/60">+ {t("settingsPage.agentConfig.helper")}+ </p>+ </div>+ </SettingsPanelRow>+ </SettingsPanel></div>- </SettingsPanelRow>- </SettingsPanel>- {/* Word List */}- <div>- <div className="flex items-center justify-between mb-2">- <p className="text-[12px] font-medium text-foreground">- {t("settingsPage.dictionary.yourWords")}- {customDictionary.length > 0 && (- <span className="ml-1.5 text-muted-foreground/50 font-normal text-[11px]">- {customDictionary.length}- </span>- )}- </p>- {customDictionary.length > 0 && (- <button- onClick={() => {- showConfirmDialog({- title: t("settingsPage.dictionary.clearDictionaryTitle"),- description: t("settingsPage.dictionary.clearDictionaryDescription"),- confirmText: t("settingsPage.dictionary.clearAll"),- variant: "destructive",- onConfirm: () =>- setCustomDictionary(customDictionary.filter((w) => w === agentName)),- });- }}- className="text-[10px] text-muted-foreground/40 hover:text-destructive transition-colors"- >- {t("settingsPage.dictionary.clearAll")}- </button>- )}- </div>+ <div>+ <SectionHeader title={t("settingsPage.agentConfig.howItWorksTitle")} />+ <SettingsPanel>+ <SettingsPanelRow>+ <p className="text-xs text-muted-foreground leading-relaxed">+ {t("settingsPage.agentConfig.howItWorksDescription", { agentName })}+ </p>+ </SettingsPanelRow>+ </SettingsPanel>+ </div>- {customDictionary.length > 0 ? (- <SettingsPanel>- <SettingsPanelRow>- <div className="flex flex-wrap gap-1">- {customDictionary.map((word) => {- const isAgentName = word === agentName;- return (- <span- key={word}- className={`group inline-flex items-center gap-0.5 py-0.5 rounded-[5px] text-[11px] border transition-all ${- isAgentName- ? "pl-2 pr-2 bg-primary/10 dark:bg-primary/15 text-primary border-primary/20 dark:border-primary/30"- : "pl-2 pr-1 bg-primary/5 dark:bg-primary/10 text-foreground border-border/30 dark:border-border-subtle hover:border-destructive/40 hover:bg-destructive/5"- }`}- title={- isAgentName- ? t("settingsPage.dictionary.agentNameAutoManaged")- : undefined- }- >- {word}- {!isAgentName && (- <button- onClick={() => handleRemoveDictionaryWord(word)}- className="ml-0.5 p-0.5 rounded-sm text-muted-foreground/40 hover:text-destructive transition-colors"- title={t("settingsPage.dictionary.removeWord")}- >- <svg- width="9"- height="9"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2.5"- strokeLinecap="round"- >- <path d="M18 6L6 18M6 6l12 12" />- </svg>- </button>- )}- </span>- );- })}- </div>- </SettingsPanelRow>- </SettingsPanel>- ) : (- <div className="rounded-lg border border-dashed border-border/40 dark:border-border-subtle py-6 flex flex-col items-center justify-center text-center">- <p className="text-[11px] text-muted-foreground/50">- {t("settingsPage.dictionary.noWords")}- </p>- <p className="text-[10px] text-muted-foreground/40 mt-0.5">- {t("settingsPage.dictionary.wordsAppearHere")}- </p>+ <div>+ <SectionHeader title={t("settingsPage.agentConfig.examplesTitle")} />+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="space-y-2.5">+ {[+ {+ input: `Hey ${agentName}, write a formal email about the budget`,+ mode: t("settingsPage.agentConfig.instructionMode"),+ },+ {+ input: `Hey ${agentName}, make this more professional`,+ mode: t("settingsPage.agentConfig.instructionMode"),+ },+ {+ input: `Hey ${agentName}, convert this to bullet points`,+ mode: t("settingsPage.agentConfig.instructionMode"),+ },+ {+ input: t("settingsPage.agentConfig.cleanupExample"),+ mode: t("settingsPage.agentConfig.cleanupMode"),+ },+ ].map((example, i) => (+ <div key={i} className="flex items-start gap-3">+ <span+ className={`shrink-0 mt-0.5 text-xs font-medium uppercase tracking-wider px-1.5 py-px rounded ${+ example.mode === t("settingsPage.agentConfig.instructionMode")+ ? "bg-primary/10 text-primary dark:bg-primary/15"+ : "bg-muted text-muted-foreground"+ }`}+ >+ {example.mode}+ </span>+ <p className="text-xs text-muted-foreground leading-relaxed">+ "{example.input}"+ </p>+ </div>+ ))}+ </div>+ </SettingsPanelRow>+ </SettingsPanel></div>- )}+ </div></div>- {/* How it works */}- <div>- <SectionHeader title={t("settingsPage.dictionary.howItWorksTitle")} />- <SettingsPanel>- <SettingsPanelRow>- <p className="text-[12px] text-muted-foreground leading-relaxed">- {t("settingsPage.dictionary.howItWorksDescription")}- </p>- </SettingsPanelRow>- <SettingsPanelRow>- <p className="text-[12px] text-muted-foreground leading-relaxed">- <span className="font-medium text-foreground">- {t("settingsPage.dictionary.tipLabel")}- </span>{" "}- {t("settingsPage.dictionary.tipDescription")}- </p>- </SettingsPanelRow>- </SettingsPanel>+ {/* System Prompt */}+ <div className="border-t border-border/40 pt-6">+ <SectionHeader+ title={t("settingsPage.prompts.title")}+ description={t("settingsPage.prompts.description")}+ />+ <PromptStudio /></div></div>);- case "aiModels":+ case "privacyData":return (- <AiModelsSection- isSignedIn={isSignedIn ?? false}- cloudReasoningMode={cloudReasoningMode}- setCloudReasoningMode={setCloudReasoningMode}- useReasoningModel={useReasoningModel}- setUseReasoningModel={(value) => {- setUseReasoningModel(value);- updateReasoningSettings({ useReasoningModel: value });- }}- reasoningModel={reasoningModel}- setReasoningModel={setReasoningModel}- reasoningProvider={reasoningProvider}- setReasoningProvider={setReasoningProvider}- cloudReasoningBaseUrl={cloudReasoningBaseUrl}- setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}- openaiApiKey={openaiApiKey}- setOpenaiApiKey={setOpenaiApiKey}- anthropicApiKey={anthropicApiKey}- setAnthropicApiKey={setAnthropicApiKey}- geminiApiKey={geminiApiKey}- setGeminiApiKey={setGeminiApiKey}- groqApiKey={groqApiKey}- setGroqApiKey={setGroqApiKey}- customReasoningApiKey={customReasoningApiKey}- setCustomReasoningApiKey={setCustomReasoningApiKey}- showAlertDialog={showAlertDialog}- toast={toast}- />- );+ <div className="space-y-6">+ {/* Privacy */}+ <div>+ <SectionHeader+ title={t("settingsPage.privacy.title")}+ description={t("settingsPage.privacy.description")}+ />- case "agentConfig":- return (- <div className="space-y-5">- <SectionHeader- title={t("settingsPage.agentConfig.title")}- description={t("settingsPage.agentConfig.description")}- />+ {isSignedIn && (+ <SettingsPanel className="mb-4">+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.privacy.cloudBackup")}+ description={t("settingsPage.privacy.cloudBackupDescription")}+ >+ <Toggle checked={cloudBackupEnabled} onChange={setCloudBackupEnabled} />+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ )}- {/* Agent Name */}- <div>- <p className="text-[13px] font-medium text-foreground mb-3">- {t("settingsPage.agentConfig.agentName")}- </p><SettingsPanel><SettingsPanelRow>- <div className="space-y-3">- <div className="flex gap-2">- <Input- placeholder={t("settingsPage.agentConfig.placeholder")}- value={agentNameInput}- onChange={(e) => setAgentNameInput(e.target.value)}- className="flex-1 text-center text-base font-mono"- />- <Button- onClick={() => {- const trimmed = agentNameInput.trim();- setAgentName(trimmed);- setAgentNameInput(trimmed);- showAlertDialog({- title: t("settingsPage.agentConfig.dialogs.updatedTitle"),- description: t("settingsPage.agentConfig.dialogs.updatedDescription", {- name: trimmed,- }),- });- }}- disabled={!agentNameInput.trim()}- size="sm"- >- {t("settingsPage.agentConfig.save")}- </Button>- </div>- <p className="text-[11px] text-muted-foreground/60">- {t("settingsPage.agentConfig.helper")}- </p>- </div>+ <SettingsRow+ label={t("settingsPage.privacy.usageAnalytics")}+ description={t("settingsPage.privacy.usageAnalyticsDescription")}+ >+ <Toggle checked={telemetryEnabled} onChange={setTelemetryEnabled} />+ </SettingsRow></SettingsPanelRow></SettingsPanel></div>- {/* How it works */}- <div>- <SectionHeader title={t("settingsPage.agentConfig.howItWorksTitle")} />- <SettingsPanel>- <SettingsPanelRow>- <p className="text-[12px] text-muted-foreground leading-relaxed">- {t("settingsPage.agentConfig.howItWorksDescription", { agentName })}- </p>- </SettingsPanelRow>- </SettingsPanel>- </div>+ {/* Permissions */}+ <div className="border-t border-border/40 pt-6">+ <SectionHeader+ title={t("settingsPage.permissions.title")}+ description={t("settingsPage.permissions.description")}+ />- {/* Examples */}- <div>- <SectionHeader title={t("settingsPage.agentConfig.examplesTitle")} />- <SettingsPanel>- <SettingsPanelRow>- <div className="space-y-2.5">- {[- {- input: `Hey ${agentName}, write a formal email about the budget`,- mode: t("settingsPage.agentConfig.instructionMode"),- },- {- input: `Hey ${agentName}, make this more professional`,- mode: t("settingsPage.agentConfig.instructionMode"),- },- {- input: `Hey ${agentName}, convert this to bullet points`,- mode: t("settingsPage.agentConfig.instructionMode"),- },- {- input: t("settingsPage.agentConfig.cleanupExample"),- mode: t("settingsPage.agentConfig.cleanupMode"),- },- ].map((example, i) => (- <div key={i} className="flex items-start gap-3">- <span- className={`shrink-0 mt-0.5 text-[10px] font-medium uppercase tracking-wider px-1.5 py-px rounded ${- example.mode === t("settingsPage.agentConfig.instructionMode")- ? "bg-primary/10 text-primary dark:bg-primary/15"- : "bg-muted text-muted-foreground"- }`}- >- {example.mode}- </span>- <p className="text-[12px] text-muted-foreground leading-relaxed">- "{example.input}"- </p>- </div>- ))}- </div>- </SettingsPanelRow>- </SettingsPanel>- </div>- </div>- );+ <div className="space-y-3">+ <PermissionCard+ icon={Mic}+ title={t("settingsPage.permissions.microphoneTitle")}+ description={t("settingsPage.permissions.microphoneDescription")}+ granted={permissionsHook.micPermissionGranted}+ onRequest={permissionsHook.requestMicPermission}+ buttonText={t("settingsPage.permissions.test")}+ onOpenSettings={permissionsHook.openMicPrivacySettings}+ />- case "prompts":- return (- <div className="space-y-5">- <SectionHeader- title={t("settingsPage.prompts.title")}- description={t("settingsPage.prompts.description")}- />+ {platform === "darwin" && (+ <PermissionCard+ icon={Shield}+ title={t("settingsPage.permissions.accessibilityTitle")}+ description={t("settingsPage.permissions.accessibilityDescription")}+ granted={permissionsHook.accessibilityPermissionGranted}+ onRequest={permissionsHook.testAccessibilityPermission}+ buttonText={t("settingsPage.permissions.testAndGrant")}+ onOpenSettings={permissionsHook.openAccessibilitySettings}+ />+ )}+ </div>- <PromptStudio />+ {!permissionsHook.micPermissionGranted && permissionsHook.micPermissionError && (+ <MicPermissionWarning+ error={permissionsHook.micPermissionError}+ onOpenSoundSettings={permissionsHook.openSoundInputSettings}+ onOpenPrivacySettings={permissionsHook.openMicPrivacySettings}+ />+ )}++ {platform === "linux" &&+ permissionsHook.pasteToolsInfo &&+ !permissionsHook.pasteToolsInfo.available && (+ <PasteToolsInfo+ pasteToolsInfo={permissionsHook.pasteToolsInfo}+ isChecking={permissionsHook.isCheckingPasteTools}+ onCheck={permissionsHook.checkPasteToolsAvailability}+ />+ )}++ {platform === "darwin" && (+ <div className="mt-5">+ <p className="text-xs font-medium text-foreground mb-3">+ {t("settingsPage.permissions.troubleshootingTitle")}+ </p>+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.permissions.resetAccessibility.label")}+ description={t(+ "settingsPage.permissions.resetAccessibility.rowDescription"+ )}+ >+ <Button+ onClick={resetAccessibilityPermissions}+ variant="ghost"+ size="sm"+ className="text-foreground/70 hover:text-foreground"+ >+ {t("settingsPage.permissions.troubleshoot")}+ </Button>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </div>+ )}+ </div></div>);- case "privacy":+ case "system":return (<div className="space-y-6">+ {/* Software Updates */}<div>- <h3 className="text-lg font-semibold text-foreground mb-2">- {t("settingsPage.privacy.title")}- </h3>- <p className="text-sm text-muted-foreground mb-6">- {t("settingsPage.privacy.description")}- </p>- </div>-- {isSignedIn && (+ <SectionHeader title={t("settingsPage.general.updates.title")} /><SettingsPanel><SettingsPanelRow><SettingsRow- label={t("settingsPage.privacy.cloudBackup")}- description={t("settingsPage.privacy.cloudBackupDescription")}+ label={t("settingsPage.general.updates.currentVersion")}+ description={+ updateStatus.isDevelopment+ ? t("settingsPage.general.updates.devMode")+ : isUpdateAvailable+ ? t("settingsPage.general.updates.newVersionAvailable")+ : t("settingsPage.general.updates.latestVersion")+ }>- <Toggle checked={cloudBackupEnabled} onChange={setCloudBackupEnabled} />+ <div className="flex items-center gap-2.5">+ <span className="text-xs tabular-nums text-muted-foreground font-mono">+ {currentVersion || t("settingsPage.general.updates.versionPlaceholder")}+ </span>+ {updateStatus.isDevelopment ? (+ <Badge variant="warning">+ {t("settingsPage.general.updates.badges.dev")}+ </Badge>+ ) : isUpdateAvailable ? (+ <Badge variant="success">+ {t("settingsPage.general.updates.badges.update")}+ </Badge>+ ) : (+ <Badge variant="outline">+ {t("settingsPage.general.updates.badges.latest")}+ </Badge>+ )}+ </div></SettingsRow></SettingsPanelRow>- </SettingsPanel>- )}- <SettingsPanel>- <SettingsPanelRow>- <SettingsRow- label={t("settingsPage.privacy.usageAnalytics")}- description={t("settingsPage.privacy.usageAnalyticsDescription")}- >- <Toggle checked={telemetryEnabled} onChange={setTelemetryEnabled} />- </SettingsRow>- </SettingsPanelRow>- </SettingsPanel>- </div>- );-- case "permissions":- return (- <div className="space-y-5">- <SectionHeader- title={t("settingsPage.permissions.title")}- description={t("settingsPage.permissions.description")}- />-- {/* Permission Cards - matching onboarding style */}- <div className="space-y-3">- <PermissionCard- icon={Mic}- title={t("settingsPage.permissions.microphoneTitle")}- description={t("settingsPage.permissions.microphoneDescription")}- granted={permissionsHook.micPermissionGranted}- onRequest={permissionsHook.requestMicPermission}- buttonText={t("settingsPage.permissions.test")}- onOpenSettings={permissionsHook.openMicPrivacySettings}- />-- {platform === "darwin" && (- <PermissionCard- icon={Shield}- title={t("settingsPage.permissions.accessibilityTitle")}- description={t("settingsPage.permissions.accessibilityDescription")}- granted={permissionsHook.accessibilityPermissionGranted}- onRequest={permissionsHook.testAccessibilityPermission}- buttonText={t("settingsPage.permissions.testAndGrant")}- onOpenSettings={permissionsHook.openAccessibilitySettings}- />- )}- </div>+ <SettingsPanelRow>+ <div className="space-y-2.5">+ <Button+ onClick={async () => {+ try {+ const result = await checkForUpdates();+ if (result?.updateAvailable) {+ showAlertDialog({+ title: t(+ "settingsPage.general.updates.dialogs.updateAvailable.title"+ ),+ description: t(+ "settingsPage.general.updates.dialogs.updateAvailable.description",+ {+ version:+ result.version || t("settingsPage.general.updates.newVersion"),+ }+ ),+ });+ } else {+ showAlertDialog({+ title: t("settingsPage.general.updates.dialogs.noUpdates.title"),+ description:+ result?.message ||+ t("settingsPage.general.updates.dialogs.noUpdates.description"),+ });+ }+ } catch (error: any) {+ showAlertDialog({+ title: t("settingsPage.general.updates.dialogs.checkFailed.title"),+ description: t(+ "settingsPage.general.updates.dialogs.checkFailed.description"+ ),+ });+ }+ }}+ disabled={checkingForUpdates || updateStatus.isDevelopment}+ variant="outline"+ className="w-full"+ size="sm"+ >+ <RefreshCw+ size={13}+ className={`mr-1.5 ${checkingForUpdates ? "animate-spin" : ""}`}+ />+ {checkingForUpdates+ ? t("settingsPage.general.updates.checking")+ : t("settingsPage.general.updates.checkForUpdates")}+ </Button>- {/* Error state for microphone */}- {!permissionsHook.micPermissionGranted && permissionsHook.micPermissionError && (- <MicPermissionWarning- error={permissionsHook.micPermissionError}- onOpenSoundSettings={permissionsHook.openSoundInputSettings}- onOpenPrivacySettings={permissionsHook.openMicPrivacySettings}- />- )}+ {isUpdateAvailable && !updateStatus.updateDownloaded && (+ <div className="space-y-2">+ <Button+ onClick={async () => {+ try {+ await downloadUpdate();+ } catch (error: any) {+ showAlertDialog({+ title: t(+ "settingsPage.general.updates.dialogs.downloadFailed.title"+ ),+ description: t(+ "settingsPage.general.updates.dialogs.downloadFailed.description"+ ),+ });+ }+ }}+ disabled={downloadingUpdate}+ variant="success"+ className="w-full"+ size="sm"+ >+ <Download+ size={13}+ className={`mr-1.5 ${downloadingUpdate ? "animate-pulse" : ""}`}+ />+ {downloadingUpdate+ ? t("settingsPage.general.updates.downloading", {+ progress: Math.round(updateDownloadProgress),+ })+ : t("settingsPage.general.updates.downloadUpdate", {+ version: updateInfo?.version || "",+ })}+ </Button>- {/* Linux paste tools info */}- {platform === "linux" &&- permissionsHook.pasteToolsInfo &&- !permissionsHook.pasteToolsInfo.available && (- <PasteToolsInfo- pasteToolsInfo={permissionsHook.pasteToolsInfo}- isChecking={permissionsHook.isCheckingPasteTools}- onCheck={permissionsHook.checkPasteToolsAvailability}- />- )}+ {downloadingUpdate && (+ <div className="h-1 w-full overflow-hidden rounded-full bg-muted/50">+ <div+ className="h-full bg-success transition-[width] duration-200 rounded-full"+ style={{+ width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%`,+ }}+ />+ </div>+ )}+ </div>+ )}- {/* Troubleshooting section for macOS */}- {platform === "darwin" && (- <div>- <p className="text-[13px] font-medium text-foreground mb-3">- {t("settingsPage.permissions.troubleshootingTitle")}- </p>- <SettingsPanel>- <SettingsPanelRow>- <SettingsRow- label={t("settingsPage.permissions.resetAccessibility.label")}- description={t("settingsPage.permissions.resetAccessibility.rowDescription")}- >+ {updateStatus.updateDownloaded && (<Button- onClick={resetAccessibilityPermissions}- variant="ghost"+ onClick={() => {+ showConfirmDialog({+ title: t("settingsPage.general.updates.dialogs.installUpdate.title"),+ description: t(+ "settingsPage.general.updates.dialogs.installUpdate.description",+ { version: updateInfo?.version || "" }+ ),+ confirmText: t(+ "settingsPage.general.updates.dialogs.installUpdate.confirmText"+ ),+ onConfirm: async () => {+ try {+ await installUpdateAction();+ } catch (error: any) {+ showAlertDialog({+ title: t(+ "settingsPage.general.updates.dialogs.installFailed.title"+ ),+ description: t(+ "settingsPage.general.updates.dialogs.installFailed.description"+ ),+ });+ }+ },+ });+ }}+ disabled={installInitiated}+ className="w-full"size="sm"- className="text-foreground/70 hover:text-foreground">- {t("settingsPage.permissions.troubleshoot")}+ <RefreshCw+ size={14}+ className={`mr-2 ${installInitiated ? "animate-spin" : ""}`}+ />+ {installInitiated+ ? t("settingsPage.general.updates.restarting")+ : t("settingsPage.general.updates.installAndRestart")}</Button>- </SettingsRow>- </SettingsPanelRow>- </SettingsPanel>- </div>- )}- </div>- );+ )}+ </div>- case "developer":- return (- <div className="space-y-6">- <DeveloperSection />+ {updateInfo?.releaseNotes && (+ <div className="mt-4 pt-4 border-t border-border/30">+ <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">+ {t("settingsPage.general.updates.whatsNew", {+ version: updateInfo.version,+ })}+ </p>+ <div+ className="text-xs text-muted-foreground [&_ul]:list-disc [&_ul]:pl-4 [&_ul]:space-y-1 [&_ol]:list-decimal [&_ol]:pl-4 [&_ol]:space-y-1 [&_li]:pl-1 [&_p]:mb-2 [&_p:last-child]:mb-0 [&_a]:text-link [&_a]:underline"+ dangerouslySetInnerHTML={{ __html: updateInfo.releaseNotes }}+ />+ </div>+ )}+ </SettingsPanelRow>+ </SettingsPanel>+ </div>++ {/* Developer Tools */}+ <div className="border-t border-border/40 pt-6">+ <DeveloperSection />+ </div>- {/* Data Management — moved from General */}- <div className="border-t border-border/40 pt-8">+ {/* Data Management */}+ <div className="border-t border-border/40 pt-6"><SectionHeadertitle={t("settingsPage.developer.dataManagementTitle")}description={t("settingsPage.developer.dataManagementDescription")}diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex e7ce76d07..19f3292fd 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -23,8 +23,9 @@ import {type ModelPickerStyles,} from "../utils/modelPickerStyles";import { getProviderIcon, isMonochromeProvider } from "../utils/providerIcons";-import { API_ENDPOINTS } from "../config/constants";+import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";import { createExternalLinkHandler } from "../utils/externalLinks";+import logger from "../utils/logger";interface LocalModel {model: string;@@ -81,7 +82,7 @@ function LocalModelCard({return (<divonClick={handleClick}- className={`relative w-full text-left overflow-hidden rounded-md border transition-all duration-200 group ${+ className={`relative w-full text-left overflow-hidden rounded-md border transition-colors duration-200 group ${isSelected ? cardStyles.modelCard.selected : cardStyles.modelCard.default} ${isDownloaded && !isSelected ? "cursor-pointer" : ""}`}>@@ -110,14 +111,14 @@ function LocalModelCard({<span className="font-semibold text-sm text-foreground truncate tracking-tight">{name}</span>- <span className="text-[11px] text-muted-foreground/50 tabular-nums shrink-0">+ <span className="text-xs text-muted-foreground/50 tabular-nums shrink-0">{actualSizeMb ? `${actualSizeMb}MB` : size}</span>{recommended && (<span className={cardStyles.badges.recommended}>{t("common.recommended")}</span>)}{languageLabel && (- <span className="text-[11px] text-muted-foreground/50 font-medium shrink-0">+ <span className="text-xs text-muted-foreground/50 font-medium shrink-0">{languageLabel}</span>)}@@ -127,7 +128,7 @@ function LocalModelCard({{isDownloaded ? (<>{isSelected && (- <span className="text-[10px] font-medium text-primary px-2 py-0.5 bg-primary/10 rounded-sm">+ <span className="text-xs font-medium text-primary px-2 py-0.5 bg-primary/10 rounded-sm">{t("common.active")}</span>)}@@ -138,7 +139,7 @@ function LocalModelCard({}}size="sm"variant="ghost"- className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-all active:scale-95"+ className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-[color,opacity,transform] active:scale-95"><Trash2 size={12} /></Button>@@ -152,7 +153,7 @@ function LocalModelCard({disabled={isCancelling}size="sm"variant="outline"- className="h-6 px-2.5 text-[11px] text-destructive border-destructive/25 hover:bg-destructive/8"+ className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"><X size={11} className="mr-0.5" />{isCancelling ? "..." : t("common.cancel")}@@ -165,7 +166,7 @@ function LocalModelCard({}}size="sm"variant="default"- className="h-6 px-2.5 text-[11px]"+ className="h-6 px-2.5 text-xs"><Download size={11} className="mr-1" />{t("common.download")}@@ -336,7 +337,7 @@ export default function TranscriptionModelPicker({validateAndSelectModel(result.models);}} catch (error) {- console.error("[TranscriptionModelPicker] Failed to load models:", error);+ logger.error("Failed to load models", { error }, "models");setLocalModels([]);} finally {isLoadingRef.current = false;@@ -353,7 +354,7 @@ export default function TranscriptionModelPicker({setParakeetModels(result.models);}} catch (error) {- console.error("[TranscriptionModelPicker] Failed to load Parakeet models:", error);+ logger.error("Failed to load Parakeet models", { error }, "models");setParakeetModels([]);} finally {isLoadingParakeetRef.current = false;@@ -526,7 +527,6 @@ export default function TranscriptionModelPicker({const trimmed = (cloudTranscriptionBaseUrl || "").trim();if (!trimmed) return;- const { normalizeBaseUrl } = require("../config/constants");const normalized = normalizeBaseUrl(trimmed);if (normalized && normalized !== cloudTranscriptionBaseUrl) {@@ -772,7 +772,7 @@ export default function TranscriptionModelPicker({providers={cloudProviderTabs}selectedId={selectedCloudProvider}onSelect={handleCloudProviderChange}- colorScheme={colorScheme === "purple" ? "purple" : "indigo"}+ colorScheme="purple"scrollable/></div>@@ -828,7 +828,7 @@ export default function TranscriptionModelPicker({openai: "https://platform.openai.com/api-keys",}[selectedCloudProvider] || "https://platform.openai.com/api-keys")}- className="text-[11px] text-white/70 hover:text-white transition-colors cursor-pointer"+ className="text-xs text-white/70 hover:text-white transition-colors cursor-pointer">{t("transcription.getKey")}</button>@@ -855,7 +855,7 @@ export default function TranscriptionModelPicker({models={cloudModelOptions}selectedModel={selectedCloudModel}onModelSelect={onCloudModelSelect}- colorScheme={colorScheme === "purple" ? "purple" : "indigo"}+ colorScheme="purple"/></div></div>@@ -869,7 +869,7 @@ export default function TranscriptionModelPicker({providers={LOCAL_PROVIDER_TABS}selectedId={internalLocalProvider}onSelect={handleLocalProviderChange}- colorScheme={colorScheme === "purple" ? "purple" : "indigo"}+ colorScheme="purple"/></div>diff --git a/src/components/UpgradePrompt.tsx b/src/components/UpgradePrompt.tsxindex fa91f9e68..d4eff27a4 100644--- a/src/components/UpgradePrompt.tsx+++ b/src/components/UpgradePrompt.tsx@@ -2,6 +2,7 @@ import { Dialog, DialogContent } from "./ui/dialog";import { ChevronRight } from "lucide-react";import { useTranslation } from "react-i18next";import { useUsage } from "../hooks/useUsage";+import { useSettingsStore } from "../stores/settingsStore";interface UpgradePromptProps {open: boolean;@@ -71,7 +72,7 @@ export default function UpgradePrompt({title={t("upgradePrompt.useApiKey")}description={t("upgradePrompt.useApiKeyDescription")}onClick={() => {- localStorage.setItem("cloudTranscriptionMode", "byok");+ useSettingsStore.getState().setCloudTranscriptionMode("byok");onOpenChange(false);}}/>@@ -79,7 +80,7 @@ export default function UpgradePrompt({title={t("upgradePrompt.switchToLocal")}description={t("upgradePrompt.switchToLocalDescription")}onClick={() => {- localStorage.setItem("useLocalWhisper", "true");+ useSettingsStore.getState().setUseLocalWhisper(true);onOpenChange(false);}}/>diff --git a/src/components/UsageDisplay.tsx b/src/components/UsageDisplay.tsxnew file mode 100644index 000000000..89b0643ff--- /dev/null+++ b/src/components/UsageDisplay.tsx@@ -0,0 +1,144 @@+import { useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { useUsage } from "../hooks/useUsage";+import { useToast } from "./ui/Toast";+import { Badge } from "./ui/badge";+import { Progress } from "./ui/progress";+import { Button } from "./ui/button";+import { useSettingsStore } from "../stores/settingsStore";++export default function UsageDisplay() {+ const { t } = useTranslation();+ const usage = useUsage();+ const { toast } = useToast();+ const hasShownApproachingToast = useRef(false);++ // One-time toast when approaching limit (>80%)+ useEffect(() => {+ if (usage?.isApproachingLimit && !hasShownApproachingToast.current) {+ hasShownApproachingToast.current = true;+ toast({+ title: t("usage.approachingLimit"),+ description: t("usage.approachingLimitDescription", {+ wordsUsed: usage.wordsUsed.toLocaleString(),+ limit: usage.limit.toLocaleString(),+ }),+ duration: 6000,+ });+ }+ }, [usage?.isApproachingLimit, usage?.wordsUsed, usage?.limit, toast, t]);++ if (!usage) return null;++ // Pro plan or trial — minimal display+ if (usage.isSubscribed) {+ return (+ <div className="bg-card border border-border rounded-xl p-4 space-y-3">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium text-foreground">{t("usage.yourPlan")}</span>+ {usage.isTrial ? (+ <Badge variant="outline" className="text-primary border-primary/30">+ {t("usage.trial", { days: usage.trialDaysLeft, count: usage.trialDaysLeft })}+ </Badge>+ ) : (+ <Badge variant="success">{t("usage.pro")}</Badge>+ )}+ </div>+ <p className="text-sm text-muted-foreground">+ {usage.isTrial ? t("usage.unlimitedTrial") : t("usage.unlimited")}+ </p>+ {!usage.isTrial && (+ <Button variant="outline" size="sm" onClick={() => usage.openBillingPortal()}>+ {t("usage.manageSubscription")}+ </Button>+ )}+ </div>+ );+ }++ // Free plan+ const percentage = usage.limit > 0 ? Math.min(100, (usage.wordsUsed / usage.limit) * 100) : 0;+ const progressColor =+ percentage >= 100+ ? "[&>div]:bg-destructive"+ : percentage >= 80+ ? "[&>div]:bg-warning"+ : "[&>div]:bg-primary";++ return (+ <div className="bg-card border border-border rounded-xl p-4 space-y-3">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium text-foreground">{t("usage.weeklyUsage")}</span>+ {usage.isOverLimit ? (+ <Badge variant="warning">{t("usage.limitReached")}</Badge>+ ) : (+ <Badge variant="outline">{t("usage.free")}</Badge>+ )}+ </div>++ <div className="space-y-1.5">+ <Progress+ value={percentage}+ className={`h-2 transition-colors duration-500 ${progressColor}`}+ />+ <div className="flex items-center justify-between">+ <span className="text-sm tabular-nums text-muted-foreground">+ {usage.wordsUsed.toLocaleString()} / {usage.limit.toLocaleString()}+ </span>+ {usage.isApproachingLimit && (+ <span className="text-xs text-warning">+ {t("usage.wordsRemaining", {+ count: usage.wordsRemaining,+ remaining: usage.wordsRemaining.toLocaleString(),+ })}+ </span>+ )}+ {!usage.isApproachingLimit && !usage.isOverLimit && (+ <span className="text-xs text-muted-foreground">{t("usage.rollingLimit")}</span>+ )}+ </div>+ </div>++ {usage.isOverLimit ? (+ <div className="flex gap-2">+ <Button+ size="sm"+ className="bg-primary hover:bg-primary/90"+ onClick={() => usage.openCheckout()}+ >+ {t("usage.upgradeToPro")}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ useSettingsStore.getState().setCloudTranscriptionMode("byok");+ window.location.reload();+ }}+ >+ {t("usage.useYourOwnKey")}+ </Button>+ </div>+ ) : usage.isApproachingLimit ? (+ <Button+ size="sm"+ className="bg-primary hover:bg-primary/90"+ onClick={() => usage.openCheckout()}+ >+ {t("usage.upgradeToPro")}+ </Button>+ ) : (+ <a+ href="#"+ className="text-primary hover:text-primary/80 text-sm inline-block"+ onClick={(e) => {+ e.preventDefault();+ usage.openCheckout();+ }}+ >+ {t("usage.upgradeUnlimited")}+ </a>+ )}+ </div>+ );+}diff --git a/src/components/WindowControls.tsx b/src/components/WindowControls.tsxindex 74c907ca3..da77cbad6 100644--- a/src/components/WindowControls.tsx+++ b/src/components/WindowControls.tsx@@ -1,13 +1,8 @@-import React, { useEffect, useState } from "react";+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";import { Minus, Square, X, Copy } from "lucide-react";-/**- * Window control buttons for Linux and Windows platforms- * Provides minimize, maximize/restore, and close functionality- * macOS uses native window controls so this component is not rendered there- */export default function WindowControls() {const { t } = useTranslation();const [isMaximized, setIsMaximized] = useState(false);@@ -15,22 +10,14 @@ export default function WindowControls() {useEffect(() => {let mounted = true;- // Sync maximized state with main processconst syncIsMaximized = async () => {try {const maximized = await window.electronAPI?.windowIsMaximized?.();- if (mounted) {- setIsMaximized(!!maximized);- }- } catch {- // Silently handle if API not available- }+ if (mounted) setIsMaximized(!!maximized);+ } catch {}};- // Initial syncsyncIsMaximized();-- // Poll for changes (window can be maximized via double-click on title bar, etc.)const intervalId = setInterval(syncIsMaximized, 1000);return () => {@@ -42,28 +29,21 @@ export default function WindowControls() {const handleMinimize = async () => {try {await window.electronAPI?.windowMinimize?.();- } catch {- // Silently handle if API not available- }+ } catch {}};const handleMaximize = async () => {try {await window.electronAPI?.windowMaximize?.();- // Update state after toggleconst maximized = await window.electronAPI?.windowIsMaximized?.();setIsMaximized(!!maximized);- } catch {- // Silently handle if API not available- }+ } catch {}};const handleClose = async () => {try {await window.electronAPI?.windowClose?.();- } catch {- // Silently handle if API not available- }+ } catch {}};return (diff --git a/src/components/notes/ActionManagerDialog.tsx b/src/components/notes/ActionManagerDialog.tsxnew file mode 100644index 000000000..c5d713dae--- /dev/null+++ b/src/components/notes/ActionManagerDialog.tsx@@ -0,0 +1,221 @@+import { useState, useEffect } from "react";+import { useTranslation } from "react-i18next";+import { Sparkles, Pencil, Trash2, Loader2 } from "lucide-react";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../ui/dialog";+import { Button } from "../ui/button";+import { cn } from "../lib/utils";+import {+ useActions,+ initializeActions,+ getActionName,+ getActionDescription,+} from "../../stores/actionStore";+import { notesInputClass } from "./shared";+import type { ActionItem } from "../../types/electron";++interface ActionManagerDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function ActionManagerDialog({ open, onOpenChange }: ActionManagerDialogProps) {+ const { t } = useTranslation();+ const actions = useActions();+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [prompt, setPrompt] = useState("");+ const [editingId, setEditingId] = useState<number | null>(null);+ const [isSaving, setIsSaving] = useState(false);++ useEffect(() => {+ if (open) {+ initializeActions();+ } else {+ resetForm();+ }+ }, [open]);++ const resetForm = () => {+ setName("");+ setDescription("");+ setPrompt("");+ setEditingId(null);+ };++ const handleEdit = (action: ActionItem) => {+ setName(action.name);+ setDescription(action.description);+ setPrompt(action.prompt);+ setEditingId(action.id);+ };++ const handleDelete = async (id: number) => {+ await window.electronAPI.deleteAction(id);+ if (editingId === id) resetForm();+ };++ const handleSave = async () => {+ if (!name.trim() || !prompt.trim()) return;+ setIsSaving(true);+ try {+ if (editingId !== null) {+ await window.electronAPI.updateAction(editingId, {+ name: name.trim(),+ description: description.trim(),+ prompt: prompt.trim(),+ });+ } else {+ await window.electronAPI.createAction(name.trim(), description.trim(), prompt.trim());+ }+ resetForm();+ } finally {+ setIsSaving(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg gap-2.5">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-sm">+ <Sparkles size={13} className="text-accent" />+ {t("notes.actions.manageTitle")}+ </DialogTitle>+ </DialogHeader>++ <div className="space-y-2">+ <p className="text-xs font-medium text-foreground/50">+ {editingId !== null ? t("notes.actions.editAction") : t("notes.actions.addAction")}+ </p>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t("notes.actions.namePlaceholder")}+ disabled={isSaving}+ className={cn(notesInputClass, "disabled:opacity-40")}+ />+ <input+ type="text"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder={t("notes.actions.descriptionPlaceholder")}+ disabled={isSaving}+ className={cn(notesInputClass, "disabled:opacity-40")}+ />+ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder={t("notes.actions.promptPlaceholder")}+ rows={3}+ disabled={isSaving}+ className={cn(+ "w-full px-3 py-2 rounded-md text-xs leading-relaxed resize-none",+ "bg-foreground/3 dark:bg-white/4 border border-border/30 dark:border-white/6",+ "text-foreground/80 placeholder:text-foreground/20 outline-none",+ "focus:border-primary/30 transition-colors duration-150",+ "disabled:opacity-40"+ )}+ />+ <div className="flex items-center justify-end gap-2">+ {editingId !== null && (+ <Button+ variant="ghost"+ size="sm"+ onClick={resetForm}+ disabled={isSaving}+ className="h-7 text-xs"+ >+ {t("notes.actions.cancel")}+ </Button>+ )}+ <Button+ variant="default"+ size="sm"+ onClick={handleSave}+ disabled={isSaving || !name.trim() || !prompt.trim()}+ className="h-7 text-xs"+ >+ {isSaving ? (+ <Loader2 size={12} className="animate-spin" />+ ) : editingId !== null ? (+ t("notes.actions.update")+ ) : (+ t("notes.actions.save")+ )}+ </Button>+ </div>+ </div>++ <div className="border-t border-border/20 dark:border-white/4 pt-2.5">+ {actions.length === 0 ? (+ <p className="text-xs text-muted-foreground/40 text-center py-4">+ {t("notes.actions.noActions")}+ </p>+ ) : (+ <div className="space-y-0.5 max-h-52 overflow-y-auto">+ {actions.map((action) => (+ <div+ key={action.id}+ className={cn(+ "flex items-center gap-2.5 px-2.5 py-2 rounded-md group",+ "hover:bg-foreground/3 dark:hover:bg-white/3",+ "transition-colors duration-150"+ )}+ >+ <Sparkles size={12} className="text-accent/40 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5">+ <span className="text-xs font-medium truncate">+ {getActionName(action, t)}+ </span>+ {action.is_builtin === 1 && (+ <span className="text-xs font-medium px-1.5 py-0.5 rounded bg-foreground/5 dark:bg-white/6 text-muted-foreground/50 shrink-0">+ {t("notes.actions.builtIn")}+ </span>+ )}+ </div>+ {action.description && (+ <p className="text-xs text-muted-foreground/40 truncate">+ {getActionDescription(action, t)}+ </p>+ )}+ </div>+ <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity duration-150 shrink-0">+ <button+ onClick={() => handleEdit(action)}+ aria-label={t("notes.actions.editAction")}+ className={cn(+ "p-1.5 rounded-md",+ "text-muted-foreground/40 hover:text-foreground/70",+ "hover:bg-foreground/5 dark:hover:bg-white/6",+ "active:bg-foreground/8 dark:active:bg-white/8",+ "transition-colors duration-150"+ )}+ >+ <Pencil size={11} />+ </button>+ {action.is_builtin !== 1 && (+ <button+ onClick={() => handleDelete(action.id)}+ aria-label={t("notes.context.delete")}+ className={cn(+ "p-1.5 rounded-md",+ "text-muted-foreground/40 hover:text-destructive/70",+ "hover:bg-destructive/5 active:bg-destructive/8",+ "transition-colors duration-150"+ )}+ >+ <Trash2 size={11} />+ </button>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/notes/ActionPicker.tsx b/src/components/notes/ActionPicker.tsxnew file mode 100644index 000000000..6971fa5be--- /dev/null+++ b/src/components/notes/ActionPicker.tsx@@ -0,0 +1,129 @@+import { useState, useEffect } from "react";+import { useTranslation } from "react-i18next";+import { Sparkles, ChevronDown, Settings2 } from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";+import {+ useActions,+ initializeActions,+ getActionName,+ getActionDescription,+} from "../../stores/actionStore";+import type { ActionItem } from "../../types/electron";++interface ActionPickerProps {+ onRunAction: (action: ActionItem) => void;+ onManageActions: () => void;+ disabled?: boolean;+}++export default function ActionPicker({+ onRunAction,+ onManageActions,+ disabled,+}: ActionPickerProps) {+ const { t } = useTranslation();+ const actions = useActions();+ const [lastUsedId, setLastUsedId] = useState<number | null>(null);++ useEffect(() => {+ initializeActions();+ const stored = localStorage.getItem("lastUsedActionId");+ if (stored) setLastUsedId(Number(stored));+ }, []);++ const activeAction = actions.find((a) => a.id === lastUsedId) ?? actions[0] ?? null;++ const handleRun = (action: ActionItem) => {+ setLastUsedId(action.id);+ localStorage.setItem("lastUsedActionId", String(action.id));+ onRunAction(action);+ };++ if (!activeAction) return null;++ return (+ <div className="flex items-center">+ <button+ onClick={() => handleRun(activeAction)}+ disabled={disabled}+ aria-label={t("notes.actions.runAction", { name: getActionName(activeAction, t) })}+ className={cn(+ "flex items-center gap-2 h-11 pl-5 pr-3 rounded-l-xl",+ "bg-accent/8 dark:bg-accent/12",+ "backdrop-blur-xl",+ "border border-r-0 border-accent/15 dark:border-accent/20",+ "shadow-sm hover:shadow-md",+ "text-accent/70 hover:text-accent",+ "transition-[background-color,color,transform] duration-200",+ "hover:bg-accent/12 dark:hover:bg-accent/18",+ "active:scale-[0.98]",+ "disabled:opacity-40 disabled:pointer-events-none"+ )}+ >+ <Sparkles size={14} />+ <span className="text-xs font-semibold tracking-tight">+ {getActionName(activeAction, t)}+ </span>+ </button>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ disabled={disabled}+ aria-label={t("notes.actions.selectAction")}+ className={cn(+ "flex items-center justify-center h-11 w-8 rounded-r-xl",+ "bg-accent/8 dark:bg-accent/12",+ "backdrop-blur-xl",+ "border border-l-0 border-accent/15 dark:border-accent/20",+ "shadow-sm hover:shadow-md",+ "text-accent/50 hover:text-accent",+ "transition-[background-color,color,transform] duration-200",+ "hover:bg-accent/15 dark:hover:bg-accent/22",+ "disabled:opacity-40 disabled:pointer-events-none"+ )}+ >+ <ChevronDown size={12} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" side="top" sideOffset={8} className="min-w-48">+ {actions.map((action) => (+ <DropdownMenuItem+ key={action.id}+ onClick={() => handleRun(action)}+ className={cn(+ "text-xs gap-2.5 rounded-md px-2.5 py-1.5",+ action.id === activeAction.id && "bg-accent/5"+ )}+ >+ <Sparkles size={12} className="text-accent/50 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="font-medium truncate">{getActionName(action, t)}</div>+ {action.description && (+ <div className="text-xs text-muted-foreground/50 truncate">+ {getActionDescription(action, t)}+ </div>+ )}+ </div>+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={onManageActions}+ className="text-xs gap-2.5 rounded-md px-2.5 py-1.5 text-muted-foreground/60"+ >+ <Settings2 size={12} />+ {t("notes.actions.manage")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/src/components/notes/ActionProcessingOverlay.tsx b/src/components/notes/ActionProcessingOverlay.tsxnew file mode 100644index 000000000..65107a310--- /dev/null+++ b/src/components/notes/ActionProcessingOverlay.tsx@@ -0,0 +1,97 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Check } from "lucide-react";+import { cn } from "../lib/utils";+import type { ActionProcessingState } from "../../hooks/useActionProcessing";++interface ActionProcessingOverlayProps {+ state: ActionProcessingState;+ actionName: string | null;+}++export default function ActionProcessingOverlay({+ state,+ actionName,+}: ActionProcessingOverlayProps) {+ const { t } = useTranslation();+ const [visible, setVisible] = useState(false);++ useEffect(() => {+ if (state === "processing" || state === "success") {+ setVisible(true);+ } else if (state === "idle") {+ const id = setTimeout(() => setVisible(false), 300);+ return () => clearTimeout(id);+ }+ }, [state]);++ if (!visible && state === "idle") return null;++ const isSuccess = state === "success";+ const isFadingOut = state === "idle";++ return (+ <div+ className={cn(+ "absolute inset-0 z-[5] flex items-center justify-center",+ "bg-background/60 dark:bg-background/70 backdrop-blur-md",+ "transition-opacity duration-300",+ isFadingOut && "opacity-0 pointer-events-none"+ )}+ style={!isFadingOut ? { animation: "float-up 0.25s ease-out" } : undefined}+ >+ <div+ className="absolute inset-0 pointer-events-none opacity-[0.02]"+ style={{+ backgroundImage:+ "repeating-linear-gradient(0deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)",+ }}+ />++ <div+ className={cn(+ "absolute left-0 right-0 h-[2px] pointer-events-none scanner-sweep-line",+ isSuccess ? "bg-success/60" : "bg-accent/60"+ )}+ style={{+ animation: isSuccess ? "none" : "scanner-sweep 2.5s ease-in-out infinite",+ boxShadow: isSuccess+ ? "0 0 24px 8px oklch(0.7 0.18 145 / 0.2)"+ : "0 0 24px 8px oklch(0.55 0.22 285 / 0.15)",+ ...(isSuccess ? { top: "50%" } : {}),+ }}+ />++ <div+ className={cn(+ "relative flex flex-col items-center gap-2.5",+ isSuccess+ ? "bg-success/6 dark:bg-success/8 border-success/12 dark:border-success/15"+ : "bg-accent/6 dark:bg-accent/8 border-accent/12 dark:border-accent/15",+ "backdrop-blur-xl border rounded-xl px-6 py-3 shadow-elevated",+ "transition-colors duration-300"+ )}+ >+ {isSuccess ? (+ <div className="flex items-center gap-2">+ <Check size={13} className="text-success/70" />+ <span className="text-xs font-medium text-success/70 tracking-tight">+ {t("notes.actions.done")}+ </span>+ </div>+ ) : (+ <>+ <span className="text-xs font-medium text-accent/70 tracking-tight">{actionName}</span>+ <div className="w-32 h-0.5 bg-accent/10 rounded-full overflow-hidden">+ <div+ className="h-full w-1/3 bg-accent/40 rounded-full"+ style={{ animation: "indeterminate 1.5s ease-in-out infinite" }}+ data-scanner-progress=""+ />+ </div>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/notes/AddNotesToFolderDialog.tsx b/src/components/notes/AddNotesToFolderDialog.tsxnew file mode 100644index 000000000..e1a18e92e--- /dev/null+++ b/src/components/notes/AddNotesToFolderDialog.tsx@@ -0,0 +1,175 @@+import { useState, useEffect, useMemo, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Search, FileText, Check } from "lucide-react";+import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";+import { Button } from "../ui/button";+import { cn } from "../lib/utils";+import { formatDateGroup } from "../../utils/dateFormatting";+import type { NoteItem } from "../../types/electron";++interface AddNotesToFolderDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ targetFolderId: number;+ onNotesAdded: () => void;+}++function groupNotesByDate(notes: NoteItem[], t: (key: string) => string): [string, NoteItem[]][] {+ const groups = new Map<string, NoteItem[]>();+ for (const note of notes) {+ const key = formatDateGroup(note.updated_at, t);+ const arr = groups.get(key) || [];+ arr.push(note);+ groups.set(key, arr);+ }+ return Array.from(groups.entries());+}++export default function AddNotesToFolderDialog({+ open,+ onOpenChange,+ targetFolderId,+ onNotesAdded,+}: AddNotesToFolderDialogProps) {+ const { t } = useTranslation();+ const [allNotes, setAllNotes] = useState<NoteItem[]>([]);+ const [search, setSearch] = useState("");+ const [selected, setSelected] = useState<Set<number>>(new Set());+ const [isAdding, setIsAdding] = useState(false);++ useEffect(() => {+ if (!open) return;+ setSearch("");+ setSelected(new Set());+ window.electronAPI.getNotes(null, 500, null).then(setAllNotes);+ }, [open]);++ const availableNotes = useMemo(+ () => allNotes.filter((n) => n.folder_id !== targetFolderId),+ [allNotes, targetFolderId]+ );++ const filteredNotes = useMemo(() => {+ if (!search.trim()) return availableNotes;+ const q = search.toLowerCase();+ return availableNotes.filter(+ (n) => n.title.toLowerCase().includes(q) || n.content.toLowerCase().includes(q)+ );+ }, [availableNotes, search]);++ const grouped = useMemo(() => groupNotesByDate(filteredNotes, t), [filteredNotes, t]);++ const toggleNote = useCallback((id: number) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);++ const handleAdd = useCallback(async () => {+ if (selected.size === 0) return;+ setIsAdding(true);+ try {+ await Promise.all(+ Array.from(selected).map((id) =>+ window.electronAPI.updateNote(id, { folder_id: targetFolderId })+ )+ );+ onNotesAdded();+ onOpenChange(false);+ } finally {+ setIsAdding(false);+ }+ }, [selected, targetFolderId, onNotesAdded, onOpenChange]);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-96 p-0 gap-0 overflow-hidden" aria-describedby={undefined}>+ <DialogTitle className="sr-only">{t("notes.addToFolder.title")}</DialogTitle>++ <div className="px-4 pr-12 pt-4 pb-2">+ <div className="relative">+ <Search+ size={13}+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-foreground/20"+ />+ <input+ placeholder={t("notes.addToFolder.searchPlaceholder")}+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ className="w-full h-8 rounded-md bg-foreground/[0.03] dark:bg-white/[0.04] border border-foreground/8 dark:border-white/8 pl-8 pr-3 text-xs text-foreground placeholder:text-foreground/20 outline-none focus:border-primary/30 transition-colors"+ autoFocus+ />+ </div>+ </div>++ <div className="max-h-80 overflow-y-auto px-2 pb-2">+ {grouped.length === 0 ? (+ <div className="flex items-center justify-center py-10">+ <p className="text-xs text-foreground/20">+ {search+ ? t("notes.addToFolder.noResults")+ : t("notes.addToFolder.noNotesAvailable")}+ </p>+ </div>+ ) : (+ grouped.map(([dateLabel, notes]) => (+ <div key={dateLabel}>+ <p className="text-xs font-medium text-foreground/30 px-2 pt-3 pb-1.5">+ {dateLabel}+ </p>+ {notes.map((note) => {+ const isSelected = selected.has(note.id);+ return (+ <button+ key={note.id}+ onClick={() => toggleNote(note.id)}+ className={cn(+ "w-full flex items-center gap-3 px-2 py-2 rounded-md transition-colors",+ "hover:bg-foreground/3 dark:hover:bg-white/3",+ isSelected && "bg-primary/5 dark:bg-primary/8"+ )}+ >+ <div className="w-7 h-7 rounded-md bg-foreground/[0.03] dark:bg-white/[0.04] border border-foreground/6 dark:border-white/6 flex items-center justify-center shrink-0">+ <FileText size={12} className="text-foreground/20" />+ </div>+ <div className="flex-1 min-w-0 text-left">+ <p className="text-xs text-foreground/80 truncate">+ {note.title || t("notes.list.untitled")}+ </p>+ </div>+ <div+ className={cn(+ "w-4 h-4 rounded-[3px] border shrink-0 flex items-center justify-center transition-colors",+ isSelected+ ? "bg-primary border-primary"+ : "border-foreground/15 dark:border-white/15"+ )}+ >+ {isSelected && <Check size={10} className="text-white" strokeWidth={2.5} />}+ </div>+ </button>+ );+ })}+ </div>+ ))+ )}+ </div>++ <div className="px-4 py-3 border-t border-border/30 dark:border-white/5 flex justify-end">+ <Button+ variant="default"+ size="sm"+ onClick={handleAdd}+ disabled={selected.size === 0 || isAdding}+ className="h-7 text-xs"+ >+ {t("notes.addToFolder.addCount", { count: selected.size })}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/notes/DictationWidget.tsx b/src/components/notes/DictationWidget.tsxnew file mode 100644index 000000000..f548ecb63--- /dev/null+++ b/src/components/notes/DictationWidget.tsx@@ -0,0 +1,137 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Mic, Square, Loader2 } from "lucide-react";+import { cn } from "../lib/utils";++interface DictationWidgetProps {+ isRecording: boolean;+ isProcessing: boolean;+ onStart: () => void;+ onStop: () => void;+ actionPicker?: React.ReactNode;+}++const BAR_COUNT = 7;++export default function DictationWidget({+ isRecording,+ isProcessing,+ onStart,+ onStop,+ actionPicker,+}: DictationWidgetProps) {+ const { t } = useTranslation();+ const [elapsed, setElapsed] = useState(0);++ useEffect(() => {+ if (!isRecording) {+ setElapsed(0);+ return;+ }+ const id = setInterval(() => setElapsed((s) => s + 1), 1000);+ return () => clearInterval(id);+ }, [isRecording]);++ const minutes = String(Math.floor(elapsed / 60)).padStart(2, "0");+ const seconds = String(elapsed % 60).padStart(2, "0");++ return (+ <div className="absolute bottom-5 left-0 right-0 z-10 flex justify-center pointer-events-none">+ {isRecording ? (+ <div+ className={cn(+ "flex items-center gap-4 h-12 px-5 rounded-xl pointer-events-auto",+ "bg-primary/6 dark:bg-primary/10",+ "backdrop-blur-xl",+ "border border-primary/20 dark:border-primary/25",+ "shadow-elevated"+ )}+ style={{+ animation: "grow-to-bar 0.45s cubic-bezier(0.22, 1, 0.36, 1) both",+ }}+ >+ <div+ className="flex items-end gap-0.75 h-5"+ style={{+ animation: "fade-in-content 0.3s ease-out 0.2s both",+ }}+ >+ {Array.from({ length: BAR_COUNT }, (_, i) => (+ <div+ key={i}+ className="w-0.75 rounded-full bg-primary/60 dark:bg-primary/70 origin-bottom"+ style={{+ height: "100%",+ animation: `waveform-bar ${0.6 + i * 0.08}s ease-in-out infinite`,+ animationDelay: `${0.35 + i * 0.05}s`,+ }}+ />+ ))}+ </div>++ <span+ className="text-xs font-medium tabular-nums text-primary/60 dark:text-primary/70 min-w-9"+ style={{+ animation: "fade-in-content 0.3s ease-out 0.25s both",+ }}+ >+ {minutes}:{seconds}+ </span>++ <button+ onClick={onStop}+ className={cn(+ "flex items-center justify-center w-7 h-7 rounded-lg",+ "bg-primary/10 hover:bg-primary/18 active:bg-primary/25",+ "text-primary",+ "transition-colors duration-150"+ )}+ style={{+ animation: "fade-in-content 0.3s ease-out 0.3s both",+ }}+ aria-label={t("notes.editor.stop")}+ >+ <Square size={12} fill="currentColor" />+ </button>+ </div>+ ) : isProcessing ? (+ <div+ className={cn(+ "flex items-center gap-3 h-12 px-5 rounded-xl pointer-events-auto",+ "bg-primary/6 dark:bg-primary/10",+ "backdrop-blur-xl",+ "border border-primary/15 dark:border-primary/20",+ "shadow-elevated"+ )}+ >+ <Loader2 size={14} className="animate-spin text-primary/50" />+ <span className="text-xs font-medium text-primary/50">+ {t("notes.editor.processing")}+ </span>+ </div>+ ) : (+ <div className="flex items-center gap-2 pointer-events-auto">+ <button+ onClick={onStart}+ className={cn(+ "flex items-center justify-center w-11 h-11 rounded-full",+ "bg-primary/8 dark:bg-primary/12",+ "backdrop-blur-xl",+ "border border-primary/15 dark:border-primary/20",+ "shadow-sm hover:shadow-md",+ "text-primary/60 hover:text-primary",+ "transition-all duration-200",+ "hover:bg-primary/14 dark:hover:bg-primary/20",+ "hover:scale-105",+ "active:scale-[0.97]"+ )}+ aria-label={t("notes.editor.transcribe")}+ >+ <Mic size={16} />+ </button>+ {actionPicker}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxnew file mode 100644index 000000000..3bc9d65ff--- /dev/null+++ b/src/components/notes/NoteEditor.tsx@@ -0,0 +1,733 @@+import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Download, Loader2, FileText, Sparkles, AlignLeft } from "lucide-react";+import { MarkdownTextarea } from "../ui/MarkdownTextarea";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";+import type { NoteItem } from "../../types/electron";+import type { ActionProcessingState } from "../../hooks/useActionProcessing";+import ActionProcessingOverlay from "./ActionProcessingOverlay";+import DictationWidget from "./DictationWidget";++function formatNoteDate(dateStr: string): string {+ const source = dateStr.endsWith("Z") ? dateStr : `${dateStr}Z`;+ const date = new Date(source);+ if (Number.isNaN(date.getTime())) return "";+ const datePart = date.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ year: "numeric",+ });+ const timePart = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+ return `${datePart} \u00b7 ${timePart}`;+}++export interface Enhancement {+ content: string;+ isStale: boolean;+ onChange: (content: string) => void;+}++interface NoteEditorProps {+ note: NoteItem;+ onTitleChange: (title: string) => void;+ onContentChange: (content: string) => void;+ isSaving: boolean;+ isRecording: boolean;+ partialTranscript: string;+ finalTranscript: string | null;+ onFinalTranscriptConsumed: () => void;+ streamingCommit: string | null;+ onStreamingCommitConsumed: () => void;+ isProcessing: boolean;+ onStartRecording: () => void;+ onStopRecording: () => void;+ onExportNote?: (format: "md" | "txt") => void;+ enhancement?: Enhancement;+ actionPicker?: React.ReactNode;+ actionProcessingState?: ActionProcessingState;+ actionName?: string | null;+}++interface DictationRange {+ start: number;+ partialStart: number;+ end: number;+ committedChars: number;+}++interface TextSelectionRange {+ start: number;+ end: number;+}++interface PendingSelectionRestore extends TextSelectionRange {+ version: number;+}++function transformSelectionForReplacement(+ selection: TextSelectionRange,+ replaceStart: number,+ replaceEnd: number,+ insertLength: number+): TextSelectionRange {+ const replacementEnd = replaceStart + insertLength;++ const overlapsReplacement =+ selection.start === selection.end+ ? selection.start >= replaceStart && selection.start <= replaceEnd+ : selection.start < replaceEnd && selection.end > replaceStart;++ if (overlapsReplacement) {+ return { start: replacementEnd, end: replacementEnd };+ }++ const delta = insertLength - (replaceEnd - replaceStart);+ const shift = (index: number) => {+ if (index > replaceEnd) return index + delta;+ if (index === replaceEnd) return replacementEnd;+ return index;+ };++ return {+ start: shift(selection.start),+ end: shift(selection.end),+ };+}++function mapIndexThroughUserEdit(+ index: number,+ editStart: number,+ editEnd: number,+ insertLength: number+): number {+ const delta = insertLength - (editEnd - editStart);++ if (editStart === editEnd) {+ return index < editStart ? index : index + delta;+ }++ if (index < editStart) return index;+ if (index > editEnd) return index + delta;+ return editStart + insertLength;+}++function mapIndexAfterRangeRemoval(index: number, removeStart: number, removeEnd: number): number {+ const removedLength = removeEnd - removeStart;++ if (index < removeStart) return index;+ if (index > removeEnd) return index - removedLength;+ return removeStart;+}++export default function NoteEditor({+ note,+ onTitleChange,+ onContentChange,+ isSaving,+ isRecording,+ isProcessing,+ partialTranscript,+ finalTranscript,+ onFinalTranscriptConsumed,+ streamingCommit,+ onStreamingCommitConsumed,+ onStartRecording,+ onStopRecording,+ onExportNote,+ enhancement,+ actionPicker,+ actionProcessingState,+ actionName,+}: NoteEditorProps) {+ const { t } = useTranslation();+ const [viewMode, setViewMode] = useState<"raw" | "enhanced">("raw");+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const titleRef = useRef<HTMLDivElement>(null);+ const prevNoteIdRef = useRef<number>(note.id);++ const cursorPosRef = useRef(0);+ const selectionEndRef = useRef(0);+ const dictationRef = useRef<DictationRange | null>(null);+ const prevRecordingRef = useRef(false);+ const expectedSelectionRef = useRef<TextSelectionRange>({ start: 0, end: 0 });+ const selectionVersionRef = useRef(0);+ const pendingSelectionRestoreRef = useRef<PendingSelectionRestore | null>(null);+ const suppressSelectionCaptureRef = useRef(false);+ const beforeInputSelectionRef = useRef<TextSelectionRange | null>(null);+ const contentRef = useRef(note.content);+ contentRef.current = note.content;++ const syncSelectionRefs = useCallback((start: number, end: number) => {+ cursorPosRef.current = start;+ selectionEndRef.current = end;+ expectedSelectionRef.current = { start, end };+ }, []);++ const queueSelectionRestore = useCallback(+ (start: number, end: number, version = selectionVersionRef.current) => {+ syncSelectionRefs(start, end);+ pendingSelectionRestoreRef.current = { start, end, version };+ },+ [syncSelectionRefs]+ );++ const applyProgrammaticSelection = useCallback(+ (start: number, end: number) => {+ const ta = textareaRef.current;+ if (!ta) return;+ suppressSelectionCaptureRef.current = true;+ ta.setSelectionRange(start, end);+ queueMicrotask(() => {+ suppressSelectionCaptureRef.current = false;+ });+ syncSelectionRefs(start, end);+ },+ [syncSelectionRefs]+ );++ const commitContentChange = useCallback(+ (newContent: string, nextSelection?: TextSelectionRange, selectionVersion?: number) => {+ if (nextSelection) {+ queueSelectionRestore(nextSelection.start, nextSelection.end, selectionVersion);+ }+ contentRef.current = newContent;+ onContentChange(newContent);+ },+ [onContentChange, queueSelectionRestore]+ );++ const replaceContentRange = useCallback(+ (replaceStart: number, replaceEnd: number, insertText: string) => {+ const currentContent = contentRef.current;+ const before = currentContent.slice(0, replaceStart);+ const after = currentContent.slice(replaceEnd);+ const newContent = before + insertText + after;+ const selectionBefore = expectedSelectionRef.current;+ const selectionVersion = selectionVersionRef.current;+ const nextSelection = transformSelectionForReplacement(+ selectionBefore,+ replaceStart,+ replaceEnd,+ insertText.length+ );++ commitContentChange(newContent, nextSelection, selectionVersion);+ return newContent;+ },+ [commitContentChange]+ );++ const reanchorDictationToSelection = useCallback(+ (anchorStart: number, anchorEnd: number, selectionVersion: number) => {+ const range = dictationRef.current;+ if (!range) return;++ if (range.partialStart === range.end) {+ range.start = anchorStart;+ range.partialStart = anchorStart;+ range.end = anchorEnd;+ return;+ }++ const currentContent = contentRef.current;+ const partialText = currentContent.slice(range.partialStart, range.end);++ if (!partialText) {+ range.start = anchorStart;+ range.partialStart = anchorStart;+ range.end = anchorEnd;+ return;+ }++ const withoutPartial =+ currentContent.slice(0, range.partialStart) + currentContent.slice(range.end);+ const targetStart = mapIndexAfterRangeRemoval(anchorStart, range.partialStart, range.end);+ const targetEnd = mapIndexAfterRangeRemoval(anchorEnd, range.partialStart, range.end);+ const newContent =+ withoutPartial.slice(0, targetStart) + partialText + withoutPartial.slice(targetEnd);++ const newPartialStart = targetStart;+ const newEnd = newPartialStart + partialText.length;++ range.start = newPartialStart;+ range.partialStart = newPartialStart;+ range.end = newEnd;++ commitContentChange(newContent, { start: newEnd, end: newEnd }, selectionVersion);+ },+ [commitContentChange]+ );++ const captureUserSelection = useCallback(+ (start: number, end: number) => {+ const prev = expectedSelectionRef.current;+ const changed = prev.start !== start || prev.end !== end;++ syncSelectionRefs(start, end);++ if (!changed) return;++ selectionVersionRef.current += 1;++ if (dictationRef.current) {+ reanchorDictationToSelection(start, end, selectionVersionRef.current);+ }+ },+ [reanchorDictationToSelection, syncSelectionRefs]+ );++ useLayoutEffect(() => {+ const pending = pendingSelectionRestoreRef.current;+ if (!pending) return;+ pendingSelectionRestoreRef.current = null;+ if (pending.version !== selectionVersionRef.current) return;+ applyProgrammaticSelection(pending.start, pending.end);+ }, [note.content, applyProgrammaticSelection]);++ // Capture selection before browser applies user edits so dictation range+ // adjustments handle replacements/paste correctly.+ useEffect(() => {+ const ta = textareaRef.current;+ if (!ta) return;+ const handler = () => {+ if (suppressSelectionCaptureRef.current) return;+ beforeInputSelectionRef.current = {+ start: ta.selectionStart,+ end: ta.selectionEnd,+ };+ };+ ta.addEventListener("beforeinput", handler);+ return () => {+ ta.removeEventListener("beforeinput", handler);+ };+ }, [viewMode]);++ // Capture cursor on mouse interaction — click for positioning,+ // mouseup for drag-selections (click may not fire if drag distance is large)+ useEffect(() => {+ const ta = textareaRef.current;+ if (!ta) return;+ const handler = () => {+ if (suppressSelectionCaptureRef.current) return;+ captureUserSelection(ta.selectionStart, ta.selectionEnd);+ };+ ta.addEventListener("click", handler);+ ta.addEventListener("mouseup", handler);+ return () => {+ ta.removeEventListener("click", handler);+ ta.removeEventListener("mouseup", handler);+ };+ }, [captureUserSelection, viewMode]);++ const segmentContainerRef = useRef<HTMLDivElement>(null);+ const [indicatorStyle, setIndicatorStyle] = useState<React.CSSProperties>({ opacity: 0 });++ const updateSegmentIndicator = useCallback(() => {+ const container = segmentContainerRef.current;+ if (!container) return;++ const idx = viewMode === "raw" ? 0 : 1;++ const buttons = container.querySelectorAll<HTMLButtonElement>("[data-segment-button]");+ const btn = buttons[idx];+ if (!btn) return;++ const cr = container.getBoundingClientRect();+ const br = btn.getBoundingClientRect();+ setIndicatorStyle({+ width: br.width,+ height: br.height,+ transform: `translateX(${br.left - cr.left}px)`,+ opacity: 1,+ });+ }, [viewMode]);++ useEffect(() => {+ updateSegmentIndicator();+ }, [updateSegmentIndicator]);++ useEffect(() => {+ const observer = new ResizeObserver(() => updateSegmentIndicator());+ if (segmentContainerRef.current) observer.observe(segmentContainerRef.current);+ return () => observer.disconnect();+ }, [updateSegmentIndicator]);++ const prevProcessingStateRef = useRef(actionProcessingState);+ useEffect(() => {+ if (prevProcessingStateRef.current === "processing" && actionProcessingState === "success") {+ setViewMode("enhanced");+ }+ prevProcessingStateRef.current = actionProcessingState;+ }, [actionProcessingState]);++ useEffect(() => {+ if (note.id !== prevNoteIdRef.current) {+ prevNoteIdRef.current = note.id;+ setViewMode("raw");+ if (titleRef.current && titleRef.current.textContent !== note.title) {+ titleRef.current.textContent = note.title || "";+ }+ textareaRef.current?.focus();+ if (textareaRef.current) {+ const start = textareaRef.current.selectionStart;+ const end = textareaRef.current.selectionEnd;+ syncSelectionRefs(start, end);+ }+ pendingSelectionRestoreRef.current = null;+ beforeInputSelectionRef.current = null;+ }+ }, [note.id, syncSelectionRefs]);++ useEffect(() => {+ if (titleRef.current && titleRef.current.textContent !== note.title) {+ titleRef.current.textContent = note.title || "";+ }+ }, [note.title]);++ const handleTitleInput = useCallback(() => {+ if (titleRef.current) {+ const text = titleRef.current.textContent || "";+ onTitleChange(text);+ }+ }, [onTitleChange]);++ const handleTitleKeyDown = useCallback((e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ e.preventDefault();+ textareaRef.current?.focus();+ }+ }, []);++ const handleTitlePaste = useCallback((e: React.ClipboardEvent) => {+ e.preventDefault();+ const text = e.clipboardData.getData("text/plain").replace(/\n/g, " ");+ document.execCommand("insertText", false, text);+ }, []);++ // --- Dictation lifecycle ---++ const handleStartRecording = useCallback(() => {+ if (textareaRef.current) {+ syncSelectionRefs(textareaRef.current.selectionStart, textareaRef.current.selectionEnd);+ }+ onStartRecording();+ }, [onStartRecording, syncSelectionRefs]);++ useEffect(() => {+ if (isRecording && !prevRecordingRef.current) {+ const selStart = cursorPosRef.current;+ const selEnd = selectionEndRef.current;+ dictationRef.current = {+ start: selStart,+ partialStart: selStart,+ end: selEnd,+ committedChars: 0,+ };+ if (viewMode === "enhanced") setViewMode("raw");+ }+ if (!isRecording && prevRecordingRef.current) {+ // Only clear if no progressive text was inserted (non-streaming case).+ // For streaming, keep dictationRef alive so the final transcript replaces+ // the partial zone instead of inserting a duplicate at cursor.+ const range = dictationRef.current;+ if (range && range.partialStart === range.start && range.end === range.start) {+ dictationRef.current = null;+ }+ }+ prevRecordingRef.current = isRecording;+ }, [isRecording]);++ // Partial effect: only replace the active partial zone [partialStart, end].+ // Committed text before partialStart is untouched — users can edit it freely.+ useEffect(() => {+ if (!partialTranscript || !dictationRef.current) return;++ const { partialStart, end } = dictationRef.current;+ const hasCommitted = partialStart > dictationRef.current.start;+ const textToInsert = (hasCommitted ? " " : "") + partialTranscript;+ const newEnd = partialStart + textToInsert.length;++ replaceContentRange(partialStart, end, textToInsert);+ dictationRef.current.end = newEnd;+ }, [partialTranscript, replaceContentRange]); // note.content intentionally excluded++ // Streaming commit: a Deepgram segment was finalized. Replace the partial zone+ // with the committed text and advance partialStart for the next utterance.+ useEffect(() => {+ if (streamingCommit == null || !dictationRef.current) return;++ const { partialStart, end } = dictationRef.current;+ const newPartialStart = partialStart + streamingCommit.length;++ replaceContentRange(partialStart, end, streamingCommit);+ dictationRef.current.partialStart = newPartialStart;+ dictationRef.current.end = newPartialStart;+ dictationRef.current.committedChars += streamingCommit.length;++ onStreamingCommitConsumed();+ }, [streamingCommit, onStreamingCommitConsumed, replaceContentRange]); // note.content intentionally excluded++ // Final transcript (on recording stop).+ useEffect(() => {+ if (finalTranscript == null) return;++ const range = dictationRef.current;+ if (!range) {+ // Non-streaming: insert at cursor with separator+ const pos = cursorPosRef.current;+ const before = contentRef.current.slice(0, pos);+ const after = contentRef.current.slice(pos);+ const separator = before && !before.endsWith("\n") ? "\n" : "";+ const newContent = before + separator + finalTranscript + after;+ commitContentChange(newContent);+ onFinalTranscriptConsumed();+ return;+ }++ // Streaming: committed text is already in the note. Only finalize the+ // remaining partial zone with the tail of the final transcript.+ const { partialStart, end, committedChars } = range;+ const remainingFinal = finalTranscript.slice(committedChars);++ // If partial zone is empty and nothing new to insert, just clean up+ if (partialStart === end && !remainingFinal.trim()) {+ dictationRef.current = null;+ onFinalTranscriptConsumed();+ return;+ }++ replaceContentRange(partialStart, end, remainingFinal);+ dictationRef.current = null;+ onFinalTranscriptConsumed();+ }, [finalTranscript, commitContentChange, onFinalTranscriptConsumed, replaceContentRange]); // note.content intentionally excluded++ // Safety: clear dictation range when processing ends without a final transcript+ // (e.g. cancelled recording with no captured text). Declared after the final+ // transcript effect so it runs second if both trigger in the same render.+ const prevDictationProcessingRef = useRef(false);+ useEffect(() => {+ if (prevDictationProcessingRef.current && !isProcessing && dictationRef.current) {+ dictationRef.current = null;+ }+ prevDictationProcessingRef.current = isProcessing;+ }, [isProcessing]);++ const handleSelect = () => {+ if (textareaRef.current && document.activeElement === textareaRef.current) {+ if (suppressSelectionCaptureRef.current) return;+ captureUserSelection(textareaRef.current.selectionStart, textareaRef.current.selectionEnd);+ }+ };++ const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ const newValue = e.target.value;++ // Skip no-op changes (e.g. React controlled-component echo during dictation)+ if (newValue === note.content) return;++ if (dictationRef.current) {+ const beforeInput = beforeInputSelectionRef.current;+ beforeInputSelectionRef.current = null;++ if (beforeInput) {+ const replacedLength = beforeInput.end - beforeInput.start;+ const insertLength = newValue.length - (note.content.length - replacedLength);+ const range = dictationRef.current;++ const nextStart = mapIndexThroughUserEdit(+ range.start,+ beforeInput.start,+ beforeInput.end,+ insertLength+ );+ const nextPartialStart = mapIndexThroughUserEdit(+ range.partialStart,+ beforeInput.start,+ beforeInput.end,+ insertLength+ );+ const nextEnd = mapIndexThroughUserEdit(+ range.end,+ beforeInput.start,+ beforeInput.end,+ insertLength+ );++ range.start = Math.min(nextStart, newValue.length);+ range.partialStart = Math.min(Math.max(nextPartialStart, range.start), newValue.length);+ range.end = Math.min(Math.max(nextEnd, range.partialStart), newValue.length);+ } else {+ const delta = newValue.length - note.content.length;+ const editPos = e.target.selectionStart - delta;+ if (editPos <= dictationRef.current.start) {+ dictationRef.current.start += delta;+ dictationRef.current.partialStart += delta;+ dictationRef.current.end += delta;+ } else if (editPos <= dictationRef.current.partialStart) {+ dictationRef.current.partialStart += delta;+ dictationRef.current.end += delta;+ } else if (editPos < dictationRef.current.end) {+ dictationRef.current.end += delta;+ }+ }+ }++ beforeInputSelectionRef.current = null;+ contentRef.current = newValue;+ onContentChange(newValue);+ captureUserSelection(e.target.selectionStart, e.target.selectionEnd);+ };++ const handleEnhancedChange = useCallback(+ (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ enhancement?.onChange(e.target.value);+ },+ [enhancement]+ );++ const wordCount = useMemo(() => {+ const trimmed = note.content.trim();+ return trimmed ? trimmed.split(/\s+/).length : 0;+ }, [note.content]);++ const noteDate = formatNoteDate(note.created_at);++ return (+ <div className="flex flex-col h-full min-h-0">+ <div className="px-5 pt-4 pb-0">+ <div+ ref={titleRef}+ contentEditable+ suppressContentEditableWarning+ onInput={handleTitleInput}+ onKeyDown={handleTitleKeyDown}+ onPaste={handleTitlePaste}+ data-placeholder={t("notes.editor.untitled")}+ className="text-base font-semibold text-foreground bg-transparent outline-none tracking-[-0.01em] empty:before:content-[attr(data-placeholder)] empty:before:text-foreground/15 empty:before:pointer-events-none"+ role="textbox"+ aria-label={t("notes.editor.noteTitle")}+ />+ <div className="flex items-center mt-1">+ <div className="flex items-center text-xs text-foreground/50 dark:text-foreground/20 min-w-0">+ {noteDate && <span>{noteDate}</span>}+ {noteDate && (isSaving || wordCount > 0) && <span className="mx-1.5">·</span>}+ <span className="tabular-nums flex items-center gap-1 shrink-0">+ {isSaving && <Loader2 size={8} className="animate-spin" />}+ {isSaving+ ? t("notes.editor.saving")+ : wordCount > 0+ ? t("notes.editor.wordsCount", { count: wordCount })+ : ""}+ </span>+ </div>+ <div className="flex-1" />+ <div className="flex items-center gap-1">+ {enhancement && (+ <div+ ref={segmentContainerRef}+ className="relative flex items-center shrink-0 rounded-md bg-foreground/3 dark:bg-white/3 p-0.5"+ >+ <div+ className="absolute top-0.5 left-0 rounded bg-background dark:bg-surface-2 shadow-sm transition-[width,height,transform,opacity] duration-200 ease-out pointer-events-none"+ style={indicatorStyle}+ />+ <button+ data-segment-button+ onClick={() => setViewMode("raw")}+ className={cn(+ "relative z-1 px-1.5 h-5 rounded text-xs font-medium transition-colors duration-150 flex items-center gap-1",+ viewMode === "raw"+ ? "text-foreground/60"+ : "text-foreground/25 hover:text-foreground/40"+ )}+ >+ <AlignLeft size={10} />+ {t("notes.editor.raw")}+ </button>+ <button+ data-segment-button+ onClick={() => setViewMode("enhanced")}+ className={cn(+ "relative z-1 px-1.5 h-5 rounded text-xs font-medium transition-colors duration-150 flex items-center gap-1",+ viewMode === "enhanced"+ ? "text-foreground/60"+ : "text-foreground/25 hover:text-foreground/40"+ )}+ >+ <Sparkles size={9} />+ {t("notes.editor.enhanced")}+ {enhancement.isStale && (+ <span+ className="w-1 h-1 rounded-full bg-amber-400/60"+ title={t("notes.editor.staleIndicator")}+ />+ )}+ </button>+ </div>+ )}+ {onExportNote && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="shrink-0 h-6 w-6 flex items-center justify-center rounded-md bg-foreground/3 dark:bg-white/3 text-foreground/25 hover:text-foreground/40 hover:bg-foreground/6 dark:hover:bg-white/6 transition-colors duration-150"+ aria-label={t("notes.editor.export")}+ >+ <Download size={11} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4}>+ <DropdownMenuItem onClick={() => onExportNote("md")} className="text-xs gap-2">+ <FileText size={13} className="text-foreground/40" />+ {t("notes.editor.asMarkdown")}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onExportNote("txt")} className="text-xs gap-2">+ <FileText size={13} className="text-foreground/40" />+ {t("notes.editor.asPlainText")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ </div>+ </div>++ <div className="flex-1 relative min-h-0">+ <div className="h-full overflow-y-auto">+ {viewMode === "enhanced" && enhancement ? (+ <MarkdownTextarea value={enhancement.content} onChange={handleEnhancedChange} />+ ) : (+ <MarkdownTextarea+ value={note.content}+ onChange={handleContentChange}+ onSelect={handleSelect}+ textareaRef={textareaRef}+ placeholder={t("notes.editor.startWriting")}+ disabled={actionProcessingState === "processing"}+ />+ )}+ </div>+ <ActionProcessingOverlay+ state={actionProcessingState ?? "idle"}+ actionName={actionName ?? null}+ />+ <div+ className="absolute bottom-0 left-0 right-0 h-24 pointer-events-none"+ style={{ background: "linear-gradient(to bottom, transparent, var(--color-background))" }}+ />+ <DictationWidget+ isRecording={isRecording}+ isProcessing={isProcessing}+ onStart={handleStartRecording}+ onStop={onStopRecording}+ actionPicker={actionPicker}+ />+ </div>+ </div>+ );+}diff --git a/src/components/notes/NoteListItem.tsx b/src/components/notes/NoteListItem.tsxnew file mode 100644index 000000000..ec18986a2--- /dev/null+++ b/src/components/notes/NoteListItem.tsx@@ -0,0 +1,263 @@+import { useState, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { MoreHorizontal, FolderOpen, Trash2, Check, Plus, Search } from "lucide-react";+import { Button } from "../ui/button";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";+import type { NoteItem, FolderItem } from "../../types/electron";++const RE_HEADING = /#{1,6}\s+/g;+const RE_EMPHASIS = /[*_~`]+/g;+const RE_LINK = /\[([^\]]+)\]\([^)]+\)/g;+const RE_IMAGE = /!\[([^\]]*)\]\([^)]+\)/g;+const RE_BLOCKQUOTE = />\s+/g;+const RE_NEWLINES = /\n+/g;++interface NoteListItemProps {+ note: NoteItem;+ isActive: boolean;+ onClick: () => void;+ onDelete: (id: number) => void;+ folders: FolderItem[];+ currentFolderId: number | null;+ onMoveToFolder: (noteId: number, folderId: number) => void;+ onCreateFolderAndMove: (noteId: number, folderName: string) => void;+ dragHandlers?: {+ draggable: true;+ onDragStart: (e: React.DragEvent) => void;+ onDragEnd: () => void;+ };+ isDragging?: boolean;+}++function stripMarkdown(text: string): string {+ return text+ .replace(RE_HEADING, "")+ .replace(RE_EMPHASIS, "")+ .replace(RE_LINK, "$1")+ .replace(RE_IMAGE, "$1")+ .replace(RE_BLOCKQUOTE, "")+ .replace(RE_NEWLINES, " ")+ .trim();+}++function relativeTime(+ dateStr: string,+ t: (key: string, options?: Record<string, unknown>) => string+): string {+ const source = dateStr.endsWith("Z") ? dateStr : `${dateStr}Z`;+ const date = new Date(source);+ if (Number.isNaN(date.getTime())) return dateStr;++ const diff = Date.now() - date.getTime();+ const minutes = Math.floor(diff / 60000);+ const hours = Math.floor(diff / 3600000);+ const days = Math.floor(diff / 86400000);++ if (minutes < 1) return t("notes.list.timeNow");+ if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });+ if (hours < 24) return t("notes.list.hoursAgo", { count: hours });+ if (days < 7) return t("notes.list.daysAgo", { count: days });+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });+}++export default function NoteListItem({+ note,+ isActive,+ onClick,+ onDelete,+ folders,+ currentFolderId,+ onMoveToFolder,+ onCreateFolderAndMove,+ dragHandlers,+ isDragging,+}: NoteListItemProps) {+ const { t } = useTranslation();+ const preview = stripMarkdown(note.content);+ const [folderSearch, setFolderSearch] = useState("");+ const [newFolderName, setNewFolderName] = useState("");+ const [isCreating, setIsCreating] = useState(false);++ const filteredFolders = useMemo(+ () =>+ folderSearch+ ? folders.filter((f) => f.name.toLowerCase().includes(folderSearch.toLowerCase()))+ : folders,+ [folders, folderSearch]+ );++ return (+ <button+ type="button"+ onClick={onClick}+ {...dragHandlers}+ className={cn(+ "group relative w-full text-left px-3 py-2 cursor-pointer transition-all duration-150",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",+ isActive ? "bg-primary/6 dark:bg-primary/8" : "hover:bg-foreground/3 dark:hover:bg-white/3",+ isDragging && "opacity-40 scale-[0.97]"+ )}+ >+ {isActive && (+ <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 rounded-r-full bg-primary" />+ )}+ <div className="flex-1 min-w-0">+ <div className="flex items-center justify-between gap-2">+ <p+ className={cn(+ "text-xs truncate transition-colors duration-150",+ isActive ? "text-foreground font-medium" : "text-foreground"+ )}+ >+ {note.title || t("notes.list.untitled")}+ </p>+ <div className="flex items-center gap-0.5 shrink-0">+ <span className="text-xs text-muted-foreground dark:text-muted-foreground/30 tabular-nums group-hover:opacity-0 transition-opacity">+ {relativeTime(note.updated_at, t)}+ </span>+ <DropdownMenu+ onOpenChange={(open) => {+ if (!open) {+ setFolderSearch("");+ setIsCreating(false);+ setNewFolderName("");+ }+ }}+ >+ <DropdownMenuTrigger asChild>+ <Button+ size="icon"+ variant="ghost"+ onClick={(e) => e.stopPropagation()}+ className="h-5 w-5 rounded-sm opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity absolute right-2 text-muted-foreground/60 dark:text-muted-foreground/40 hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8"+ >+ <MoreHorizontal size={12} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-40">+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="text-xs gap-2 rounded-lg px-2.5 py-1.5 cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5">+ <FolderOpen+ size={12}+ className="text-muted-foreground/80 dark:text-muted-foreground/60"+ />+ {t("notes.context.moveToFolder")}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={4}+ className="min-w-36 rounded-xl border border-border p-1"+ >+ {folders.length > 5 && (+ <>+ <div className="relative px-2 py-1.5">+ <Search+ size={9}+ className="absolute left-4 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"+ />+ <input+ value={folderSearch}+ onChange={(e) => setFolderSearch(e.target.value)}+ onKeyDown={(e) => e.stopPropagation()}+ placeholder={t("notes.context.searchFolders")}+ style={{ background: "none" }}+ className="w-full pl-5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"+ />+ </div>+ <DropdownMenuSeparator />+ </>+ )}+ <div className="overflow-y-auto max-h-40">+ {filteredFolders.map((folder) => {+ const isCurrent = folder.id === currentFolderId;+ return (+ <DropdownMenuItem+ key={folder.id}+ disabled={isCurrent}+ onClick={(e) => {+ e.stopPropagation();+ onMoveToFolder(note.id, folder.id);+ }}+ className="text-xs gap-2 rounded-md px-2 py-1"+ >+ <span className="truncate flex-1">{folder.name}</span>+ {isCurrent && <Check size={9} className="text-primary shrink-0" />}+ </DropdownMenuItem>+ );+ })}+ {folderSearch && filteredFolders.length === 0 && (+ <p className="text-xs text-foreground/20 text-center py-1.5">+ {t("notes.context.noResults")}+ </p>+ )}+ </div>+ <DropdownMenuSeparator />+ {isCreating ? (+ <div className="px-2 py-1">+ <input+ autoFocus+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter" && newFolderName.trim()) {+ onCreateFolderAndMove(note.id, newFolderName.trim());+ setNewFolderName("");+ setIsCreating(false);+ }+ if (e.key === "Escape") {+ setIsCreating(false);+ setNewFolderName("");+ }+ }}+ placeholder={t("notes.folders.folderName")}+ className="w-full bg-transparent text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"+ />+ </div>+ ) : (+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ setIsCreating(true);+ }}+ className="text-xs gap-2 rounded-md px-2 py-1 text-foreground/40"+ >+ <Plus size={10} />+ {t("notes.context.newFolder")}+ </DropdownMenuItem>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onDelete(note.id);+ }}+ className="text-xs gap-2 rounded-lg px-2.5 py-1.5 text-destructive focus:text-destructive focus:bg-destructive/10"+ >+ <Trash2 size={12} />+ {t("notes.context.delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ {preview && (+ <p className="text-xs text-muted-foreground/80 dark:text-muted-foreground/40 line-clamp-1 mt-0.5">+ {preview}+ </p>+ )}+ </div>+ </button>+ );+}diff --git a/src/components/notes/NotesOnboarding.tsx b/src/components/notes/NotesOnboarding.tsxnew file mode 100644index 000000000..8ddae3c0f--- /dev/null+++ b/src/components/notes/NotesOnboarding.tsx@@ -0,0 +1,327 @@+import { useState, useEffect } from "react";+import { useTranslation } from "react-i18next";+import { Sparkles, Plus, ChevronRight, Zap, Loader2, Check } from "lucide-react";+import { Button } from "../ui/button";+import { cn } from "../lib/utils";+import { useSettingsStore } from "../../stores/settingsStore";+import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";+import {+ useActions,+ initializeActions,+ getActionName,+ getActionDescription,+} from "../../stores/actionStore";+import { notesInputClass } from "./shared";+import { useDialogs } from "../../hooks/useDialogs";+import { AlertDialog } from "../ui/dialog";+import ReasoningModelSelector from "../ReasoningModelSelector";++interface NotesOnboardingProps {+ onComplete: () => void;+}++export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {+ const { t } = useTranslation();+ const { isProUser, isProLoading, isLLMConfigured, complete } = useNotesOnboarding();+ const actions = useActions();+ const [llmExpanded, setLlmExpanded] = useState(!isLLMConfigured && !isProUser);+ const [createExpanded, setCreateExpanded] = useState(false);+ const [actionName, setActionName] = useState("");+ const [actionDescription, setActionDescription] = useState("");+ const [actionPrompt, setActionPrompt] = useState("");+ const [isSaving, setIsSaving] = useState(false);+ const [justCreated, setJustCreated] = useState(false);++ const reasoningModel = useSettingsStore((s) => s.reasoningModel);+ const setReasoningModel = useSettingsStore((s) => s.setReasoningModel);+ const reasoningProvider = useSettingsStore((s) => s.reasoningProvider);+ const setReasoningProvider = useSettingsStore((s) => s.setReasoningProvider);+ const cloudReasoningBaseUrl = useSettingsStore((s) => s.cloudReasoningBaseUrl);+ const setCloudReasoningBaseUrl = useSettingsStore((s) => s.setCloudReasoningBaseUrl);+ const openaiApiKey = useSettingsStore((s) => s.openaiApiKey);+ const setOpenaiApiKey = useSettingsStore((s) => s.setOpenaiApiKey);+ const anthropicApiKey = useSettingsStore((s) => s.anthropicApiKey);+ const setAnthropicApiKey = useSettingsStore((s) => s.setAnthropicApiKey);+ const geminiApiKey = useSettingsStore((s) => s.geminiApiKey);+ const setGeminiApiKey = useSettingsStore((s) => s.setGeminiApiKey);+ const groqApiKey = useSettingsStore((s) => s.groqApiKey);+ const setGroqApiKey = useSettingsStore((s) => s.setGroqApiKey);+ const customReasoningApiKey = useSettingsStore((s) => s.customReasoningApiKey);+ const setCustomReasoningApiKey = useSettingsStore((s) => s.setCustomReasoningApiKey);++ const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();++ useEffect(() => {+ initializeActions();+ }, []);++ const handleCreateAction = async () => {+ if (!actionName.trim() || !actionPrompt.trim()) return;+ setIsSaving(true);+ try {+ await window.electronAPI.createAction(+ actionName.trim(),+ actionDescription.trim(),+ actionPrompt.trim()+ );+ setActionName("");+ setActionDescription("");+ setActionPrompt("");+ setJustCreated(true);+ setTimeout(() => setJustCreated(false), 2000);+ } finally {+ setIsSaving(false);+ }+ };++ const handleComplete = () => {+ complete();+ onComplete();+ };++ const builtInAction = actions.find((a) => a.is_builtin === 1);+ const customActions = actions.filter((a) => a.is_builtin !== 1);++ return (+ <div className="flex flex-col items-center h-full overflow-y-auto px-6 py-6">+ <div+ className="w-full max-w-[420px] space-y-5 my-auto"+ style={{ animation: "float-up 0.4s ease-out" }}+ >+ <div className="flex flex-col items-center text-center">+ <div className="w-10 h-10 rounded-[10px] bg-gradient-to-b from-accent/10 to-accent/[0.03] dark:from-accent/15 dark:to-accent/5 border border-accent/15 dark:border-accent/20 flex items-center justify-center mb-3">+ <Sparkles size={17} strokeWidth={1.5} className="text-accent/60" />+ </div>+ <h2 className="text-sm font-semibold text-foreground mb-1">+ {t("notes.onboarding.actions.title")}+ </h2>+ <p className="text-xs text-foreground/35 leading-relaxed max-w-[320px]">+ {t("notes.onboarding.actions.description")}+ </p>+ </div>++ {/* LLM Configuration — non-Pro only, deferred until pro status is known */}+ {!isProLoading && !isProUser && (+ <div+ className={cn(+ "rounded-lg border transition-colors duration-200",+ isLLMConfigured+ ? "border-success/20 bg-success/[0.03]"+ : "border-foreground/8 dark:border-white/6 bg-surface-1/30 dark:bg-white/[0.02]"+ )}+ >+ <button+ type="button"+ onClick={() => setLlmExpanded(!llmExpanded)}+ aria-expanded={llmExpanded}+ className="flex items-center justify-between w-full px-4 py-3 text-left"+ >+ <div className="flex items-center gap-2.5">+ <Zap+ size={13}+ className={cn(isLLMConfigured ? "text-success/60" : "text-foreground/30")}+ />+ <span className="text-xs font-medium text-foreground/70">+ {t("notes.onboarding.llm.title")}+ </span>+ {isLLMConfigured && (+ <span className="text-xs text-success/60 font-medium">+ {t("notes.onboarding.llm.configured")}+ </span>+ )}+ </div>+ <ChevronRight+ size={12}+ className={cn(+ "text-foreground/20 transition-transform duration-200",+ llmExpanded && "rotate-90"+ )}+ />+ </button>++ {llmExpanded && (+ <div className="px-4 pb-4 space-y-3" style={{ animation: "float-up 0.2s ease-out" }}>+ <p className="text-xs text-foreground/30 leading-relaxed">+ {t("notes.onboarding.llm.description")}+ </p>++ <ReasoningModelSelector+ reasoningModel={reasoningModel}+ setReasoningModel={setReasoningModel}+ localReasoningProvider={reasoningProvider}+ setLocalReasoningProvider={setReasoningProvider}+ cloudReasoningBaseUrl={cloudReasoningBaseUrl}+ setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ anthropicApiKey={anthropicApiKey}+ setAnthropicApiKey={setAnthropicApiKey}+ geminiApiKey={geminiApiKey}+ setGeminiApiKey={setGeminiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ customReasoningApiKey={customReasoningApiKey}+ setCustomReasoningApiKey={setCustomReasoningApiKey}+ showAlertDialog={showAlertDialog}+ />+ </div>+ )}+ </div>+ )}++ {/* Built-in action */}+ <div>+ <div className="flex items-center gap-2 mb-2">+ <span className="text-xs font-medium text-foreground/50">+ {t("notes.onboarding.actions.builtInLabel")}+ </span>+ </div>+ {builtInAction && (+ <div className="flex items-center gap-3 px-3 py-2.5 rounded-lg border border-foreground/6 dark:border-white/6 bg-surface-1/20 dark:bg-white/[0.02]">+ <div className="w-7 h-7 rounded-md bg-accent/8 dark:bg-accent/12 border border-accent/10 dark:border-accent/15 flex items-center justify-center shrink-0">+ <Sparkles size={12} className="text-accent/60" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground/70 truncate">+ {getActionName(builtInAction, t)}+ </p>+ <p className="text-xs text-foreground/25 truncate">+ {getActionDescription(builtInAction, t)}+ </p>+ </div>+ <span className="text-xs text-foreground/15 font-medium shrink-0">+ {t("notes.actions.builtIn")}+ </span>+ </div>+ )}++ {/* Show any custom actions the user just created */}+ {customActions.length > 0 && (+ <div className="mt-1.5 space-y-1.5">+ {customActions.map((action) => (+ <div+ key={action.id}+ className="flex items-center gap-3 px-3 py-2.5 rounded-lg border border-success/20 bg-success/[0.03]"+ >+ <div className="w-7 h-7 rounded-md bg-success/8 border border-success/15 dark:border-success/20 flex items-center justify-center shrink-0">+ <Check size={12} className="text-success/60" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground/70 truncate">{action.name}</p>+ {action.description && (+ <p className="text-xs text-foreground/25 truncate">{action.description}</p>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Create custom action */}+ <div+ className={cn(+ "rounded-lg border transition-colors duration-200",+ "border-foreground/8 dark:border-white/6 bg-surface-1/30 dark:bg-white/[0.02]"+ )}+ >+ <button+ type="button"+ onClick={() => setCreateExpanded(!createExpanded)}+ aria-expanded={createExpanded}+ className="flex items-center justify-between w-full px-4 py-3 text-left"+ >+ <div className="flex items-center gap-2.5">+ <Plus size={13} className="text-foreground/30" />+ <span className="text-xs font-medium text-foreground/70">+ {t("notes.onboarding.actions.createTitle")}+ </span>+ {justCreated && (+ <span className="text-xs text-success/60 font-medium">+ {t("notes.onboarding.actions.created")}+ </span>+ )}+ </div>+ <ChevronRight+ size={12}+ className={cn(+ "text-foreground/20 transition-transform duration-200",+ createExpanded && "rotate-90"+ )}+ />+ </button>++ {createExpanded && (+ <div className="px-4 pb-4 space-y-2" style={{ animation: "float-up 0.2s ease-out" }}>+ <p className="text-xs text-foreground/30 leading-relaxed">+ {t("notes.onboarding.actions.createDescription")}+ </p>+ <input+ type="text"+ value={actionName}+ onChange={(e) => setActionName(e.target.value)}+ placeholder={t("notes.actions.namePlaceholder")}+ aria-label={t("notes.actions.namePlaceholder")}+ disabled={isSaving}+ className={cn(notesInputClass, "disabled:opacity-40")}+ />+ <input+ type="text"+ value={actionDescription}+ onChange={(e) => setActionDescription(e.target.value)}+ placeholder={t("notes.actions.descriptionPlaceholder")}+ aria-label={t("notes.actions.descriptionPlaceholder")}+ disabled={isSaving}+ className={cn(notesInputClass, "disabled:opacity-40")}+ />+ <textarea+ value={actionPrompt}+ onChange={(e) => setActionPrompt(e.target.value)}+ placeholder={t("notes.actions.promptPlaceholder")}+ aria-label={t("notes.actions.promptPlaceholder")}+ rows={3}+ disabled={isSaving}+ className={cn(+ "w-full px-3 py-2 rounded-md text-xs leading-relaxed resize-none",+ "bg-foreground/3 dark:bg-white/4 border border-border/30 dark:border-white/6",+ "text-foreground/80 placeholder:text-foreground/20 outline-none",+ "focus:border-primary/30 transition-colors duration-150",+ "disabled:opacity-40"+ )}+ />+ <div className="flex justify-end">+ <Button+ variant="default"+ size="sm"+ onClick={handleCreateAction}+ disabled={isSaving || !actionName.trim() || !actionPrompt.trim()}+ className="h-7 text-xs"+ >+ {isSaving ? (+ <Loader2 size={12} className="animate-spin" />+ ) : (+ t("notes.actions.save")+ )}+ </Button>+ </div>+ </div>+ )}+ </div>++ <div className="flex justify-center pt-1 pb-4">+ <Button variant="default" size="sm" onClick={handleComplete} className="h-8 text-xs px-8">+ {t("notes.onboarding.getStarted")}+ </Button>+ </div>+ </div>++ <AlertDialog+ open={alertDialog.open}+ onOpenChange={(open) => !open && hideAlertDialog()}+ title={alertDialog.title}+ description={alertDialog.description}+ onOk={hideAlertDialog}+ />+ </div>+ );+}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxnew file mode 100644index 000000000..ce71d36a3--- /dev/null+++ b/src/components/notes/PersonalNotesView.tsx@@ -0,0 +1,926 @@+import { useState, useEffect, useRef, useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { Plus, Loader2, FolderOpen, MoreHorizontal, Pencil, Trash2, Check } from "lucide-react";+import { Button } from "../ui/button";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { useToast } from "../ui/Toast";+import NoteListItem from "./NoteListItem";+import NoteEditor from "./NoteEditor";+import ActionPicker from "./ActionPicker";+import ActionManagerDialog from "./ActionManagerDialog";+import AddNotesToFolderDialog from "./AddNotesToFolderDialog";+import { useNoteRecording } from "../../hooks/useNoteRecording";+import { useActionProcessing } from "../../hooks/useActionProcessing";+import {+ useSettingsStore,+ selectEffectiveReasoningModel,+ selectIsCloudReasoningMode,+} from "../../stores/settingsStore";+import { useFolderManagement } from "../../hooks/useFolderManagement";+import { useNoteDragAndDrop } from "../../hooks/useNoteDragAndDrop";+import { cn } from "../lib/utils";+import {+ useNotes,+ useActiveNoteId,+ useActiveFolderId,+ initializeNotes,+ setActiveNoteId,+ setActiveFolderId,+} from "../../stores/noteStore";+import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";+import NotesOnboarding from "./NotesOnboarding";+import RealtimeTranscriptionBanner from "./RealtimeTranscriptionBanner";++const FOLDER_INPUT_CLASS =+ "w-full h-6 bg-foreground/5 dark:bg-white/5 rounded px-2 text-xs text-foreground outline-none border border-primary/30 focus:border-primary/50";++interface PersonalNotesViewProps {+ onOpenSettings?: (section: string) => void;+}++export default function PersonalNotesView({ onOpenSettings }: PersonalNotesViewProps) {+ const { t } = useTranslation();+ const notes = useNotes();+ const activeNoteId = useActiveNoteId();+ const activeFolderId = useActiveFolderId();+ const [isSaving, setIsSaving] = useState(false);+ const [localTitle, setLocalTitle] = useState("");+ const [localContent, setLocalContent] = useState("");+ const [localEnhancedContent, setLocalEnhancedContent] = useState<string | null>(null);+ const [finalTranscript, setFinalTranscript] = useState<string | null>(null);+ const [showActionManager, setShowActionManager] = useState(false);+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const enhancedSaveTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const activeNoteRef = useRef<number | null>(null);+ const localContentRef = useRef(localContent);+ localContentRef.current = localContent;+ const localTitleRef = useRef(localTitle);+ localTitleRef.current = localTitle;+ const { toast } = useToast();+ const isCloudMode = useSettingsStore(selectIsCloudReasoningMode);+ const effectiveModelId = useSettingsStore(selectEffectiveReasoningModel);+ const {+ isComplete: isOnboardingComplete,+ isProUser,+ isProLoading,+ complete: completeOnboarding,+ } = useNotesOnboarding();++ const {+ folders,+ folderCounts,+ isLoading,+ isCreatingFolder,+ newFolderName,+ renamingFolderId,+ renameValue,+ showAddNotesDialog,+ newFolderInputRef,+ renameInputRef,+ setIsCreatingFolder,+ setNewFolderName,+ setRenamingFolderId,+ setRenameValue,+ setShowAddNotesDialog,+ loadFolders,+ handleCreateFolder,+ handleConfirmRename,+ handleDeleteFolder,+ } = useFolderManagement();++ const activeNote = notes.find((n) => n.id === activeNoteId) ?? null;+ const isMeetingsFolder = useMemo(+ () => folders.find((f) => f.id === activeFolderId)?.name === "Meetings",+ [folders, activeFolderId]+ );++ const {+ isRecording,+ isProcessing,+ partialTranscript,+ streamingCommit,+ consumeStreamingCommit,+ startRecording,+ stopRecording,+ } = useNoteRecording({+ onTranscriptionComplete: useCallback((text: string) => {+ setFinalTranscript(text);+ }, []),+ onError: useCallback(+ (error: { title: string; description: string }) => {+ toast({ title: error.title, description: error.description, variant: "destructive" });+ },+ [toast]+ ),+ });++ useEffect(() => {+ if (activeNote && activeNote.id !== activeNoteRef.current) {+ activeNoteRef.current = activeNote.id;+ setLocalTitle(activeNote.title);+ setLocalContent(activeNote.content);+ setLocalEnhancedContent(activeNote.enhanced_content ?? null);+ }+ if (!activeNote) {+ activeNoteRef.current = null;+ }+ }, [activeNote]);++ const debouncedSave = useCallback((noteId: number, title: string, content: string) => {+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);+ saveTimeoutRef.current = setTimeout(async () => {+ setIsSaving(true);+ try {+ await window.electronAPI.updateNote(noteId, { title, content });+ } finally {+ setIsSaving(false);+ }+ }, 1000);+ }, []);++ useEffect(() => {+ return () => {+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);+ if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);+ };+ }, []);++ const handleTitleChange = useCallback(+ (title: string) => {+ setLocalTitle(title);+ if (activeNoteId) debouncedSave(activeNoteId, title, localContent);+ },+ [activeNoteId, localContent, debouncedSave]+ );++ const handleContentChange = useCallback(+ (content: string) => {+ setLocalContent(content);+ if (activeNoteId) debouncedSave(activeNoteId, localTitle, content);+ },+ [activeNoteId, localTitle, debouncedSave]+ );++ const handleEnhancedContentChange = useCallback(+ (content: string) => {+ setLocalEnhancedContent(content);+ if (!activeNoteId) return;+ if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);+ enhancedSaveTimeoutRef.current = setTimeout(async () => {+ setIsSaving(true);+ try {+ await window.electronAPI.updateNote(activeNoteId, { enhanced_content: content });+ } finally {+ setIsSaving(false);+ }+ }, 1000);+ },+ [activeNoteId]+ );++ const handleNewNote = useCallback(async () => {+ if (!activeFolderId || isMeetingsFolder) return;+ const result = await window.electronAPI.saveNote(+ t("notes.list.untitledNote"),+ "",+ "personal",+ null,+ null,+ activeFolderId+ );+ if (result.success && result.note) {+ setActiveNoteId(result.note.id);+ loadFolders();+ }+ }, [activeFolderId, isMeetingsFolder, loadFolders]);++ const handleNotesAdded = useCallback(async () => {+ if (activeFolderId) {+ await initializeNotes(null, 50, activeFolderId);+ }+ loadFolders();+ }, [activeFolderId, loadFolders]);++ const handleDelete = useCallback(+ async (id: number) => {+ await window.electronAPI.deleteNote(id);+ if (activeNoteId === id) {+ const remaining = notes.filter((n) => n.id !== id);+ setActiveNoteId(remaining.length > 0 ? remaining[0].id : null);+ }+ loadFolders();+ },+ [activeNoteId, notes, loadFolders]+ );++ const handleMoveToFolder = useCallback(+ async (noteId: number, folderId: number) => {+ await window.electronAPI.updateNote(noteId, { folder_id: folderId });+ if (activeFolderId) await initializeNotes(null, 50, activeFolderId);+ loadFolders();+ },+ [activeFolderId, loadFolders]+ );++ const { dragState, noteDragHandlers, folderDropHandlers } = useNoteDragAndDrop({+ onMoveToFolder: handleMoveToFolder,+ currentFolderId: activeFolderId,+ });++ const handleCreateFolderAndMove = useCallback(+ async (noteId: number, folderName: string) => {+ const result = await window.electronAPI.createFolder(folderName);+ if (result.success && result.folder) {+ await window.electronAPI.updateNote(noteId, { folder_id: result.folder.id });+ if (activeFolderId) await initializeNotes(null, 50, activeFolderId);+ await loadFolders();+ } else if (result.error) {+ toast({+ title: t("notes.folders.couldNotCreate"),+ description: result.error,+ variant: "destructive",+ });+ }+ },+ [activeFolderId, loadFolders, toast, t]+ );++ const handleApplyEnhancement = useCallback(+ async (enhancedContent: string, prompt: string) => {+ if (!activeNoteId) return;+ setLocalEnhancedContent(enhancedContent);+ const hash =+ String(localContentRef.current.length) + "-" + localContentRef.current.slice(0, 50);+ setIsSaving(true);+ try {+ await window.electronAPI.updateNote(activeNoteId, {+ enhanced_content: enhancedContent,+ enhancement_prompt: prompt,+ enhanced_at_content_hash: hash,+ });+ } finally {+ setIsSaving(false);+ }+ },+ [activeNoteId]+ );++ const {+ state: actionProcessingState,+ actionName,+ runAction,+ cancel: cancelAction,+ } = useActionProcessing({+ onSuccess: useCallback(+ (enhancedContent: string, prompt: string) => {+ handleApplyEnhancement(enhancedContent, prompt);+ },+ [handleApplyEnhancement]+ ),+ onError: useCallback(+ (errorMessage: string) => {+ toast({+ title: t("notes.enhance.title"),+ description: errorMessage,+ variant: "destructive",+ });+ },+ [toast, t]+ ),+ });++ useEffect(() => {+ return () => cancelAction();+ }, [activeNoteId, cancelAction]);++ const isEnhancementStale = useMemo(() => {+ if (!activeNote?.enhanced_content || !activeNote?.enhanced_at_content_hash) return false;+ const currentHash = String(localContent.length) + "-" + localContent.slice(0, 50);+ return currentHash !== activeNote.enhanced_at_content_hash;+ }, [activeNote?.enhanced_content, activeNote?.enhanced_at_content_hash, localContent]);++ const handleExportNote = useCallback(+ async (format: "md" | "txt") => {+ if (!activeNoteId) return;+ await window.electronAPI.exportNote(activeNoteId, format);+ },+ [activeNoteId]+ );++ const editorNote = activeNote+ ? { ...activeNote, title: localTitle, content: localContent }+ : null;++ if (!isOnboardingComplete) {+ return <NotesOnboarding onComplete={completeOnboarding} />;+ }++ return (+ <div className="flex h-full">+ <div className="w-52 shrink-0 border-r border-border/15 dark:border-white/4 flex flex-col">+ {/* Folders */}+ <div className="flex items-center justify-between px-3 py-2">+ <span className="text-xs font-medium uppercase tracking-wider text-foreground/50 dark:text-foreground/25">+ {t("notes.folders.title")}+ </span>+ <Button+ variant="ghost"+ size="icon"+ onClick={() => setIsCreatingFolder(true)}+ aria-label={t("notes.context.newFolder")}+ className="h-5 w-5 rounded-md text-muted-foreground/50 dark:text-muted-foreground/30 hover:text-foreground/60 hover:bg-foreground/5"+ >+ <Plus size={13} />+ </Button>+ </div>++ <div className="px-1.5 space-y-px">+ {folders.map((folder) => {+ const isActive = folder.id === activeFolderId;+ const isMeetings = folder.name === "Meetings";+ const count = folderCounts[folder.id] || 0;+ const isRenaming = renamingFolderId === folder.id;++ if (isRenaming) {+ return (+ <div key={folder.id} className="px-2">+ <input+ ref={renameInputRef}+ value={renameValue}+ onChange={(e) => setRenameValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleConfirmRename();+ if (e.key === "Escape") {+ setRenamingFolderId(null);+ setRenameValue("");+ }+ }}+ onBlur={handleConfirmRename}+ className={FOLDER_INPUT_CLASS}+ />+ </div>+ );+ }++ const isDragOver = dragState.dragOverFolderId === folder.id;+ const isDropSuccess = dragState.dropSuccessFolderId === folder.id;++ return (+ <button+ key={folder.id}+ onClick={() => setActiveFolderId(folder.id)}+ {...folderDropHandlers(folder.id, folder.name)}+ className={cn(+ "group relative flex items-center gap-2 w-full h-7 px-2 rounded-md cursor-pointer text-left transition-all duration-150",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",+ isActive+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4",+ isDragOver &&+ !isMeetings &&+ "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25 scale-[1.02]",+ isDropSuccess &&+ "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20"+ )}+ >+ {isActive && !isDragOver && !isDropSuccess && (+ <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-3 rounded-r-full bg-primary" />+ )}+ <FolderOpen+ size={13}+ className={cn(+ "shrink-0 transition-colors duration-150",+ isDragOver || isActive+ ? "text-primary"+ : "text-foreground/35 dark:text-foreground/20 group-hover:text-foreground/50 dark:group-hover:text-foreground/35"+ )}+ />+ <span+ className={cn(+ "text-xs truncate flex-1 transition-colors duration-150",+ isDragOver || isActive+ ? "text-foreground font-medium"+ : "text-foreground/50 group-hover:text-foreground/70"+ )}+ >+ {folder.name}+ </span>++ {isMeetings ? (+ <span className="text-[7px] font-semibold uppercase tracking-wider text-foreground/20 bg-foreground/4 dark:bg-white/6 px-1.5 py-px rounded shrink-0">+ {t("notes.folders.soon")}+ </span>+ ) : (+ <>+ {isDropSuccess ? (+ <Check+ size={10}+ className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"+ />+ ) : (+ <span+ className={cn(+ "text-xs tabular-nums shrink-0 transition-colors group-hover:opacity-0",+ isActive+ ? "text-foreground/50 dark:text-foreground/30"+ : "text-foreground/35 dark:text-foreground/15"+ )}+ >+ {count > 0 ? count : ""}+ </span>+ )}+ {!folder.is_default && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <span+ role="button"+ tabIndex={-1}+ onClick={(e) => e.stopPropagation()}+ className="h-4 w-4 flex items-center justify-center rounded-sm opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity absolute right-1.5 text-foreground/25 hover:text-foreground/50 cursor-pointer"+ >+ <MoreHorizontal size={11} />+ </span>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-32">+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ setRenamingFolderId(folder.id);+ setRenameValue(folder.name);+ }}+ className="text-xs gap-2 rounded-md px-2 py-1"+ >+ <Pencil size={11} className="text-muted-foreground/60" />+ {t("notes.context.rename")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ handleDeleteFolder(folder.id);+ }}+ className="text-xs gap-2 rounded-md px-2 py-1 text-destructive focus:text-destructive focus:bg-destructive/10"+ >+ <Trash2 size={11} />+ {t("notes.context.delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </>+ )}+ </button>+ );+ })}++ {isCreatingFolder && (+ <div className="px-2">+ <input+ ref={newFolderInputRef}+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleCreateFolder();+ if (e.key === "Escape") {+ setIsCreatingFolder(false);+ setNewFolderName("");+ }+ }}+ onBlur={handleCreateFolder}+ placeholder={t("notes.folders.folderName")}+ className={cn(FOLDER_INPUT_CLASS, "placeholder:text-foreground/20")}+ />+ </div>+ )}+ </div>++ <div className="mx-3 h-px bg-border/10 dark:bg-white/4 my-2" />++ {/* Notes list */}+ {!isMeetingsFolder && (+ <>+ <div className="flex items-center justify-between px-3 py-1">+ <span className="text-xs font-medium uppercase tracking-wider text-foreground/50 dark:text-foreground/25">+ {t("notes.list.title")}+ </span>+ <Button+ variant="ghost"+ size="icon"+ onClick={handleNewNote}+ aria-label={t("notes.list.newNote")}+ className="h-5 w-5 rounded-md text-muted-foreground/50 dark:text-muted-foreground/30 hover:text-foreground/60 hover:bg-foreground/5"+ >+ <Plus size={13} />+ </Button>+ </div>++ <div className="flex-1 overflow-y-auto">+ {isLoading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 size={12} className="animate-spin text-foreground/15" />+ </div>+ ) : notes.length === 0 ? (+ <div className="flex flex-col items-center justify-center py-8 px-4">+ <svg+ className="text-foreground dark:text-white mb-3"+ width="40"+ height="36"+ viewBox="0 0 40 36"+ fill="none"+ >+ <rect+ x="12"+ y="1"+ width="20"+ height="26"+ rx="2"+ transform="rotate(5 22 14)"+ fill="currentColor"+ fillOpacity={0.025}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <rect+ x="8"+ y="3"+ width="20"+ height="26"+ rx="2"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.08}+ />+ <rect+ x="12"+ y="9"+ width="10"+ height="1.5"+ rx="0.75"+ fill="currentColor"+ fillOpacity={0.07}+ />+ <rect+ x="12"+ y="13"+ width="12"+ height="1.5"+ rx="0.75"+ fill="currentColor"+ fillOpacity={0.05}+ />+ <rect+ x="12"+ y="17"+ width="8"+ height="1.5"+ rx="0.75"+ fill="currentColor"+ fillOpacity={0.04}+ />+ </svg>+ <p className="text-xs text-foreground/50 dark:text-foreground/25 mb-3">+ {t("notes.empty.emptyFolder")}+ </p>+ <div className="flex flex-col gap-1.5 w-full max-w-36">+ <button+ onClick={handleNewNote}+ className="flex items-center justify-center gap-1.5 h-6 rounded-md bg-primary/8 dark:bg-primary/10 border border-primary/12 dark:border-primary/15 text-xs font-medium text-primary/70 hover:bg-primary/12 hover:text-primary hover:border-primary/20 transition-colors"+ >+ <Plus size={10} />+ {t("notes.empty.createNote")}+ </button>+ <button+ onClick={() => setShowAddNotesDialog(true)}+ className="flex items-center justify-center gap-1.5 h-6 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"+ >+ {t("notes.addToFolder.addExisting")}+ </button>+ </div>+ </div>+ ) : (+ notes.map((note) => (+ <NoteListItem+ key={note.id}+ note={note}+ isActive={note.id === activeNoteId}+ onClick={() => setActiveNoteId(note.id)}+ onDelete={handleDelete}+ folders={folders}+ currentFolderId={activeFolderId}+ onMoveToFolder={handleMoveToFolder}+ onCreateFolderAndMove={handleCreateFolderAndMove}+ dragHandlers={noteDragHandlers(note.id, note.title)}+ isDragging={dragState.draggingNoteId === note.id}+ />+ ))+ )}+ </div>+ </>+ )}++ {isMeetingsFolder && <div className="flex-1" />}+ </div>++ <div className="flex-1 flex flex-col min-w-0 min-h-0">+ {!isProLoading && !isProUser && (+ <RealtimeTranscriptionBanner+ onUpgrade={onOpenSettings ? () => onOpenSettings("plansBilling") : undefined}+ />+ )}+ {isMeetingsFolder ? (+ <div className="flex flex-col items-center justify-center h-full -mt-6">+ <svg+ className="text-foreground dark:text-white mb-5"+ width="72"+ height="56"+ viewBox="0 0 72 56"+ fill="none"+ >+ <ellipse cx="36" cy="48" rx="24" ry="2" fill="currentColor" fillOpacity={0.03} />+ <circle+ cx="24"+ cy="20"+ r="7"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.08}+ />+ <path+ d="M13 40c0-6 5-11 11-11s11 5 11 11"+ fill="currentColor"+ fillOpacity={0.03}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <circle+ cx="48"+ cy="20"+ r="7"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.08}+ />+ <path+ d="M37 40c0-6 5-11 11-11s11 5 11 11"+ fill="currentColor"+ fillOpacity={0.03}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <rect+ x="16"+ y="6"+ width="14"+ height="8"+ rx="3"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.07}+ />+ <rect+ x="18.5"+ y="8.5"+ width="5"+ height="1"+ rx="0.5"+ fill="currentColor"+ fillOpacity={0.06}+ />+ <rect+ x="18.5"+ y="11"+ width="8"+ height="1"+ rx="0.5"+ fill="currentColor"+ fillOpacity={0.04}+ />+ <rect+ x="44"+ y="9"+ width="12"+ height="7"+ rx="2.5"+ fill="currentColor"+ fillOpacity={0.03}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <rect+ x="46.5"+ y="11.5"+ width="4"+ height="1"+ rx="0.5"+ fill="currentColor"+ fillOpacity={0.05}+ />+ </svg>+ <h3 className="text-xs font-semibold text-foreground/60 mb-1">+ {t("notes.meeting.title")}+ </h3>+ <p className="text-xs text-foreground/50 dark:text-foreground/25 text-center max-w-52 mb-3">+ {t("notes.meeting.description")}+ </p>+ <span className="text-[8px] font-semibold uppercase tracking-widest text-primary/40 bg-primary/5 dark:bg-primary/8 px-2.5 py-1 rounded-md border border-primary/8 dark:border-primary/12">+ {t("notes.meeting.comingSoon")}+ </span>+ </div>+ ) : editorNote ? (+ <>+ <NoteEditor+ note={editorNote}+ onTitleChange={handleTitleChange}+ onContentChange={handleContentChange}+ isSaving={isSaving}+ isRecording={isRecording}+ isProcessing={isProcessing}+ partialTranscript={partialTranscript}+ finalTranscript={finalTranscript}+ onFinalTranscriptConsumed={() => setFinalTranscript(null)}+ streamingCommit={streamingCommit}+ onStreamingCommitConsumed={consumeStreamingCommit}+ onStartRecording={startRecording}+ onStopRecording={stopRecording}+ onExportNote={handleExportNote}+ enhancement={+ localEnhancedContent+ ? {+ content: localEnhancedContent,+ isStale: isEnhancementStale,+ onChange: handleEnhancedContentChange,+ }+ : undefined+ }+ actionProcessingState={actionProcessingState}+ actionName={actionName}+ actionPicker={+ <ActionPicker+ onRunAction={(action) => {+ if (!localContent.trim()) return;+ runAction(action, localContent, { isCloudMode, modelId: effectiveModelId });+ }}+ onManageActions={() => setShowActionManager(true)}+ disabled={!localContent.trim() || actionProcessingState === "processing"}+ />+ }+ />+ <ActionManagerDialog open={showActionManager} onOpenChange={setShowActionManager} />+ </>+ ) : (+ <div className="flex-1 flex flex-col items-center justify-center -mt-6">+ <svg+ className="text-foreground dark:text-white mb-5"+ width="72"+ height="64"+ viewBox="0 0 72 64"+ fill="none"+ >+ <rect+ x="22"+ y="2"+ width="32"+ height="42"+ rx="3"+ transform="rotate(6 38 23)"+ fill="currentColor"+ fillOpacity={0.025}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <rect+ x="18"+ y="5"+ width="32"+ height="42"+ rx="3"+ transform="rotate(3 34 26)"+ fill="currentColor"+ fillOpacity={0.04}+ stroke="currentColor"+ strokeOpacity={0.08}+ />+ <rect+ x="14"+ y="8"+ width="32"+ height="42"+ rx="3"+ fill="currentColor"+ fillOpacity={0.05}+ stroke="currentColor"+ strokeOpacity={0.1}+ />+ <rect+ x="20"+ y="16"+ width="16"+ height="2"+ rx="1"+ fill="currentColor"+ fillOpacity={0.08}+ />+ <rect+ x="20"+ y="21"+ width="20"+ height="2"+ rx="1"+ fill="currentColor"+ fillOpacity={0.06}+ />+ <rect+ x="20"+ y="26"+ width="12"+ height="2"+ rx="1"+ fill="currentColor"+ fillOpacity={0.05}+ />+ <rect+ x="20"+ y="31"+ width="18"+ height="2"+ rx="1"+ fill="currentColor"+ fillOpacity={0.04}+ />+ <circle+ cx="54"+ cy="50"+ r="5"+ fill="currentColor"+ fillOpacity={0.03}+ stroke="currentColor"+ strokeOpacity={0.06}+ />+ <path+ d="M51.5 50L53 51.5L56.5 48"+ stroke="currentColor"+ strokeOpacity={0.12}+ strokeWidth={1.2}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ {notes.length === 0 ? (+ <>+ <h3 className="text-xs font-semibold text-foreground/60 mb-1">+ {t("notes.empty.title")}+ </h3>+ <p className="text-xs text-foreground/50 dark:text-foreground/25 text-center max-w-55 mb-4">+ {t("notes.empty.description")}+ </p>+ <div className="flex items-center gap-2">+ <button+ onClick={handleNewNote}+ className="flex items-center gap-1.5 px-4 h-7 rounded-md bg-primary/8 dark:bg-primary/10 border border-primary/12 dark:border-primary/15 text-xs font-medium text-primary/70 hover:bg-primary/12 hover:text-primary hover:border-primary/20 transition-colors"+ >+ <Plus size={11} />+ {t("notes.empty.createNote")}+ </button>+ <button+ onClick={() => setShowAddNotesDialog(true)}+ className="flex items-center gap-1.5 px-4 h-7 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"+ >+ {t("notes.addToFolder.addExisting")}+ </button>+ </div>+ </>+ ) : (+ <>+ <h3 className="text-xs font-semibold text-foreground/60 mb-1">+ {t("notes.empty.selectTitle")}+ </h3>+ <p className="text-xs text-foreground/50 dark:text-foreground/25 text-center max-w-50">+ {t("notes.empty.selectDescription")}+ </p>+ </>+ )}+ </div>+ )}+ </div>++ {activeFolderId && (+ <AddNotesToFolderDialog+ open={showAddNotesDialog}+ onOpenChange={setShowAddNotesDialog}+ targetFolderId={activeFolderId}+ onNotesAdded={handleNotesAdded}+ />+ )}+ </div>+ );+}diff --git a/src/components/notes/RealtimeTranscriptionBanner.tsx b/src/components/notes/RealtimeTranscriptionBanner.tsxnew file mode 100644index 000000000..f4565e8c5--- /dev/null+++ b/src/components/notes/RealtimeTranscriptionBanner.tsx@@ -0,0 +1,53 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Zap, X } from "lucide-react";+import { cn } from "../lib/utils";++interface RealtimeTranscriptionBannerProps {+ onUpgrade?: () => void;+}++export default function RealtimeTranscriptionBanner({+ onUpgrade,+}: RealtimeTranscriptionBannerProps) {+ const { t } = useTranslation();+ const [dismissed, setDismissed] = useState(+ () => localStorage.getItem("realtimeProBannerDismissed") === "true"+ );++ if (dismissed) return null;++ const handleDismiss = () => {+ localStorage.setItem("realtimeProBannerDismissed", "true");+ setDismissed(true);+ };++ return (+ <div+ className={cn(+ "flex items-center gap-2 px-3 h-8 shrink-0",+ "backdrop-blur-xl bg-primary/[0.03] dark:bg-primary/[0.06]",+ "border-b border-primary/10 dark:border-primary/15",+ "animate-in slide-in-from-top-2 duration-300"+ )}+ >+ <Zap size={11} className="text-primary/40 shrink-0" />+ <p className="text-xs text-primary/40 flex-1 truncate">{t("notes.realtimeBanner.message")}</p>+ {onUpgrade && (+ <button+ onClick={onUpgrade}+ className="text-xs font-medium text-primary/50 hover:text-primary/70 transition-colors shrink-0"+ >+ {t("notes.realtimeBanner.upgrade")}+ </button>+ )}+ <button+ onClick={handleDismiss}+ className="p-0.5 rounded text-primary/25 hover:text-primary/50 transition-colors shrink-0"+ aria-label={t("common.dismiss")}+ >+ <X size={11} />+ </button>+ </div>+ );+}diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxnew file mode 100644index 000000000..09e493fb9--- /dev/null+++ b/src/components/notes/UploadAudioView.tsx@@ -0,0 +1,1039 @@+import React, { useState, useRef, useEffect, Suspense } from "react";+import { useTranslation } from "react-i18next";+import {+ Upload,+ FileAudio,+ X,+ AlertCircle,+ Cloud,+ ChevronRight,+ Key,+ FolderOpen,+ Plus,+ Settings,+} from "lucide-react";+import { Button } from "../ui/button";+import { cn } from "../lib/utils";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+} from "../ui/select";+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "../ui/dialog";+import { Input } from "../ui/input";+import type { FolderItem } from "../../types/electron";+import { useAuth } from "../../hooks/useAuth";+import { useUsage } from "../../hooks/useUsage";+import { useSettings } from "../../hooks/useSettings";+import { withSessionRefresh } from "../../lib/neonAuth";+import reasoningService from "../../services/ReasoningService";+import { getAllReasoningModels } from "../../models/ModelRegistry";+import { useSettingsStore, selectEffectiveReasoningModel } from "../../stores/settingsStore";++const TranscriptionModelPicker = React.lazy(() => import("../TranscriptionModelPicker"));++type UploadState = "idle" | "selected" | "transcribing" | "complete" | "error";++const SUPPORTED_EXTENSIONS = ["mp3", "wav", "m4a", "webm", "ogg", "flac", "aac"];++const TITLE_SYSTEM_PROMPT =+ "Generate a concise 3-8 word title for these transcribed notes. Return ONLY the title text, nothing else — no quotes, no prefix, no explanation.";++function formatFileSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++interface UploadAudioViewProps {+ onNoteCreated?: (noteId: number, folderId: number | null) => void;+ onOpenSettings?: (section: string) => void;+}++export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploadAudioViewProps) {+ const { t } = useTranslation();+ const [state, setState] = useState<UploadState>("idle");+ const [file, setFile] = useState<{ name: string; path: string; size: string } | null>(null);+ const [result, setResult] = useState<string | null>(null);+ const [noteId, setNoteId] = useState<number | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [isDragOver, setIsDragOver] = useState(false);+ const [progress, setProgress] = useState(0);+ const progressRef = useRef<ReturnType<typeof setInterval> | null>(null);++ const [folders, setFolders] = useState<FolderItem[]>([]);+ const [selectedFolderId, setSelectedFolderId] = useState<string>("");+ const [showNewFolderDialog, setShowNewFolderDialog] = useState(false);+ const [newFolderName, setNewFolderName] = useState("");++ const [setupDismissed, setSetupDismissed] = useState(+ () =>+ localStorage.getItem("uploadSetupComplete") === "true" ||+ localStorage.getItem("notesOnboardingComplete") === "true"+ );+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const [providerReady, setProviderReady] = useState<boolean | null>(null);++ const { isSignedIn } = useAuth();+ const usage = useUsage();+ const isProUser = usage?.isSubscribed || usage?.isTrial;++ const {+ useLocalWhisper,+ setUseLocalWhisper,+ whisperModel,+ setWhisperModel,+ localTranscriptionProvider,+ setLocalTranscriptionProvider,+ parakeetModel,+ setParakeetModel,+ cloudTranscriptionProvider,+ setCloudTranscriptionProvider,+ cloudTranscriptionModel,+ setCloudTranscriptionModel,+ cloudTranscriptionBaseUrl,+ setCloudTranscriptionBaseUrl,+ cloudTranscriptionMode,+ setCloudTranscriptionMode,+ openaiApiKey,+ setOpenaiApiKey,+ groqApiKey,+ setGroqApiKey,+ mistralApiKey,+ setMistralApiKey,+ customTranscriptionApiKey,+ setCustomTranscriptionApiKey,+ updateTranscriptionSettings,+ } = useSettings();++ const effectiveReasoningModel = useSettingsStore(selectEffectiveReasoningModel);+ const useReasoningModel = useSettingsStore((s) => s.useReasoningModel);++ const isOpenWhisprCloud =+ isSignedIn && cloudTranscriptionMode === "openwhispr" && !useLocalWhisper;+ const usageLoaded = usage?.hasLoaded ?? false;+ const showSetup = usageLoaded && !isProUser && !setupDismissed && state === "idle";+ const showModelPicker = !isSignedIn || cloudTranscriptionMode === "byok" || useLocalWhisper;+ const shouldCenter = !showSetup && !advancedOpen;++ useEffect(() => {+ return () => {+ if (progressRef.current) clearInterval(progressRef.current);+ };+ }, []);++ useEffect(() => {+ window.electronAPI.getFolders?.().then((f) => {+ setFolders(f);+ const personal = f.find((x) => x.name === "Personal" && x.is_default);+ if (personal) setSelectedFolderId(String(personal.id));+ });+ }, []);++ useEffect(() => {+ let cancelled = false;+ const checkProviderReady = async () => {+ if (isOpenWhisprCloud) {+ setProviderReady(true);+ return;+ }+ if (!useLocalWhisper) {+ const key =+ cloudTranscriptionProvider === "openai"+ ? openaiApiKey+ : cloudTranscriptionProvider === "groq"+ ? groqApiKey+ : cloudTranscriptionProvider === "mistral"+ ? mistralApiKey+ : customTranscriptionApiKey;+ if (!cancelled) setProviderReady(!!key);+ return;+ }+ if (localTranscriptionProvider === "nvidia") {+ const r = await window.electronAPI.listParakeetModels?.();+ if (!cancelled)+ setProviderReady(+ !!(r?.success && r.models.some((m: { downloaded?: boolean }) => m.downloaded))+ );+ } else {+ const r = await window.electronAPI.listWhisperModels?.();+ if (!cancelled)+ setProviderReady(+ !!(r?.success && r.models.some((m: { downloaded?: boolean }) => m.downloaded))+ );+ }+ };+ checkProviderReady();+ return () => {+ cancelled = true;+ };+ }, [+ isOpenWhisprCloud,+ useLocalWhisper,+ localTranscriptionProvider,+ cloudTranscriptionProvider,+ openaiApiKey,+ groqApiKey,+ mistralApiKey,+ customTranscriptionApiKey,+ ]);++ const getActiveModelLabel = (): string => {+ if (isOpenWhisprCloud) return t("notes.upload.openwhisprCloud");+ if (useLocalWhisper) {+ if (localTranscriptionProvider === "nvidia")+ return `Parakeet · ${parakeetModel || "default"}`;+ return `Whisper · ${whisperModel || "base"}`;+ }+ const name =+ cloudTranscriptionProvider === "custom"+ ? t("notes.upload.custom")+ : cloudTranscriptionProvider.charAt(0).toUpperCase() + cloudTranscriptionProvider.slice(1);+ return `${name} · ${cloudTranscriptionModel}`;+ };++ const getActiveApiKey = (): string => {+ switch (cloudTranscriptionProvider) {+ case "openai":+ return openaiApiKey;+ case "groq":+ return groqApiKey;+ case "mistral":+ return mistralApiKey;+ case "custom":+ return customTranscriptionApiKey || "";+ default:+ return "";+ }+ };++ const generateTitle = async (text: string): Promise<string> => {+ if (!useReasoningModel) return "";+ const model = effectiveReasoningModel || getAllReasoningModels()[0]?.value;+ if (!model) return "";+ try {+ const title = await reasoningService.processText(text.slice(0, 2000), model, null, {+ systemPrompt: TITLE_SYSTEM_PROMPT,+ temperature: 0.3,+ });+ const cleaned = title.trim().replace(/^["']|["']$/g, "");+ return cleaned.length > 0 && cleaned.length < 100 ? cleaned : "";+ } catch {+ return "";+ }+ };++ const handleBrowse = async () => {+ const res = await window.electronAPI.selectAudioFile();+ if (!res.canceled && res.filePath) {+ const name = res.filePath.split(/[/\\]/).pop() || "audio";+ setFile({ name, path: res.filePath, size: "" });+ setState("selected");+ setError(null);+ }+ };++ const handleDrop = (e: React.DragEvent) => {+ e.preventDefault();+ setIsDragOver(false);+ const f = e.dataTransfer.files[0];+ if (!f) return;+ const ext = f.name.split(".").pop()?.toLowerCase() || "";+ if (SUPPORTED_EXTENSIONS.includes(ext)) {+ const filePath = window.electronAPI.getPathForFile(f);+ if (!filePath) return;+ setFile({ name: f.name, path: filePath, size: formatFileSize(f.size) });+ setState("selected");+ setError(null);+ }+ };++ const reset = () => {+ if (progressRef.current) clearInterval(progressRef.current);+ setState("idle");+ setFile(null);+ setResult(null);+ setNoteId(null);+ setError(null);+ setProgress(0);+ const personal = folders.find((f) => f.name === "Personal" && f.is_default);+ if (personal) setSelectedFolderId(String(personal.id));+ };++ const handleTranscribe = async () => {+ if (!file) return;+ setState("transcribing");+ setError(null);+ setProgress(0);++ progressRef.current = setInterval(() => {+ setProgress((prev) => {+ if (prev >= 90) {+ if (progressRef.current) clearInterval(progressRef.current);+ return prev;+ }+ return prev + Math.random() * 6;+ });+ }, 500);++ try {+ let res: { success: boolean; text?: string; error?: string; code?: string };++ if (isOpenWhisprCloud) {+ res = await withSessionRefresh(async () => {+ const r = await window.electronAPI.transcribeAudioFileCloud!(file.path);+ if (!r.success && r.code) {+ const err = new Error(r.error || "Cloud transcription failed");+ (err as any).code = r.code;+ throw err;+ }+ return r;+ });+ } else if (useLocalWhisper) {+ res = await window.electronAPI.transcribeAudioFile(file.path, {+ provider: localTranscriptionProvider as "whisper" | "nvidia",+ model: localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel,+ });+ } else {+ res = await window.electronAPI.transcribeAudioFileByok!({+ filePath: file.path,+ apiKey: getActiveApiKey(),+ baseUrl: cloudTranscriptionBaseUrl || "",+ model: cloudTranscriptionModel,+ });+ }++ if (progressRef.current) clearInterval(progressRef.current);++ if (res.success && res.text) {+ setProgress(100);+ setResult(res.text);++ const textFallback = res.text.trim().split(/\s+/).slice(0, 6).join(" ");+ const fallbackTitle =+ textFallback.length > 0+ ? textFallback + (res.text.trim().split(/\s+/).length > 6 ? "..." : "")+ : file.name.replace(/\.[^.]+$/, "");+ const aiTitle = await generateTitle(res.text);+ const title = aiTitle || fallbackTitle;++ const folderId = selectedFolderId ? Number(selectedFolderId) : null;+ const noteRes = await window.electronAPI.saveNote(+ title,+ res.text,+ "upload",+ file.name,+ null,+ folderId+ );+ if (noteRes.success && noteRes.note) setNoteId(noteRes.note.id);+ setState("complete");+ } else {+ setProgress(0);+ setError(res.error || t("notes.upload.transcriptionFailed"));+ setState("error");+ }+ } catch (err) {+ if (progressRef.current) clearInterval(progressRef.current);+ setProgress(0);+ setError(err instanceof Error ? err.message : t("notes.upload.errorOccurred"));+ setState("error");+ }+ };++ const dismissSetup = () => {+ localStorage.setItem("uploadSetupComplete", "true");+ setSetupDismissed(true);+ };++ const handleCreateFolder = async () => {+ const trimmed = newFolderName.trim();+ if (!trimmed) return;+ const res = await window.electronAPI.createFolder(trimmed);+ if (res.success && res.folder) {+ setFolders((prev) => [...prev, res.folder!]);+ const newId = String(res.folder.id);+ setSelectedFolderId(newId);+ if (noteId != null) {+ window.electronAPI.updateNote(noteId, { folder_id: res.folder.id });+ }+ }+ setNewFolderName("");+ setShowNewFolderDialog(false);+ };++ const handleFolderChange = (val: string) => {+ if (val === "__create_new__") {+ setShowNewFolderDialog(true);+ return;+ }+ setSelectedFolderId(val);+ if (noteId != null) {+ window.electronAPI.updateNote(noteId, { folder_id: Number(val) });+ }+ };++ const getTranscribingLabel = (): string => {+ if (isOpenWhisprCloud) return t("notes.upload.transcribingCloud");+ if (useLocalWhisper) return t("notes.upload.transcribingLocal");+ return t("notes.upload.transcribingProvider", { provider: cloudTranscriptionProvider });+ };++ const modeSelector = isSignedIn ? (+ <div className="flex items-center rounded-md border border-foreground/6 dark:border-white/6 bg-surface-1/30 dark:bg-white/[0.02] p-0.5 mb-3">+ <button+ onClick={() => {+ setCloudTranscriptionMode("openwhispr");+ setUseLocalWhisper(false);+ updateTranscriptionSettings({ useLocalWhisper: false });+ }}+ className={cn(+ "flex-1 flex items-center justify-center gap-1.5 h-7 rounded text-xs font-medium transition-colors duration-150",+ isOpenWhisprCloud+ ? "bg-foreground/[0.06] dark:bg-white/8 text-foreground/70"+ : "text-foreground/30 hover:text-foreground/50"+ )}+ >+ <Cloud size={11} />+ {t("notes.upload.openwhisprCloud")}+ </button>+ <button+ onClick={() => setCloudTranscriptionMode("byok")}+ className={cn(+ "flex-1 flex items-center justify-center gap-1.5 h-7 rounded text-xs font-medium transition-colors duration-150",+ !isOpenWhisprCloud+ ? "bg-foreground/[0.06] dark:bg-white/8 text-foreground/70"+ : "text-foreground/30 hover:text-foreground/50"+ )}+ >+ <Key size={11} />+ {t("notes.upload.custom")}+ </button>+ </div>+ ) : null;++ const modelPicker = showModelPicker ? (+ <Suspense fallback={null}>+ <TranscriptionModelPicker+ selectedCloudProvider={cloudTranscriptionProvider}+ onCloudProviderSelect={setCloudTranscriptionProvider}+ selectedCloudModel={cloudTranscriptionModel}+ onCloudModelSelect={setCloudTranscriptionModel}+ selectedLocalModel={localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel}+ onLocalModelSelect={(modelId) => {+ if (localTranscriptionProvider === "nvidia") {+ setParakeetModel(modelId);+ } else {+ setWhisperModel(modelId);+ }+ }}+ selectedLocalProvider={localTranscriptionProvider}+ onLocalProviderSelect={(id) => setLocalTranscriptionProvider(id as "whisper" | "nvidia")}+ useLocalWhisper={useLocalWhisper}+ onModeChange={(isLocal) => {+ setUseLocalWhisper(isLocal);+ updateTranscriptionSettings({ useLocalWhisper: isLocal });+ if (isLocal) setCloudTranscriptionMode("byok");+ }}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ mistralApiKey={mistralApiKey}+ setMistralApiKey={setMistralApiKey}+ customTranscriptionApiKey={customTranscriptionApiKey}+ setCustomTranscriptionApiKey={setCustomTranscriptionApiKey}+ cloudTranscriptionBaseUrl={cloudTranscriptionBaseUrl}+ setCloudTranscriptionBaseUrl={setCloudTranscriptionBaseUrl}+ variant="settings"+ />+ </Suspense>+ ) : null;++ return (+ <div className="flex flex-col items-center h-full overflow-y-auto px-6">+ <div+ className={cn("w-full max-w-md shrink-0", shouldCenter ? "my-auto" : "pt-4 pb-8")}+ style={{ animation: "float-up 0.4s ease-out" }}+ >+ {showSetup && (+ <div className="mb-6" style={{ animation: "float-up 0.3s ease-out" }}>+ <div className="flex flex-col items-center mb-5">+ <div className="w-10 h-10 rounded-[10px] bg-gradient-to-b from-primary/10 to-primary/[0.03] dark:from-primary/15 dark:to-primary/5 border border-primary/15 dark:border-primary/20 flex items-center justify-center mb-3">+ <Upload size={17} strokeWidth={1.5} className="text-primary/50" />+ </div>+ <h2 className="text-xs font-semibold text-foreground mb-1">+ {t("notes.upload.setupTitle")}+ </h2>+ <p className="text-xs text-foreground/30 text-center leading-relaxed max-w-[280px]">+ {t("notes.upload.setupDescription")}+ </p>+ </div>++ {modeSelector}+ {modelPicker}++ <div className="flex justify-center mt-4">+ <Button+ variant="default"+ size="sm"+ onClick={dismissSetup}+ className="h-8 text-xs px-6"+ >+ {t("notes.upload.continue")}+ </Button>+ </div>++ <div className="h-px bg-foreground/5 dark:bg-white/5 my-5" />+ </div>+ )}++ <div className="max-w-[320px] mx-auto">+ {state === "idle" && providerReady === false && (+ <NoProviderView t={t} onOpenSettings={() => onOpenSettings?.("transcription")} />+ )}++ {state === "idle" && providerReady !== false && (+ <IdleView+ t={t}+ getActiveModelLabel={getActiveModelLabel}+ handleDrop={handleDrop}+ handleBrowse={handleBrowse}+ isDragOver={isDragOver}+ setIsDragOver={setIsDragOver}+ />+ )}++ {state === "selected" && file && (+ <SelectedView+ t={t}+ file={file}+ getActiveModelLabel={getActiveModelLabel}+ reset={reset}+ handleTranscribe={handleTranscribe}+ />+ )}++ {state === "transcribing" && (+ <TranscribingView+ t={t}+ progress={progress}+ getTranscribingLabel={getTranscribingLabel}+ file={file}+ />+ )}++ {state === "complete" && result && (+ <CompleteView+ t={t}+ result={result}+ folders={folders}+ selectedFolderId={selectedFolderId}+ handleFolderChange={handleFolderChange}+ noteId={noteId}+ onNoteCreated={onNoteCreated}+ reset={reset}+ />+ )}++ {state === "error" && error && (+ <ErrorView t={t} error={error} reset={reset} handleTranscribe={handleTranscribe} />+ )}+ </div>++ {!showSetup && (state === "idle" || state === "selected") && (+ <div className="mx-auto mt-5" style={{ maxWidth: advancedOpen ? "448px" : "320px" }}>+ <button+ onClick={() => setAdvancedOpen(!advancedOpen)}+ className="flex items-center gap-1.5 text-xs text-foreground/25 hover:text-foreground/40 transition-colors mx-auto"+ >+ <ChevronRight+ size={10}+ className={cn("transition-transform duration-200", advancedOpen && "rotate-90")}+ />+ {t("notes.upload.transcriptionSettings")}+ </button>++ {advancedOpen && (+ <div className="mt-3" style={{ animation: "float-up 0.2s ease-out" }}>+ {modeSelector}+ {modelPicker}+ </div>+ )}+ </div>+ )}+ </div>++ <Dialog open={showNewFolderDialog} onOpenChange={setShowNewFolderDialog}>+ <DialogContent className="sm:max-w-[320px] p-5 gap-3">+ <DialogHeader>+ <DialogTitle className="text-sm">{t("notes.upload.newFolder")}</DialogTitle>+ </DialogHeader>+ <Input+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ placeholder={t("notes.upload.folderName")}+ className="h-8 text-xs"+ autoFocus+ onKeyDown={(e) => {+ if (e.key === "Enter") handleCreateFolder();+ }}+ />+ <DialogFooter className="gap-1.5">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ setShowNewFolderDialog(false);+ setNewFolderName("");+ }}+ className="h-7 text-xs"+ >+ {t("notes.upload.cancel")}+ </Button>+ <Button+ variant="default"+ size="sm"+ onClick={handleCreateFolder}+ disabled={!newFolderName.trim()}+ className="h-7 text-xs"+ >+ {t("notes.upload.create")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}++/* -------------------------------------------------------------------------- */+/* Private sub-components — one per upload state variant */+/* -------------------------------------------------------------------------- */++interface NoProviderViewProps {+ t: (key: string, options?: Record<string, unknown>) => string;+ onOpenSettings: () => void;+}++function NoProviderView({ t, onOpenSettings }: NoProviderViewProps) {+ return (+ <div+ className="flex flex-col items-center gap-4 py-2"+ style={{ animation: "float-up 0.4s ease-out" }}+ >+ <div className="w-10 h-10 rounded-[10px] bg-linear-to-b from-foreground/5 to-foreground/2 dark:from-white/8 dark:to-white/3 border border-foreground/8 dark:border-white/8 flex items-center justify-center">+ <Settings+ size={17}+ strokeWidth={1.5}+ className="text-foreground/25 dark:text-foreground/35"+ />+ </div>+ <div className="text-center">+ <h2 className="text-xs font-semibold text-foreground mb-1">+ {t("notes.upload.noProviderTitle")}+ </h2>+ <p className="text-xs text-foreground/30 leading-relaxed max-w-60">+ {t("notes.upload.noProviderDescription")}+ </p>+ </div>+ <Button variant="default" size="sm" className="h-7 text-xs px-4" onClick={onOpenSettings}>+ {t("notes.upload.noProviderAction")}+ </Button>+ </div>+ );+}++interface IdleViewProps {+ t: (key: string, options?: Record<string, unknown>) => string;+ getActiveModelLabel: () => string;+ handleDrop: (e: React.DragEvent) => void;+ handleBrowse: () => void;+ isDragOver: boolean;+ setIsDragOver: (v: boolean) => void;+}++function IdleView({+ t,+ getActiveModelLabel,+ handleDrop,+ handleBrowse,+ isDragOver,+ setIsDragOver,+}: IdleViewProps) {+ const fileInputRef = useRef<HTMLInputElement>(null);++ const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const f = e.target.files?.[0];+ if (!f) return;+ // Delegate to handleBrowse which uses Electron's file dialog;+ // the hidden input is for keyboard-triggered file selection only.+ handleBrowse();+ // Reset input so the same file can be re-selected+ if (fileInputRef.current) fileInputRef.current.value = "";+ };++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ handleBrowse();+ }+ };++ return (+ <>+ <div className="flex flex-col items-center mb-5">+ <div className="w-10 h-10 rounded-[10px] bg-gradient-to-b from-foreground/5 to-foreground/[0.02] dark:from-white/8 dark:to-white/3 border border-foreground/8 dark:border-white/8 flex items-center justify-center mb-4">+ <Upload+ size={17}+ strokeWidth={1.5}+ className="text-foreground/25 dark:text-foreground/35"+ />+ </div>+ <h2 className="text-xs font-semibold text-foreground mb-1">{t("notes.upload.title")}</h2>+ <p className="text-xs text-foreground/25">+ {t("notes.upload.using", { model: getActiveModelLabel() })}+ </p>+ </div>++ <input+ ref={fileInputRef}+ type="file"+ accept=".mp3,.wav,.m4a,.webm,.ogg,.flac,.aac"+ onChange={handleFileInputChange}+ className="sr-only"+ tabIndex={-1}+ aria-hidden="true"+ />++ <div+ role="button"+ tabIndex={0}+ aria-label={t("notes.upload.dropOrBrowse")}+ onDrop={handleDrop}+ onDragOver={(e) => {+ e.preventDefault();+ setIsDragOver(true);+ }}+ onDragLeave={(e) => {+ e.preventDefault();+ setIsDragOver(false);+ }}+ onClick={handleBrowse}+ onKeyDown={handleKeyDown}+ className={cn(+ "relative rounded-lg p-8 text-center cursor-pointer transition-[background-color,border-color,transform] duration-300 group",+ "bg-surface-1/40 dark:bg-white/[0.03] backdrop-blur-sm",+ "border border-foreground/6 dark:border-white/6",+ "hover:bg-surface-1/60 dark:hover:bg-white/[0.05] hover:border-foreground/12 dark:hover:border-white/10",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",+ isDragOver && "border-primary/30 bg-primary/[0.04] dark:bg-primary/[0.06] scale-[1.01]"+ )}+ style={isDragOver ? { animation: "drag-pulse 1.5s ease-in-out infinite" } : undefined}+ >+ <div className="absolute inset-0 rounded-lg overflow-hidden pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-500">+ <div+ className="absolute inset-0 bg-gradient-to-r from-transparent via-foreground/[0.02] dark:via-white/[0.03] to-transparent"+ style={{ animation: "shimmer-slide 3s ease-in-out infinite" }}+ />+ </div>++ {!isDragOver ? (+ <div className="flex flex-col items-center gap-2 relative">+ <div className="w-8 h-8 rounded-full bg-foreground/[0.03] dark:bg-white/[0.04] flex items-center justify-center mb-1">+ <Upload+ size={14}+ className="text-foreground/20 dark:text-foreground/30 group-hover:text-foreground/40 transition-colors"+ />+ </div>+ <p className="text-xs text-foreground/35 group-hover:text-foreground/50 transition-colors">+ {t("notes.upload.dropOrBrowse")}+ </p>+ <p className="text-xs text-foreground/15 tracking-wide">+ {t("notes.upload.supportedFormats")}+ </p>+ </div>+ ) : (+ <div className="flex flex-col items-center gap-2 relative">+ <Upload size={18} className="text-primary/60" />+ <p className="text-xs text-primary/60 font-medium">{t("notes.upload.dropToUpload")}</p>+ </div>+ )}+ </div>+ </>+ );+}++interface SelectedViewProps {+ t: (key: string) => string;+ file: { name: string; path: string; size: string };+ getActiveModelLabel: () => string;+ reset: () => void;+ handleTranscribe: () => void;+}++function SelectedView({+ t,+ file,+ getActiveModelLabel,+ reset,+ handleTranscribe,+}: SelectedViewProps) {+ return (+ <div style={{ animation: "float-up 0.3s ease-out" }}>+ <div className="rounded-lg border border-foreground/8 dark:border-white/6 bg-surface-1/40 dark:bg-white/[0.03] backdrop-blur-sm p-4 mb-3">+ <div className="flex items-center gap-3">+ <div className="w-9 h-9 rounded-[8px] bg-primary/8 dark:bg-primary/12 border border-primary/10 dark:border-primary/15 flex items-center justify-center shrink-0">+ <FileAudio size={15} className="text-primary/60" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-xs text-foreground/70 truncate font-medium">{file.name}</p>+ {file.size && <p className="text-xs text-foreground/25 mt-0.5">{file.size}</p>}+ <p className="text-xs text-foreground/20 mt-0.5">{getActiveModelLabel()}</p>+ </div>+ <button+ onClick={reset}+ className="text-foreground/15 hover:text-foreground/40 transition-colors p-1 rounded"+ >+ <X size={12} />+ </button>+ </div>+ </div>++ <div className="flex items-center gap-2 justify-center">+ <Button variant="default" size="sm" onClick={handleTranscribe} className="h-8 text-xs px-5">+ {t("notes.upload.transcribe")}+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={reset}+ className="h-8 text-xs text-foreground/35"+ >+ {t("notes.upload.cancel")}+ </Button>+ </div>+ </div>+ );+}++interface TranscribingViewProps {+ t: (key: string) => string;+ progress: number;+ getTranscribingLabel: () => string;+ file: { name: string; path: string; size: string } | null;+}++function TranscribingView({ t, progress, getTranscribingLabel, file }: TranscribingViewProps) {+ return (+ <div className="flex flex-col items-center" style={{ animation: "float-up 0.3s ease-out" }}>+ <div className="flex items-end justify-center gap-[3px] h-10 mb-5">+ {[0, 1, 2, 3, 4, 5, 6].map((i) => (+ <div+ key={i}+ className="w-[3px] rounded-full bg-primary/40 dark:bg-primary/50 origin-bottom"+ style={{+ height: "100%",+ animation: `waveform-bar ${0.8 + i * 0.12}s ease-in-out infinite`,+ animationDelay: `${i * 0.08}s`,+ }}+ />+ ))}+ </div>++ <div className="w-full max-w-[200px] h-[3px] rounded-full bg-foreground/5 dark:bg-white/5 overflow-hidden mb-3">+ <div+ className="h-full rounded-full bg-primary/50 transition-[width] duration-500 ease-out"+ style={{ width: `${Math.min(progress, 100)}%` }}+ />+ </div>++ <p className="text-xs text-foreground/50 font-medium">{getTranscribingLabel()}</p>+ {file && (+ <p className="text-xs text-foreground/20 mt-1 truncate max-w-[200px]">{file.name}</p>+ )}+ </div>+ );+}++interface CompleteViewProps {+ t: (key: string) => string;+ result: string;+ folders: FolderItem[];+ selectedFolderId: string;+ handleFolderChange: (val: string) => void;+ noteId: number | null;+ onNoteCreated?: (noteId: number, folderId: number | null) => void;+ reset: () => void;+}++function CompleteView({+ t,+ result,+ folders,+ selectedFolderId,+ handleFolderChange,+ noteId,+ onNoteCreated,+ reset,+}: CompleteViewProps) {+ return (+ <div className="flex flex-col items-center" style={{ animation: "float-up 0.3s ease-out" }}>+ <div className="relative w-12 h-12 mb-4">+ <svg className="w-12 h-12 -rotate-90" viewBox="0 0 36 36">+ <circle+ cx="18"+ cy="18"+ r="15"+ fill="none"+ strokeWidth="1.5"+ className="stroke-success/15"+ />+ <circle+ cx="18"+ cy="18"+ r="15"+ fill="none"+ strokeWidth="1.5"+ className="stroke-success/60"+ strokeDasharray="94.25"+ strokeLinecap="round"+ style={{ animation: "ring-fill 0.8s ease-out forwards" }}+ />+ </svg>+ <div className="absolute inset-0 flex items-center justify-center">+ <svg className="w-5 h-5 text-success/70" viewBox="0 0 24 24" fill="none">+ <path+ d="M5 13l4 4L19 7"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeDasharray="24"+ strokeDashoffset="24"+ style={{ animation: "draw-check 0.4s ease-out 0.5s forwards" }}+ />+ </svg>+ </div>+ </div>++ <p className="text-xs text-foreground/60 font-medium mb-1">+ {t("notes.upload.transcriptionComplete")}+ </p>+ <p className="text-xs text-foreground/25 max-w-[240px] text-center line-clamp-2 mb-4">+ {result.slice(0, 150)}+ </p>++ {folders.length > 0 && (+ <div className="flex items-center justify-center gap-2 mb-4">+ <FolderOpen size={12} className="text-foreground/20 shrink-0" />+ <Select value={selectedFolderId} onValueChange={handleFolderChange}>+ <SelectTrigger className="h-7 w-44 text-xs rounded-lg px-2.5 [&>svg]:h-3 [&>svg]:w-3">+ <SelectValue placeholder={t("notes.upload.selectFolder")} />+ </SelectTrigger>+ <SelectContent>+ {folders.map((f) => {+ const isMeetings = f.name === "Meetings" && !!f.is_default;+ return (+ <SelectItem+ key={f.id}+ value={String(f.id)}+ disabled={isMeetings}+ className="text-xs py-1.5 pl-2.5 pr-7 rounded-md"+ >+ <span className="flex items-center gap-1.5">+ {f.name}+ {isMeetings && (+ <span className="text-[8px] uppercase tracking-wider text-foreground/25 font-medium">+ {t("notes.folders.soon")}+ </span>+ )}+ </span>+ </SelectItem>+ );+ })}+ <SelectSeparator />+ <SelectItem value="__create_new__" className="text-xs py-1.5 pl-2.5 pr-7 rounded-md">+ <span className="flex items-center gap-1.5 text-primary/60">+ <Plus size={11} />+ {t("notes.upload.newFolder")}+ </span>+ </SelectItem>+ </SelectContent>+ </Select>+ </div>+ )}++ <div className="flex items-center gap-2">+ {noteId != null && onNoteCreated && (+ <Button+ variant="default"+ size="sm"+ onClick={() =>+ onNoteCreated(noteId, selectedFolderId ? Number(selectedFolderId) : null)+ }+ className="h-8 text-xs"+ >+ {t("notes.upload.openNote")}+ </Button>+ )}+ <Button+ variant="ghost"+ size="sm"+ onClick={reset}+ className="h-8 text-xs text-foreground/35"+ >+ {t("notes.upload.uploadAnother")}+ </Button>+ </div>+ </div>+ );+}++interface ErrorViewProps {+ t: (key: string) => string;+ error: string;+ reset: () => void;+ handleTranscribe: () => void;+}++function ErrorView({ t, error, reset, handleTranscribe }: ErrorViewProps) {+ return (+ <div style={{ animation: "float-up 0.3s ease-out" }}>+ <div className="rounded-lg border border-destructive/15 dark:border-destructive/20 bg-destructive/[0.03] dark:bg-destructive/[0.05] backdrop-blur-sm p-4 mb-4">+ <div className="flex items-start gap-2.5">+ <AlertCircle size={14} className="text-destructive/50 shrink-0 mt-0.5" />+ <p className="flex-1 text-xs text-destructive/70 leading-relaxed">{error}</p>+ <button+ onClick={reset}+ className="text-foreground/15 hover:text-foreground/30 transition-colors shrink-0 p-0.5 rounded"+ >+ <X size={11} />+ </button>+ </div>+ </div>++ <div className="flex items-center gap-2 justify-center">+ <Button+ variant="ghost"+ size="sm"+ onClick={handleTranscribe}+ className="h-7 text-xs text-foreground/40"+ >+ {t("notes.upload.retry")}+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={reset}+ className="h-7 text-xs text-foreground/25"+ >+ {t("notes.upload.startOver")}+ </Button>+ </div>+ </div>+ );+}diff --git a/src/components/notes/shared.ts b/src/components/notes/shared.tsnew file mode 100644index 000000000..2fcfbc595--- /dev/null+++ b/src/components/notes/shared.ts@@ -0,0 +1,8 @@+import { cn } from "../lib/utils";++export const notesInputClass = cn(+ "w-full h-8 px-3 rounded-md text-xs",+ "bg-foreground/3 dark:bg-white/4 border border-border/30 dark:border-white/6",+ "text-foreground/80 placeholder:text-foreground/20 outline-none",+ "focus:border-primary/30 transition-colors duration-150"+);diff --git a/src/components/referral-cards/SpectrogramCard.tsx b/src/components/referral-cards/SpectrogramCard.tsxnew file mode 100644index 000000000..837c02008--- /dev/null+++ b/src/components/referral-cards/SpectrogramCard.tsx@@ -0,0 +1,245 @@+import { useState, useMemo, useRef, useEffect, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { cn } from "../lib/utils";+import { generateSpectrogramData } from "./generateWaveform";++interface SpectrogramCardProps {+ referralCode: string;+}++const COLS = 48;+const ROWS = 14;+const STEP = 9;+const CELL = 6;+const CELL_RADIUS = 1.2;+const SVG_W = COLS * STEP;+const SVG_H = ROWS * STEP;+const OFFSET = (STEP - CELL) / 2;+const DURATION = 2.5;++const NOISE_BG = `url("data:image/svg+xml,${encodeURIComponent(+ '<svg viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch"/></filter><rect width="100%" height="100%" filter="url(#n)" opacity="1"/></svg>'+)}")`;++const FREQ_MIN = 150;+const FREQ_MAX = 4000;+const FREQUENCIES = Array.from({ length: ROWS }, (_, i) => {+ const t = i / (ROWS - 1);+ return FREQ_MIN * Math.pow(FREQ_MAX / FREQ_MIN, t);+});++function spectrogramColor(value: number): string {+ if (value < 0.05) return "transparent";+ const a = (0.1 + value * 0.8).toFixed(3);+ return `oklch(0.72 0.22 260 / ${a})`;+}++function createAudio(data: number[][]): { stop: () => void } | null {+ try {+ const ctx = new AudioContext();+ ctx.resume().catch(() => {});++ const now = ctx.currentTime;+ const master = ctx.createGain();+ const lpf = ctx.createBiquadFilter();++ lpf.type = "lowpass";+ lpf.frequency.value = 3500;+ lpf.Q.value = 0.7;+ lpf.connect(master);+ master.connect(ctx.destination);++ master.gain.setValueAtTime(0, now);+ master.gain.linearRampToValueAtTime(0.15, now + 0.08);+ master.gain.setValueAtTime(0.15, now + DURATION - 0.15);+ master.gain.linearRampToValueAtTime(0, now + DURATION);++ const oscillators: OscillatorNode[] = [];++ for (let band = 0; band < ROWS; band++) {+ const osc = ctx.createOscillator();+ const bandGain = ctx.createGain();++ osc.type = "sine";+ osc.frequency.value = FREQUENCIES[band];+ osc.detune.value = (Math.random() - 0.5) * 4;++ const row = data[band];+ if (!row) continue;+ bandGain.gain.setValueAtTime(0, now);+ for (let col = 0; col < row.length; col++) {+ const t = now + (col / (row.length - 1)) * DURATION;+ const val = (row[col] ?? 0) * 0.08;+ if (Number.isFinite(t) && Number.isFinite(val)) {+ bandGain.gain.linearRampToValueAtTime(val, t);+ }+ }+ bandGain.gain.linearRampToValueAtTime(0, now + DURATION);++ osc.connect(bandGain);+ bandGain.connect(lpf);+ osc.start(now);+ osc.stop(now + DURATION);+ oscillators.push(osc);+ }++ return {+ stop() {+ oscillators.forEach((o) => {+ try {+ o.stop();+ } catch {+ /* already stopped */+ }+ });+ ctx.close().catch(() => {});+ },+ };+ } catch {+ return null;+ }+}++export function SpectrogramCard({ referralCode }: SpectrogramCardProps) {+ const { t } = useTranslation();+ const data = useMemo(() => generateSpectrogramData(referralCode, COLS, ROWS), [referralCode]);+ const [playing, setPlaying] = useState(false);+ const [playKey, setPlayKey] = useState(0);+ const audioRef = useRef<{ stop(): void } | null>(null);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const hasAutoPlayed = useRef(false);++ const resetPlayback = useCallback(() => {+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = null;+ audioRef.current?.stop();+ audioRef.current = null;+ setPlaying(false);+ }, []);++ const play = useCallback(() => {+ audioRef.current?.stop();+ if (timerRef.current) clearTimeout(timerRef.current);++ setPlaying(true);+ setPlayKey((k) => k + 1);+ audioRef.current = createAudio(data);++ // Safety net — animationend on scan line is the primary reset+ timerRef.current = setTimeout(resetPlayback, DURATION * 1000 + 500);+ }, [data, resetPlayback]);++ useEffect(() => {+ return () => {+ if (timerRef.current) clearTimeout(timerRef.current);+ audioRef.current?.stop();+ };+ }, []);++ useEffect(() => {+ if (hasAutoPlayed.current) return;+ hasAutoPlayed.current = true;+ const delay = setTimeout(() => play(), 200);+ return () => clearTimeout(delay);+ }, [play]);++ return (+ <div className="relative w-full h-55 rounded-lg border overflow-hidden bg-surface-1 border-border dark:border-foreground/6">+ {/* Noise texture */}+ <div+ className="absolute inset-0 rounded-lg opacity-[0.03] pointer-events-none mix-blend-overlay"+ style={{ backgroundImage: NOISE_BG, backgroundSize: "128px 128px" }}+ />++ {/* Brand + Signal ID */}+ <div className="absolute top-0 inset-x-0 px-5 pt-3.5 flex items-center justify-between z-10">+ <span className="text-xs font-medium uppercase tracking-[0.2em] text-foreground/20 select-none">+ {t("referral.card.brand")}+ </span>+ <div className="flex flex-col items-end">+ <span className="text-xs font-mono text-foreground/30 tracking-wider select-all">+ {referralCode}+ </span>+ <span className="text-[7px] uppercase tracking-[0.15em] text-foreground/12 select-none">+ {t("referral.card.signalId")}+ </span>+ </div>+ </div>++ {/* Spectrogram visualization */}+ <div className="absolute inset-x-5 top-11 bottom-17">+ <svg+ viewBox={`0 0 ${SVG_W} ${SVG_H}`}+ className="w-full h-full"+ preserveAspectRatio="none"+ aria-hidden+ >+ {data.map((row, y) =>+ row.map((value, x) =>+ value >= 0.05 ? (+ <rect+ key={`${x}-${y}`}+ x={x * STEP + OFFSET}+ y={y * STEP + OFFSET}+ width={CELL}+ height={CELL}+ rx={CELL_RADIUS}+ fill={spectrogramColor(value)}+ />+ ) : null+ )+ )}+ </svg>++ {/* Playback scan line — onAnimationEnd resets play state */}+ {playing && (+ <div+ key={playKey}+ className="spectrogram-play absolute top-0 bottom-0 w-px pointer-events-none z-10"+ onAnimationEnd={resetPlayback}+ style={{+ background: "oklch(0.72 0.22 260)",+ boxShadow:+ "0 0 10px 3px oklch(0.72 0.22 260 / 0.5), 0 0 24px 6px oklch(0.72 0.22 260 / 0.2)",+ animationDuration: `${DURATION}s`,+ }}+ />+ )}+ </div>++ {/* Bottom content */}+ <div className="absolute bottom-0 inset-x-0 px-5 pb-4 z-10">+ <div className="flex items-end justify-between">+ <div className="flex items-center gap-3">+ <button+ onClick={playing ? resetPlayback : play}+ className={cn(+ "w-8 h-8 rounded-full flex items-center justify-center transition-[background-color,color,transform] duration-200",+ "border border-foreground/10 active:scale-[0.93]",+ playing+ ? "bg-foreground/12 text-foreground/80"+ : "bg-foreground/6 text-foreground/40 hover:bg-foreground/10 hover:text-foreground/70"+ )}+ aria-label={playing ? t("referral.card.stop") : t("referral.card.playSignal")}+ >+ {playing ? (+ <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor">+ <rect x="1" y="1" width="8" height="8" rx="1" />+ </svg>+ ) : (+ <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor">+ <polygon points="2,0.5 9.5,5 2,9.5" />+ </svg>+ )}+ </button>+ <div>+ <span className="text-xs font-medium text-foreground/70 leading-tight block">+ {t("referral.card.audioSignature")}+ </span>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/referral-cards/generateWaveform.ts b/src/components/referral-cards/generateWaveform.tsnew file mode 100644index 000000000..8176c0f6d--- /dev/null+++ b/src/components/referral-cards/generateWaveform.ts@@ -0,0 +1,74 @@+/**+ * Generates a 2D spectrogram-like heatmap from a referral code.+ * Rows = frequency bands (low->high), Cols = time steps.+ * Each cell is a 0-1 intensity value.+ */+export function generateSpectrogramData(code: string, cols: number, rows: number): number[][] {+ let hash = 0;+ for (let i = 0; i < code.length; i++) {+ hash = ((hash << 5) - hash + code.charCodeAt(i)) | 0;+ }++ const seed = (offset: number) => {+ const h = ((hash + offset * 2654435761) | 0) >>> 0;+ return (h % 10000) / 10000;+ };++ // Formant peaks — horizontal bands of energy like speech+ const numFormants = 3 + Math.floor(seed(0) * 3);+ const formants = Array.from({ length: numFormants }, (_, f) => ({+ center: 1 + seed(f * 10 + 1) * (rows - 2),+ width: 0.8 + seed(f * 10 + 2) * 2,+ intensity: 0.3 + seed(f * 10 + 3) * 0.7,+ timeFreq: 0.5 + seed(f * 10 + 4) * 3,+ timePhase: seed(f * 10 + 5) * Math.PI * 2,+ }));++ // Time bursts — energy clusters like syllables+ const numBursts = 3 + Math.floor(seed(100) * 3);+ const bursts = Array.from({ length: numBursts }, (_, b) => ({+ center: 0.1 + seed(b * 5 + 101) * 0.8,+ width: 0.05 + seed(b * 5 + 102) * 0.15,+ intensity: 0.5 + seed(b * 5 + 103) * 0.5,+ }));++ const data: number[][] = [];+ for (let row = 0; row < rows; row++) {+ const rowData: number[] = [];+ for (let col = 0; col < cols; col++) {+ let value = 0;+ const t = col / (cols - 1);++ // Noise floor+ value += seed(row * cols + col + 500) * 0.08;++ // Burst envelope+ let burstEnv = 0.15;+ for (const burst of bursts) {+ const dist = Math.abs(t - burst.center);+ burstEnv += burst.intensity * Math.exp(-(dist * dist) / (2 * burst.width * burst.width));+ }+ burstEnv = Math.min(1, burstEnv);++ // Formant contributions+ for (const f of formants) {+ const freqDist = Math.abs(row - f.center);+ const gaussian = Math.exp(-(freqDist * freqDist) / (2 * f.width * f.width));+ const timeMod = 0.4 + 0.6 * Math.sin(t * Math.PI * f.timeFreq * 2 + f.timePhase);+ value += gaussian * f.intensity * timeMod * burstEnv;+ }++ // High frequency rolloff+ const freqRolloff = 1 - (row / rows) * 0.5;++ // Edge fade+ const edgeFade = Math.min(t * 8, (1 - t) * 8, 1);++ const raw = Math.min(1, value * freqRolloff * edgeFade);+ rowData.push(Math.pow(raw, 0.75)); // contrast boost — brightens midtones+ }+ data.push(rowData);+ }++ return data;+}diff --git a/src/components/ui/ActivationModeSelector.tsx b/src/components/ui/ActivationModeSelector.tsxindex 7da1e4aff..0f6ce3bc3 100644--- a/src/components/ui/ActivationModeSelector.tsx+++ b/src/components/ui/ActivationModeSelector.tsx@@ -23,7 +23,7 @@ export function ActivationModeSelector({return (<divclassName={`- relative flex rounded-md border transition-all duration-200+ relative flex rounded-md border transition-colors duration-200bg-surface-1 border-border-subtle${isCompact ? "p-0.5" : "p-0.5"}${disabled ? "opacity-50 cursor-not-allowed" : ""}diff --git a/src/components/ui/ApiKeyInput.tsx b/src/components/ui/ApiKeyInput.tsxindex 2e9a77136..14546d4f5 100644--- a/src/components/ui/ApiKeyInput.tsx+++ b/src/components/ui/ApiKeyInput.tsx@@ -1,5 +1,6 @@-import React from "react";-import { Check } from "lucide-react";+import React, { useState, useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Check, X, KeyRound } from "lucide-react";import { Input } from "./input";interface ApiKeyInputProps {@@ -8,40 +9,152 @@ interface ApiKeyInputProps {className?: string;placeholder?: string;label?: string;+ ariaLabel?: string;helpText?: React.ReactNode;variant?: "default" | "purple";}+function maskKey(key: string): string {+ if (key.length <= 8) return "••••••••";+ return key.slice(0, 3) + "..." + key.slice(-4);+}+export default function ApiKeyInput({apiKey,setApiKey,className = "",- placeholder = "sk-...",- label = "API Key",- helpText = "Get your API key from platform.openai.com",+ placeholder,+ label,+ ariaLabel,+ helpText,variant = "default",}: ApiKeyInputProps) {+ const { t } = useTranslation();+ const resolvedPlaceholder = placeholder ?? t("apiKeyInput.placeholder");+ const resolvedLabel = label ?? t("apiKeyInput.label");+ const [isEditing, setIsEditing] = useState(false);+ const [draft, setDraft] = useState("");+ const inputRef = useRef<HTMLInputElement>(null);+ const containerRef = useRef<HTMLDivElement>(null);const hasKey = apiKey.length > 0;const variantClasses = variant === "purple" ? "border-primary focus:border-primary" : "";+ useEffect(() => {+ if (isEditing) {+ requestAnimationFrame(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ });+ }+ }, [isEditing]);++ const enterEdit = () => {+ setDraft(apiKey);+ setIsEditing(true);+ };++ const save = () => {+ try {+ setApiKey(draft.trim());+ } catch {+ // Store setter may throw (e.g. cache invalidation in renderer)+ }+ setIsEditing(false);+ };++ const cancel = () => {+ setDraft("");+ setIsEditing(false);+ };++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ e.preventDefault();+ save();+ }+ if (e.key === "Escape") {+ e.preventDefault();+ cancel();+ }+ };++ useEffect(() => {+ if (!isEditing) return;+ const handleClickOutside = (e: MouseEvent) => {+ if (containerRef.current?.contains(e.target as Node)) return;+ cancel();+ };+ document.addEventListener("mousedown", handleClickOutside);+ return () => document.removeEventListener("mousedown", handleClickOutside);+ }, [isEditing]);+return (<div className={className}>- {label && <label className="block text-xs font-medium text-foreground mb-1">{label}</label>}- <div className="relative">- <Input- type="password"- placeholder={placeholder}- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- className={`h-8 text-sm ${hasKey ? "pr-8" : ""} ${variantClasses}`}- />- {hasKey && (- <div className="absolute right-2.5 top-1/2 -translate-y-1/2">- <Check className="w-3.5 h-3.5 text-success" />+ {resolvedLabel && (+ <label className="block text-xs font-medium text-foreground mb-1">{resolvedLabel}</label>+ )}++ <div ref={containerRef} className="relative">+ {isEditing ? (+ <div className="relative">+ <Input+ ref={inputRef}+ type="text"+ placeholder={resolvedPlaceholder}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={handleKeyDown}+ aria-label={ariaLabel || resolvedLabel || t("apiKeyInput.label")}+ className={`h-8 text-sm font-mono pr-16 ${variantClasses}`}+ autoComplete="off"+ spellCheck={false}+ />+ <div className="absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-0.5">+ <button+ type="button"+ onClick={save}+ className="h-6 w-6 flex items-center justify-center rounded text-success hover:bg-success/10 active:scale-95 transition-all"+ aria-label={t("apiKeyInput.save")}+ >+ <Check className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={cancel}+ className="h-6 w-6 flex items-center justify-center rounded text-muted-foreground/50 hover:text-muted-foreground hover:bg-muted/50 active:scale-95 transition-all"+ aria-label={t("apiKeyInput.cancelEdit")}+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div></div>+ ) : (+ <button+ type="button"+ onClick={enterEdit}+ className={`w-full h-8 flex items-center px-3 rounded border text-sm transition-all cursor-pointer group ${+ hasKey+ ? "border-border/70 bg-input hover:border-border-hover dark:bg-surface-1 dark:border-border-subtle/50 dark:hover:border-border-hover"+ : "border-dashed border-border/40 bg-transparent hover:border-border/70 hover:bg-muted/30"+ }`}+ aria-label={hasKey ? t("apiKeyInput.edit") : t("apiKeyInput.add")}+ >+ {hasKey ? (+ <span className="flex items-center gap-1.5 text-foreground/70 font-mono text-xs tracking-wide">+ <KeyRound className="w-3 h-3 text-muted-foreground/50 shrink-0" />+ {maskKey(apiKey)}+ </span>+ ) : (+ <span className="text-muted-foreground/40 text-xs">{resolvedPlaceholder}</span>+ )}+ <span className="ml-auto text-muted-foreground/30 text-xs group-hover:text-muted-foreground/60 transition-colors">+ {hasKey ? t("apiKeyInput.editButton") : t("apiKeyInput.addButton")}+ </span>+ </button>)}</div>- {helpText && <p className="text-[11px] text-muted-foreground/70 mt-1">{helpText}</p>}++ {helpText && <p className="text-xs text-muted-foreground/70 mt-1">{helpText}</p>}</div>);}diff --git a/src/components/ui/DownloadProgressBar.tsx b/src/components/ui/DownloadProgressBar.tsxindex 64d00e3cb..8cb1702ab 100644--- a/src/components/ui/DownloadProgressBar.tsx+++ b/src/components/ui/DownloadProgressBar.tsx@@ -33,7 +33,7 @@ export function DownloadProgressBar({{isInstalling ? (<Loader2 className="relative w-3.5 h-3.5 text-primary animate-spin" />) : (- <span className="relative text-[10px] font-bold text-primary tabular-nums">+ <span className="relative text-xs font-bold text-primary tabular-nums">{indeterminate ? "···" : `${pct}%`}</span>)}@@ -45,21 +45,17 @@ export function DownloadProgressBar({{!isInstalling && (indeterminate || speedText || etaText) && (<div className="flex items-center gap-1.5 mt-0.5">{indeterminate && (- <span className="text-[10px] text-muted-foreground/70 tabular-nums">+ <span className="text-xs text-muted-foreground/70 tabular-nums">{formatBytes(downloadedBytes)}</span>)}{speedText && (- <span className="text-[10px] text-muted-foreground/70 tabular-nums">- {speedText}- </span>+ <span className="text-xs text-muted-foreground/70 tabular-nums">{speedText}</span>)}{etaText && (<>- <span className="text-[10px] text-muted-foreground/30">·</span>- <span className="text-[10px] text-muted-foreground/70 tabular-nums">- {etaText}- </span>+ <span className="text-xs text-muted-foreground/30">·</span>+ <span className="text-xs text-muted-foreground/70 tabular-nums">{etaText}</span></>)}</div>diff --git a/src/components/ui/HotkeyInput.tsx b/src/components/ui/HotkeyInput.tsxindex 44194a1ce..c772ea6b7 100644--- a/src/components/ui/HotkeyInput.tsx+++ b/src/components/ui/HotkeyInput.tsx@@ -473,7 +473,7 @@ export function HotkeyInput({className={`relative group flex flex-col items-center justify-center py-4 px-5 min-h-28rounded-md border cursor-pointer select-none outline-none- transition-all duration-150+ transition-colors duration-150${disabled? "bg-muted/30 border-border cursor-not-allowed opacity-50"@@ -504,7 +504,7 @@ export function HotkeyInput({<span className="text-primary/50 text-sm font-medium">+</span></div>{isFnHeld && (- <span className="text-[10px] text-muted-foreground">+ <span className="text-xs text-muted-foreground">{t("hotkeyInput.fnHeldHint")}</span>)}@@ -517,7 +517,7 @@ export function HotkeyInput({{validationWarning && (<div className="flex items-center gap-1.5 mt-2 px-3 py-1.5 rounded-md bg-warning/8 border border-warning/20 dark:bg-warning/12 dark:border-warning/25"><AlertTriangle className="w-3 h-3 text-warning shrink-0" />- <span className="text-[11px] text-warning dark:text-amber-400">+ <span className="text-xs text-warning dark:text-amber-400">{validationWarning}</span></div>@@ -548,7 +548,7 @@ export function HotkeyInput({</kbd>)}</div>- <span className="text-[10px] text-muted-foreground/60 group-hover:text-muted-foreground transition-colors">+ <span className="text-xs text-muted-foreground/60 group-hover:text-muted-foreground transition-colors">{t("hotkeyInput.clickToChange")}</span></div>@@ -575,7 +575,7 @@ export function HotkeyInput({onBlur={handleBlur}className={`relative overflow-hidden rounded-md border- transition-all duration-150 cursor-pointer select-none focus:outline-none+ transition-colors duration-150 cursor-pointer select-none focus:outline-none${disabled? "bg-muted/30 border-border cursor-not-allowed opacity-50"@@ -604,17 +604,17 @@ export function HotkeyInput({{Array.from(activeModifiers).map((mod) => (<kbdkey={mod}- className="px-2 py-0.5 bg-primary/10 border border-primary/20 rounded-sm text-[11px] font-semibold text-primary"+ className="px-2 py-0.5 bg-primary/10 border border-primary/20 rounded-sm text-xs font-semibold text-primary">{mod}</kbd>))}- <span className="text-primary/40 text-[11px]">+ <span className="text-primary/40 text-xs">{isFnHeld ? t("hotkeyInput.fnCaptureHint") : t("hotkeyInput.keyHint")}</span></div>) : (- <span className="text-[11px] text-muted-foreground">+ <span className="text-xs text-muted-foreground">{isMac ? t("hotkeyInput.tryShortcutMac") : t("hotkeyInput.tryShortcut")}</span>)}@@ -622,7 +622,7 @@ export function HotkeyInput({{validationWarning && (<div className="flex items-center gap-1.5 mt-1.5 px-3 py-1.5 rounded-md bg-warning/8 border border-warning/20 dark:bg-warning/12 dark:border-warning/25"><AlertTriangle className="w-3 h-3 text-warning shrink-0" />- <span className="text-[11px] text-warning dark:text-amber-400">+ <span className="text-xs text-warning dark:text-amber-400">{validationWarning}</span></div>@@ -630,7 +630,7 @@ export function HotkeyInput({</>) : value ? (<div className="flex items-center justify-between">- <span className="text-[11px] font-medium text-muted-foreground">+ <span className="text-xs font-medium text-muted-foreground">{t("hotkeyInput.hotkeyLabel")}</span><div className="flex items-center gap-2">@@ -638,7 +638,7 @@ export function HotkeyInput({<div className="flex items-center gap-1">{hotkeyParts.map((part, i) => (<React.Fragment key={part}>- {i > 0 && <span className="text-muted-foreground/30 text-[10px]">+</span>}+ {i > 0 && <span className="text-muted-foreground/30 text-xs">+</span>}<kbd className="px-2 py-0.5 bg-surface-raised border border-border rounded-sm text-xs font-semibold text-foreground">{part}</kbd>@@ -650,16 +650,14 @@ export function HotkeyInput({<kbd className="px-2 py-0.5 bg-surface-raised border border-border rounded-sm text-base">🌐</kbd>- <span className="text-[11px] text-muted-foreground">- {t("hotkeyInput.globe")}- </span>+ <span className="text-xs text-muted-foreground">{t("hotkeyInput.globe")}</span></div>) : (<kbd className="px-2.5 py-1 bg-surface-raised border border-border rounded-sm text-xs font-semibold text-foreground">{displayValue}</kbd>)}- <span className="text-[10px] text-muted-foreground/50">+ <span className="text-xs text-muted-foreground/50">{t("hotkeyInput.clickToChangeLower")}</span></div>diff --git a/src/components/ui/LanguageSelector.tsx b/src/components/ui/LanguageSelector.tsxindex 4109061e2..8c2e9c109 100644--- a/src/components/ui/LanguageSelector.tsx+++ b/src/components/ui/LanguageSelector.tsx@@ -158,7 +158,7 @@ export default function LanguageSelector({h-7 px-2.5 text-leftrounded text-xs font-mediumborder shadow-sm backdrop-blur-sm- transition-all duration-200 ease-out+ transition-[background-color,border-color,transform] duration-200 ease-outfocus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-1${isOpen@@ -176,7 +176,7 @@ export default function LanguageSelector({{items.find((l) => l.value === value)?.label ?? value}</span><ChevronDown- className={`w-3.5 h-3.5 shrink-0 text-muted-foreground transition-all duration-200 ${+ className={`w-3.5 h-3.5 shrink-0 text-muted-foreground transition-[color,transform] duration-200 ${isOpen ? "rotate-180 text-primary" : "group-hover:text-foreground"}`}/>@@ -241,7 +241,7 @@ export default function LanguageSelector({className={`group w-full flex items-center justify-between gap-2h-7 px-2.5 text-left text-xs font-medium- rounded transition-all duration-150 ease-out+ rounded transition-[background-color,color,transform] duration-150 ease-out${isSelected? "bg-primary/15 text-primary shadow-sm"diff --git a/src/components/ui/MarkdownTextarea.tsx b/src/components/ui/MarkdownTextarea.tsxnew file mode 100644index 000000000..1a90790c2--- /dev/null+++ b/src/components/ui/MarkdownTextarea.tsx@@ -0,0 +1,362 @@+import {+ useRef,+ useMemo,+ useCallback,+ type ReactNode,+ type ChangeEvent,+ type KeyboardEvent,+ type RefObject,+} from "react";+import { cn } from "../lib/utils";++function applyChange(ta: HTMLTextAreaElement, start: number, end: number, insert: string) {+ ta.focus();+ ta.setSelectionRange(start, end);+ document.execCommand("insertText", false, insert);+}++const BULLET_RE = /^(\s*)([-*]) $/;+const BULLET_CONTENT_RE = /^(\s*)([-*]) (.+)$/;+const NUM_RE = /^(\s*)(\d+)\. $/;+const NUM_CONTENT_RE = /^(\s*)(\d+)\. (.+)$/;++interface MarkdownTextareaProps {+ value: string;+ onChange?: (e: ChangeEvent<HTMLTextAreaElement>) => void;+ onSelect?: () => void;+ onBlur?: () => void;+ placeholder?: string;+ className?: string;+ disabled?: boolean;+ textareaRef?: RefObject<HTMLTextAreaElement | null>;+}++const SYN = "text-foreground/25";+const BULLETS = ["•", "◦", "▸"];+const RE_INLINE_MD = /(\*\*\*(.+?)\*\*\*)|(\*\*(.+?)\*\*)|(\*(.+?)\*)|(`([^`]+)`)/g;++function bulletChar(indent: string) {+ const level = Math.floor(indent.length / 2);+ return BULLETS[Math.min(level, BULLETS.length - 1)];+}++function parseInline(text: string, lineKey: number): ReactNode[] {+ if (!text) return [];++ const tokens: ReactNode[] = [];+ RE_INLINE_MD.lastIndex = 0;+ let lastIdx = 0;+ let mi = 0;+ let m: RegExpExecArray | null;++ while ((m = RE_INLINE_MD.exec(text)) !== null) {+ if (m.index > lastIdx) tokens.push(text.slice(lastIdx, m.index));+ const k = `${lineKey}-${mi++}`;++ if (m[1]) {+ tokens.push(+ <span key={k}>+ <span className={SYN}>{"***"}</span>+ <span className="font-semibold italic">{m[2]}</span>+ <span className={SYN}>{"***"}</span>+ </span>+ );+ } else if (m[3]) {+ tokens.push(+ <span key={k}>+ <span className={SYN}>{"**"}</span>+ <span className="font-semibold">{m[4]}</span>+ <span className={SYN}>{"**"}</span>+ </span>+ );+ } else if (m[5]) {+ tokens.push(+ <span key={k}>+ <span className={SYN}>{"*"}</span>+ <span className="italic">{m[6]}</span>+ <span className={SYN}>{"*"}</span>+ </span>+ );+ } else if (m[7]) {+ tokens.push(+ <span key={k}>+ <span className={SYN}>{"`"}</span>+ <span className="bg-foreground/[0.04] dark:bg-white/[0.06] rounded-sm px-px">{m[8]}</span>+ <span className={SYN}>{"`"}</span>+ </span>+ );+ }++ lastIdx = m.index + m[0].length;+ }++ if (lastIdx < text.length) tokens.push(text.slice(lastIdx));+ return tokens;+}++function renderOverlay(text: string): ReactNode[] {+ if (!text) return [];++ const lines = text.split("\n");+ const out: ReactNode[] = [];++ for (let i = 0; i < lines.length; i++) {+ if (i > 0) out.push("\n");++ const line = lines[i];+ if (!line) continue;++ // Header+ const hm = line.match(/^(#{1,3})\s/);+ if (hm) {+ const n = hm[1].length;+ out.push(+ <span key={`l${i}`} className="font-bold">+ <span className={SYN}>{line.slice(0, n + 1)}</span>+ {parseInline(line.slice(n + 1), i)}+ </span>+ );+ continue;+ }++ // Bullet list: `- item` or `* item` (with optional indent)+ const bm = line.match(/^(\s*)([-*])( )/);+ if (bm) {+ const indent = bm[1];+ const marker = bm[2];+ const p = bm[0].length;+ const content = line.slice(p);+ out.push(+ <span key={`l${i}`}>+ {indent}+ <span className="relative">+ <span className="invisible">{marker}</span>+ <span className="absolute left-0 text-foreground/40">{bulletChar(indent)}</span>+ </span>{" "}+ {parseInline(content, i)}+ </span>+ );+ continue;+ }++ // Numbered list: `1. item` (with optional indent)+ const nm = line.match(/^(\s*)(\d+)(\.)( ?)/);+ if (nm) {+ const indent = nm[1];+ const num = nm[2];+ const dot = nm[3];+ const space = nm[4];+ const p = nm[0].length;+ const content = line.slice(p);+ out.push(+ <span key={`l${i}`}>+ {indent}+ <span className="text-foreground/45">{num}</span>+ <span className={SYN}>{dot}</span>+ {space}+ {parseInline(content, i)}+ </span>+ );+ continue;+ }++ // Blockquote+ if (line.startsWith("> ")) {+ out.push(+ <span key={`l${i}`}>+ <span className={SYN}>{"> "}</span>+ {parseInline(line.slice(2), i)}+ </span>+ );+ continue;+ }++ // Horizontal rule+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(line)) {+ out.push(+ <span key={`l${i}`} className={SYN}>+ {line}+ </span>+ );+ continue;+ }++ // Regular line+ const inlined = parseInline(line, i);+ if (inlined.length === 1 && typeof inlined[0] === "string") {+ out.push(inlined[0]);+ } else {+ out.push(<span key={`l${i}`}>{inlined}</span>);+ }+ }++ return out;+}++const SHARED = "leading-[1.7] text-sm px-5 py-3 pb-20 whitespace-pre-wrap break-words";++export function MarkdownTextarea({+ value,+ onChange,+ onSelect,+ onBlur,+ placeholder,+ className,+ disabled,+ textareaRef: externalRef,+}: MarkdownTextareaProps) {+ const localRef = useRef<HTMLTextAreaElement>(null);+ const overlayRef = useRef<HTMLDivElement>(null);+ const taRef = externalRef || localRef;++ const syncScroll = useCallback(() => {+ if (taRef.current && overlayRef.current) {+ overlayRef.current.scrollTop = taRef.current.scrollTop;+ }+ }, [taRef]);++ const overlay = useMemo(() => renderOverlay(value), [value]);++ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLTextAreaElement>) => {+ const ta = taRef.current;+ if (!ta) return;++ const { selectionStart: start, selectionEnd: end, value: val } = ta;+ const before = val.slice(0, start);+ const lineStart = before.lastIndexOf("\n") + 1;+ const currentLine = before.slice(lineStart);+ const lineEndIdx = val.indexOf("\n", start);+ const fullLineEnd = lineEndIdx === -1 ? val.length : lineEndIdx;+ const hasContentAfter = fullLineEnd > start;++ if (e.key === "Enter" && !e.shiftKey && !e.metaKey && !e.ctrlKey) {+ // Empty bullet line → remove prefix, exit list+ const emptyBullet = currentLine.match(BULLET_RE);+ if (emptyBullet) {+ e.preventDefault();+ if (hasContentAfter) {+ applyChange(ta, start, end, `\n${emptyBullet[1]}${emptyBullet[2]} `);+ } else {+ applyChange(ta, lineStart, start, "");+ }+ return;+ }++ // Empty numbered line → remove prefix, exit list+ const emptyNum = currentLine.match(NUM_RE);+ if (emptyNum) {+ e.preventDefault();+ if (hasContentAfter) {+ const next = parseInt(emptyNum[2], 10) + 1;+ applyChange(ta, start, end, `\n${emptyNum[1]}${next}. `);+ } else {+ applyChange(ta, lineStart, start, "");+ }+ return;+ }++ // Bullet with content → continue list+ const bullet = currentLine.match(BULLET_CONTENT_RE);+ if (bullet) {+ e.preventDefault();+ applyChange(ta, start, end, `\n${bullet[1]}${bullet[2]} `);+ return;+ }++ // Numbered list with content → continue with next number+ const num = currentLine.match(NUM_CONTENT_RE);+ if (num) {+ e.preventDefault();+ const next = parseInt(num[2], 10) + 1;+ applyChange(ta, start, end, `\n${num[1]}${next}. `);+ return;+ }+ }++ if (e.key === "Tab") {+ // Multi-line selection → indent/outdent all lines+ if (start !== end && val.slice(start, end).includes("\n")) {+ const firstLineStart = val.lastIndexOf("\n", start - 1) + 1;+ const lastLineEndIdx = val.indexOf("\n", end);+ const lastLineEnd = lastLineEndIdx === -1 ? val.length : lastLineEndIdx;+ const block = val.slice(firstLineStart, lastLineEnd);+ const lines = block.split("\n");++ e.preventDefault();+ let newBlock: string;+ if (e.shiftKey) {+ newBlock = lines.map((l) => l.replace(/^ {1,2}/, "")).join("\n");+ } else {+ newBlock = lines.map((l) => " " + l).join("\n");+ }+ applyChange(ta, firstLineStart, lastLineEnd, newBlock);+ ta.setSelectionRange(firstLineStart, firstLineStart + newBlock.length);+ return;+ }++ // Single line list indent/outdent+ const isBullet = BULLET_RE.test(currentLine) || BULLET_CONTENT_RE.test(currentLine);+ const numMatch = currentLine.match(/^(\s*)(\d+)\. /);++ if (isBullet || numMatch) {+ e.preventDefault();+ if (e.shiftKey) {+ const spaceMatch = currentLine.match(/^ {1,2}/);+ if (spaceMatch) {+ const removed = spaceMatch[0].length;+ applyChange(ta, lineStart, lineStart + removed, "");+ ta.setSelectionRange(start - removed, start - removed);+ }+ } else if (numMatch) {+ const prefixEnd = lineStart + numMatch[1].length + numMatch[2].length;+ applyChange(ta, lineStart, prefixEnd, numMatch[1] + " 1");+ const pos = lineStart + numMatch[1].length + 5;+ ta.setSelectionRange(pos, pos);+ } else {+ applyChange(ta, lineStart, lineStart, " ");+ ta.setSelectionRange(start + 2, start + 2);+ }+ return;+ }+ }+ },+ [taRef]+ );++ return (+ <div className={cn("relative w-full h-full", className)}>+ <div+ ref={overlayRef}+ className={cn(+ SHARED,+ "absolute inset-0 overflow-hidden pointer-events-none text-foreground/90"+ )}+ aria-hidden="true"+ >+ {value ? overlay : <span className="text-foreground/15">{placeholder}</span>}+ </div>+ <textarea+ ref={taRef}+ value={value}+ onChange={onChange}+ onSelect={onSelect}+ onBlur={onBlur}+ onKeyDown={handleKeyDown}+ onScroll={syncScroll}+ disabled={disabled}+ className={cn(+ SHARED,+ "relative z-[1] w-full h-full bg-transparent! border-none! outline-none! resize-none rounded-none selection:bg-primary/15",+ disabled && "pointer-events-none"+ )}+ style={{+ boxShadow: "none",+ color: "transparent",+ caretColor: "var(--color-foreground)",+ WebkitTextFillColor: "transparent",+ }}+ />+ </div>+ );+}diff --git a/src/components/ui/MicPermissionWarning.tsx b/src/components/ui/MicPermissionWarning.tsxindex dcc5b0e23..b9a87d7b8 100644--- a/src/components/ui/MicPermissionWarning.tsx+++ b/src/components/ui/MicPermissionWarning.tsx@@ -70,7 +70,7 @@ export default function MicPermissionWarning({<div className="w-6 h-6 rounded-md bg-warning/15 flex items-center justify-center shrink-0"><AlertCircle className="w-3.5 h-3.5 text-amber-600 dark:text-warning" /></div>- <p className="flex-1 text-[11px] text-amber-700 dark:text-warning/90 leading-snug">+ <p className="flex-1 text-xs text-amber-700 dark:text-warning/90 leading-snug">{error || config.message}</p><div className="flex items-center gap-1 shrink-0">@@ -78,7 +78,7 @@ export default function MicPermissionWarning({variant="ghost"size="sm"onClick={onOpenSoundSettings}- className="h-6 px-2 text-[10px] text-amber-700 hover:text-amber-800 hover:bg-amber-100 dark:text-warning dark:hover:text-warning dark:hover:bg-warning/10"+ className="h-6 px-2 text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-100 dark:text-warning dark:hover:text-warning dark:hover:bg-warning/10">{config.soundLabel}</Button>@@ -87,7 +87,7 @@ export default function MicPermissionWarning({variant="ghost"size="sm"onClick={onOpenPrivacySettings}- className="h-6 px-2 text-[10px] text-amber-700 hover:text-amber-800 hover:bg-amber-100 dark:text-warning dark:hover:text-warning dark:hover:bg-warning/10"+ className="h-6 px-2 text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-100 dark:text-warning dark:hover:text-warning dark:hover:bg-warning/10">{config.privacyLabel}</Button>diff --git a/src/components/ui/ModelCardList.tsx b/src/components/ui/ModelCardList.tsxindex 5a081f984..f2d8a8058 100644--- a/src/components/ui/ModelCardList.tsx+++ b/src/components/ui/ModelCardList.tsx@@ -34,12 +34,6 @@ const COLOR_CONFIG: Record<default: string;}> = {- indigo: {- selected:- "border-primary/30 bg-primary/8 dark:bg-primary/6 dark:border-primary/20 shadow-[0_0_0_1px_oklch(0.62_0.22_260/0.12),0_0_10px_-3px_oklch(0.62_0.22_260/0.18)]",- default:- "border-border bg-surface-1 hover:border-border-hover hover:bg-muted dark:border-white/5 dark:bg-white/3 dark:hover:border-white/20 dark:hover:bg-white/8",- },purple: {selected:"border-primary/30 bg-primary/8 dark:bg-primary/6 dark:border-primary/20 shadow-[0_0_0_1px_oklch(0.62_0.22_260/0.12),0_0_10px_-3px_oklch(0.62_0.22_260/0.18)]",@@ -58,7 +52,7 @@ export default function ModelCardList({models,selectedModel,onModelSelect,- colorScheme = "indigo",+ colorScheme = "purple",className = "",onDownload,onDelete,@@ -116,7 +110,7 @@ export default function ModelCardList({<divkey={model.value}onClick={handleCardClick}- className={`relative w-full p-2 pl-2.5 rounded-md border text-left transition-all duration-200 group overflow-hidden ${+ className={`relative w-full p-2 pl-2.5 rounded-md border text-left transition-colors duration-200 group overflow-hidden ${isSelected ? styles.selected : styles.default} ${!isLocalMode || (isDownloaded && !isSelected) ? "cursor-pointer" : ""}`}>@@ -154,14 +148,14 @@ export default function ModelCardList({{model.label}</span>{model.description && (- <span className="text-[11px] text-muted-foreground/50 tabular-nums shrink-0">+ <span className="text-xs text-muted-foreground/50 tabular-nums shrink-0">{model.description}</span>)}{/* Recommended badge */}{model.recommended && (- <span className="text-[10px] font-medium text-primary px-1.5 py-0.5 bg-primary/10 rounded-sm shrink-0">+ <span className="text-xs font-medium text-primary px-1.5 py-0.5 bg-primary/10 rounded-sm shrink-0">Recommended</span>)}@@ -170,7 +164,7 @@ export default function ModelCardList({<div className="ml-auto flex items-center gap-1.5 shrink-0">{/* Selected/Active badge */}{isSelected && (- <span className="text-[10px] font-medium text-primary px-2 py-0.5 bg-primary/10 rounded-sm">+ <span className="text-xs font-medium text-primary px-2 py-0.5 bg-primary/10 rounded-sm">Active</span>)}@@ -186,7 +180,7 @@ export default function ModelCardList({}}size="sm"variant="ghost"- className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-all active:scale-95"+ className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-[color,opacity,transform] active:scale-95"><Trash2 size={12} /></Button>@@ -199,7 +193,7 @@ export default function ModelCardList({disabled={isCancelling}size="sm"variant="outline"- className="h-6 px-2.5 text-[11px] text-destructive border-destructive/25 hover:bg-destructive/8"+ className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"><X size={11} className="mr-0.5" />{isCancelling ? "..." : "Cancel"}@@ -212,7 +206,7 @@ export default function ModelCardList({}}size="sm"variant="default"- className="h-6 px-2.5 text-[11px]"+ className="h-6 px-2.5 text-xs"><Download size={11} className="mr-1" />Downloaddiff --git a/src/components/ui/PermissionCard.tsx b/src/components/ui/PermissionCard.tsxindex 87c3f1f7e..c38441d52 100644--- a/src/components/ui/PermissionCard.tsx+++ b/src/components/ui/PermissionCard.tsx@@ -24,7 +24,7 @@ export default function PermissionCard({return (<divclassName={cn(- "group relative rounded-md p-3 transition-all duration-150",+ "group relative rounded-md p-3 transition-colors duration-150","border",granted? "bg-success/5 border-success/20 dark:bg-success/5 dark:border-success/15"@@ -35,7 +35,7 @@ export default function PermissionCard({{/* Icon container */}<divclassName={cn(- "w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition-all duration-150",+ "w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition-colors duration-150",granted? "bg-success/10 dark:bg-success/15": "bg-primary/10 dark:bg-primary/15 group-hover:bg-primary/15"@@ -51,13 +51,13 @@ export default function PermissionCard({{/* Content */}<div className="flex-1 min-w-0"><h3 className="text-xs font-medium text-foreground">{title}</h3>- <p className="text-[11px] text-muted-foreground leading-snug mt-0.5">{description}</p>+ <p className="text-xs text-muted-foreground leading-snug mt-0.5">{description}</p></div>{/* Actions - only when not granted */}{!granted && (<div className="flex items-center gap-1.5 shrink-0">- <Button onClick={onRequest} size="sm" className="h-7 px-3 text-[11px]">+ <Button onClick={onRequest} size="sm" className="h-7 px-3 text-xs">{buttonText}</Button>{onOpenSettings && (diff --git a/src/components/ui/ProcessingModeSelector.tsx b/src/components/ui/ProcessingModeSelector.tsxindex 7f3667d6d..cfdfb5982 100644--- a/src/components/ui/ProcessingModeSelector.tsx+++ b/src/components/ui/ProcessingModeSelector.tsx@@ -34,7 +34,7 @@ export default function ProcessingModeSelector({<Cloud className="w-4 h-4" /><span className="text-sm font-medium">{t("common.cloud")}</span>{!useLocalWhisper && (- <span className="text-[10px] text-emerald-500 font-medium">{t("common.fast")}</span>+ <span className="text-xs text-emerald-500 font-medium">{t("common.fast")}</span>)}</button>@@ -47,7 +47,7 @@ export default function ProcessingModeSelector({<Lock className="w-4 h-4" /><span className="text-sm font-medium">{t("common.local")}</span>{useLocalWhisper && (- <span className="text-[10px] text-primary font-medium">{t("common.private")}</span>+ <span className="text-xs text-primary font-medium">{t("common.private")}</span>)}</button></div>diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsxindex 1d0bf6c33..438de39da 100644--- a/src/components/ui/PromptStudio.tsx+++ b/src/components/ui/PromptStudio.tsx@@ -20,6 +20,11 @@ import ReasoningService from "../../services/ReasoningService";import { getModelProvider } from "../../models/ModelRegistry";import logger from "../../utils/logger";import { UNIFIED_SYSTEM_PROMPT } from "../../config/prompts";+import {+ useSettingsStore,+ selectEffectiveReasoningModel,+ selectIsCloudReasoningMode,+} from "../../stores/settingsStore";interface PromptStudioProps {className?: string;@@ -69,6 +74,11 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();const { agentName } = useAgentName();+ const effectiveModel = useSettingsStore(selectEffectiveReasoningModel);+ const isCloudMode = useSettingsStore(selectIsCloudReasoningMode);+ const useReasoningModel = useSettingsStore((s) => s.useReasoningModel);+ const reasoningModel = useSettingsStore((s) => s.reasoningModel);+useEffect(() => {const legacyPrompts = localStorage.getItem("customPrompts");if (legacyPrompts && !localStorage.getItem("customUnifiedPrompt")) {@@ -79,7 +89,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {localStorage.removeItem("customPrompts");}} catch (e) {- console.error("Failed to migrate legacy custom prompts:", e);+ logger.error("Failed to migrate legacy custom prompts", { error: e }, "prompts");}}@@ -88,7 +98,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {try {setEditedPrompt(JSON.parse(customPrompt));} catch (error) {- console.error("Failed to load custom prompt:", error);+ logger.error("Failed to load custom prompt", { error }, "prompts");}}}, []);@@ -123,12 +133,6 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {setTestResult("");try {- const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";- const cloudReasoningMode = localStorage.getItem("cloudReasoningMode") || "openwhispr";- const isSignedIn = localStorage.getItem("isSignedIn") === "true";- const isCloudMode = isSignedIn && cloudReasoningMode === "openwhispr";-- const reasoningModel = localStorage.getItem("reasoningModel") || "";const reasoningProvider = isCloudMode? "openwhispr": reasoningModel@@ -153,20 +157,18 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {return;}- // In BYOK mode, a model must be selectedif (!isCloudMode && !reasoningModel) {setTestResult(t("promptStudio.test.noModelSelected"));return;}- // In BYOK mode with custom provider, validate base URLif (!isCloudMode) {const providerConfig = PROVIDER_CONFIG[reasoningProvider] || {label: reasoningProvider.charAt(0).toUpperCase() + reasoningProvider.slice(1),};if (providerConfig.baseStorageKey) {- const baseUrl = (localStorage.getItem(providerConfig.baseStorageKey) || "").trim();+ const baseUrl = (useSettingsStore.getState().cloudReasoningBaseUrl || "").trim();if (!baseUrl) {setTestResult(t("promptStudio.test.baseUrlMissing", {@@ -178,8 +180,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {}}- // Cloud mode doesn't require a specific model — pass a placeholder if none is set- const modelToUse = isCloudMode ? reasoningModel || "auto" : reasoningModel;+ const modelToUse = isCloudMode ? effectiveModel || "auto" : reasoningModel;const currentCustomPrompt = localStorage.getItem("customUnifiedPrompt");localStorage.setItem("customUnifiedPrompt", JSON.stringify(editedPrompt));@@ -232,7 +233,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {<buttonkey={tab.id}onClick={() => setActiveTab(tab.id)}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-[12px] font-medium transition-all duration-150 border-b-2 ${+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-xs font-medium transition-colors duration-150 border-b-2 ${isActive? "border-primary text-foreground bg-primary/5 dark:bg-primary/3": "border-transparent text-muted-foreground hover:text-foreground hover:bg-black/2 dark:hover:bg-white/2"@@ -261,10 +262,10 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {},].map((item) => (<div key={item.mode} className="flex items-start gap-3">- <span className="shrink-0 mt-0.5 text-[10px] font-medium uppercase tracking-wider px-1.5 py-px rounded bg-muted text-muted-foreground">+ <span className="shrink-0 mt-0.5 text-xs font-medium uppercase tracking-wider px-1.5 py-px rounded bg-muted text-muted-foreground">{item.mode}</span>- <p className="text-[12px] text-muted-foreground leading-relaxed">{item.desc}</p>+ <p className="text-xs text-muted-foreground leading-relaxed">{item.desc}</p></div>))}</div>@@ -273,13 +274,13 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {<div className="px-5 py-4"><div className="flex items-center justify-between mb-3"><div className="flex items-center gap-2">- <p className="text-[11px] font-medium text-muted-foreground/60 uppercase tracking-wider">+ <p className="text-xs font-medium text-muted-foreground/60 uppercase tracking-wider">{isCustomPrompt? t("promptStudio.view.customPrompt"): t("promptStudio.view.defaultPrompt")}</p>{isCustomPrompt && (- <span className="text-[9px] font-semibold uppercase tracking-wider px-1.5 py-px rounded-full bg-primary/10 text-primary">+ <span className="text-xs font-semibold uppercase tracking-wider px-1.5 py-px rounded-full bg-primary/10 text-primary">{t("promptStudio.view.modified")}</span>)}@@ -288,7 +289,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {onClick={() => copyText(getCurrentPrompt())}variant="ghost"size="sm"- className="h-7 px-2 text-[11px]"+ className="h-7 px-2 text-xs">{copiedPrompt ? (<>@@ -303,7 +304,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {</Button></div><div className="bg-muted/30 dark:bg-surface-raised/30 border border-border/30 rounded-lg p-4 max-h-80 overflow-y-auto">- <pre className="text-[11px] font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed">+ <pre className="text-xs font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed">{getCurrentPrompt().replace(/\{\{agentName\}\}/g, agentName)}</pre></div>@@ -315,12 +316,12 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {{activeTab === "edit" && (<div className="divide-y divide-border/40 dark:divide-border-subtle"><div className="px-5 py-4">- <p className="text-[12px] text-muted-foreground leading-relaxed">+ <p className="text-xs text-muted-foreground leading-relaxed"><span className="font-medium text-warning">{t("promptStudio.edit.cautionLabel")}</span>{" "}{t("promptStudio.edit.cautionTextPrefix")}{" "}- <code className="text-[11px] bg-muted/50 px-1 py-0.5 rounded font-mono">+ <code className="text-xs bg-muted/50 px-1 py-0.5 rounded font-mono">{"{{agentName}}"}</code>{" "}{t("promptStudio.edit.cautionTextSuffix")}@@ -332,10 +333,10 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {value={editedPrompt}onChange={(e) => setEditedPrompt(e.target.value)}rows={16}- className="font-mono text-[11px] leading-relaxed"+ className="font-mono text-xs leading-relaxed"placeholder={t("promptStudio.edit.placeholder")}/>- <p className="text-[11px] text-muted-foreground/50 mt-2">+ <p className="text-xs text-muted-foreground/50 mt-2">{t("promptStudio.edit.agentNameLabel")}{" "}<span className="font-medium text-foreground">{agentName}</span></p>@@ -359,12 +360,6 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {{/* ── Test Tab ── */}{activeTab === "test" &&(() => {- const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";- const cloudReasoningMode = localStorage.getItem("cloudReasoningMode") || "openwhispr";- const isSignedIn = localStorage.getItem("isSignedIn") === "true";- const isCloudMode = isSignedIn && cloudReasoningMode === "openwhispr";-- const reasoningModel = localStorage.getItem("reasoningModel") || "";const reasoningProvider = isCloudMode? "openwhispr": reasoningModel@@ -386,7 +381,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {<div className="rounded-lg border border-warning/20 bg-warning/5 dark:bg-warning/10 px-4 py-3"><div className="flex items-start gap-2.5"><AlertTriangle className="w-3.5 h-3.5 text-warning mt-0.5 shrink-0" />- <p className="text-[12px] text-muted-foreground leading-relaxed">+ <p className="text-xs text-muted-foreground leading-relaxed">{t("promptStudio.test.disabledInSettingsPrefix")}{" "}<span className="font-medium text-foreground">{t("promptStudio.test.aiModels")}@@ -401,31 +396,31 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {<div className="px-5 py-4"><div className="flex items-center gap-4"><div className="flex items-center gap-2">- <p className="text-[11px] text-muted-foreground/60 uppercase tracking-wider">+ <p className="text-xs text-muted-foreground/60 uppercase tracking-wider">{t("promptStudio.test.modelLabel")}</p>- <p className="text-[12px] font-medium text-foreground font-mono">+ <p className="text-xs font-medium text-foreground font-mono">{displayModel}</p></div><div className="h-3 w-px bg-border/40" /><div className="flex items-center gap-2">- <p className="text-[11px] text-muted-foreground/60 uppercase tracking-wider">+ <p className="text-xs text-muted-foreground/60 uppercase tracking-wider">{t("promptStudio.test.providerLabel")}</p>- <p className="text-[12px] font-medium text-foreground">{displayProvider}</p>+ <p className="text-xs font-medium text-foreground">{displayProvider}</p></div></div></div><div className="px-5 py-4"><div className="flex items-center justify-between mb-2">- <p className="text-[12px] font-medium text-foreground">+ <p className="text-xs font-medium text-foreground">{t("promptStudio.test.inputLabel")}</p>{testText && (<span- className={`text-[10px] font-medium uppercase tracking-wider px-1.5 py-px rounded ${+ className={`text-xs font-medium uppercase tracking-wider px-1.5 py-px rounded ${isAgentAddressed? "bg-primary/10 text-primary dark:bg-primary/15": "bg-muted text-muted-foreground"@@ -441,10 +436,10 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {value={testText}onChange={(e) => setTestText(e.target.value)}rows={3}- className="text-[12px]"+ className="text-xs"placeholder={t("promptStudio.test.inputPlaceholder")}/>- <p className="text-[10px] text-muted-foreground/40 mt-1.5">+ <p className="text-xs text-muted-foreground/40 mt-1.5">{t("promptStudio.test.addressHint", { agentName })}</p></div>@@ -464,7 +459,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {{testResult && (<div className="px-5 py-4"><div className="flex items-center justify-between mb-2">- <p className="text-[12px] font-medium text-foreground">+ <p className="text-xs font-medium text-foreground">{t("promptStudio.test.outputLabel")}</p><Button@@ -477,7 +472,7 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {</Button></div><div className="bg-muted/30 dark:bg-surface-raised/30 border border-border/30 rounded-lg p-4 max-h-48 overflow-y-auto">- <pre className="text-[12px] text-foreground whitespace-pre-wrap leading-relaxed">+ <pre className="text-xs text-foreground whitespace-pre-wrap leading-relaxed">{testResult}</pre></div>diff --git a/src/components/ui/ProviderTabs.tsx b/src/components/ui/ProviderTabs.tsxindex c0952c215..e1a56bb56 100644--- a/src/components/ui/ProviderTabs.tsx+++ b/src/components/ui/ProviderTabs.tsx@@ -26,7 +26,7 @@ export function ProviderTabs({selectedId,onSelect,renderIcon,- colorScheme = "indigo",+ colorScheme = "purple",scrollable = false,}: ProviderTabsProps) {const { t } = useTranslation();@@ -77,7 +77,7 @@ export function ProviderTabs({>{/* Sliding indicator - frosted glass treatment */}<div- className="absolute top-0.5 left-0 rounded-md bg-card border border-border dark:border-border-subtle shadow-sm dark:shadow-(--shadow-card) transition-all duration-200 ease-out pointer-events-none"+ className="absolute top-0.5 left-0 rounded-md bg-card border border-border dark:border-border-subtle shadow-sm dark:shadow-(--shadow-card) transition-[width,height,transform,opacity] duration-200 ease-out pointer-events-none"style={indicatorStyle}/>@@ -96,9 +96,7 @@ export function ProviderTabs({{renderIcon ? renderIcon(provider.id) : <ProviderIcon provider={provider.id} />}<span>{provider.name}</span>{provider.recommended && (- <span className="text-[9px] text-primary/70 font-medium">- {t("common.recommended")}- </span>+ <span className="text-xs text-primary/70 font-medium">{t("common.recommended")}</span>)}</button>);diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsxindex 322bf22ad..875aed2cb 100644--- a/src/components/ui/SettingsSection.tsx+++ b/src/components/ui/SettingsSection.tsx@@ -16,11 +16,9 @@ export const SettingsSection: React.FC<SettingsSectionProps> = ({return (<div className={`space-y-3 ${className}`}><div>- <h3 className="text-[13px] font-semibold text-foreground tracking-tight">{title}</h3>+ <h3 className="text-xs font-semibold text-foreground tracking-tight">{title}</h3>{description && (- <p className="text-[11px] text-muted-foreground/80 mt-0.5 leading-relaxed">- {description}- </p>+ <p className="text-xs text-muted-foreground/80 mt-0.5 leading-relaxed">{description}</p>)}</div>{children}@@ -49,7 +47,7 @@ export const SettingsGroup: React.FC<SettingsGroupProps> = ({return (<div className={`${baseClasses} ${variantClasses[variant]} ${className}`}>- {title && <h4 className="text-[12px] font-medium text-foreground">{title}</h4>}+ {title && <h4 className="text-xs font-medium text-foreground">{title}</h4>}{children}</div>);@@ -71,11 +69,9 @@ export const SettingsRow: React.FC<SettingsRowProps> = ({return (<div className={`flex items-center justify-between gap-4 ${className}`}><div className="min-w-0 flex-1">- <p className="text-[12px] font-medium text-foreground">{label}</p>+ <p className="text-xs font-medium text-foreground">{label}</p>{description && (- <p className="text-[11px] text-muted-foreground/80 mt-0.5 leading-relaxed">- {description}- </p>+ <p className="text-xs text-muted-foreground/80 mt-0.5 leading-relaxed">{description}</p>)}</div><div className="shrink-0">{children}</div>diff --git a/src/components/ui/SidebarModal.tsx b/src/components/ui/SidebarModal.tsxindex 64e17f5a3..62470acd3 100644--- a/src/components/ui/SidebarModal.tsx+++ b/src/components/ui/SidebarModal.tsx@@ -1,4 +1,5 @@import React from "react";+import { useTranslation } from "react-i18next";import * as DialogPrimitive from "@radix-ui/react-dialog";import { X } from "lucide-react";@@ -36,6 +37,7 @@ export default function SidebarModal<T extends string>({sidebarWidth = "w-52",version,}: SidebarModalProps<T>) {+ const { t } = useTranslation();// Group items by their group propertyconst groupedItems = React.useMemo(() => {const groups: { label: string | null; items: SidebarItem<T>[] }[] = [];@@ -63,7 +65,7 @@ export default function SidebarModal<T extends string>({return (<span- className={`ml-auto text-[9px] font-semibold uppercase tracking-wider px-1.5 py-px rounded-sm shrink-0 ${+ className={`ml-auto text-xs font-semibold uppercase tracking-wider px-1.5 py-px rounded-sm shrink-0 ${item.badgeVariant === "new"? "bg-primary/10 text-primary dark:bg-primary/15": item.badgeVariant === "update"@@ -82,9 +84,9 @@ export default function SidebarModal<T extends string>({<DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" /><DialogPrimitive.Content className="fixed left-[50%] top-[50%] z-50 max-h-[85vh] w-[90vw] max-w-4xl translate-x-[-50%] translate-y-[-50%] rounded-xl p-0 overflow-hidden bg-background border border-border shadow-[0_25px_50px_-12px_rgba(0,0,0,0.25)] dark:bg-surface-1 dark:border-border-subtle dark:shadow-[0_25px_60px_-12px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.05)] duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-98 data-[state=open]:zoom-in-98"><div className="relative h-full max-h-[85vh] overflow-hidden">- <DialogPrimitive.Close className="absolute right-4 top-4 z-10 rounded-md p-1.5 opacity-40 ring-offset-background transition-all hover:opacity-100 bg-transparent hover:bg-muted dark:hover:bg-surface-raised focus:outline-none focus:ring-2 focus:ring-ring/30 focus:ring-offset-1">+ <DialogPrimitive.Close className="absolute right-4 top-4 z-10 rounded-md p-1.5 opacity-40 ring-offset-background transition-[opacity,background-color] hover:opacity-100 bg-transparent hover:bg-muted dark:hover:bg-surface-raised focus:outline-none focus:ring-2 focus:ring-ring/30 focus:ring-offset-1"><X className="h-3.5 w-3.5 text-muted-foreground" />- <span className="sr-only">Close</span>+ <span className="sr-only">{t("common.close")}</span></DialogPrimitive.Close><div className="flex h-[85vh]">@@ -94,7 +96,7 @@ export default function SidebarModal<T extends string>({>{/* Title */}<div className="px-4 pt-5 pb-0.5">- <h2 className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/50">+ <h2 className="text-xs font-semibold uppercase tracking-widest text-muted-foreground/70">{title}</h2></div>@@ -105,7 +107,7 @@ export default function SidebarModal<T extends string>({<div key={groupIndex} className={groupIndex > 0 ? "mt-3" : ""}>{group.label && (<div className="px-2 pb-0.5 pt-1.5">- <span className="text-[9px] font-medium tracking-[0.08em] uppercase text-muted-foreground/35 dark:text-muted-foreground/50">+ <span className="text-xs font-medium tracking-[0.08em] uppercase text-muted-foreground/60 dark:text-muted-foreground/65">{group.label}</span></div>@@ -119,10 +121,10 @@ export default function SidebarModal<T extends string>({key={item.id}data-section-id={item.id}onClick={() => onSectionChange(item.id)}- className={`group relative w-full flex items-center gap-2.5 px-2.5 py-2 text-left text-[12px] rounded-lg transition-all duration-100 outline-none ${+ className={`group relative w-full flex items-center gap-2.5 px-2.5 py-2 text-left text-xs rounded-lg transition-colors duration-100 outline-none ${isActive? "text-foreground bg-muted dark:bg-surface-raised"- : "text-muted-foreground dark:text-foreground/60 hover:text-foreground hover:bg-muted/50 dark:hover:bg-surface-2"+ : "text-muted-foreground dark:text-foreground/75 hover:text-foreground hover:bg-muted/50 dark:hover:bg-surface-2"}`}>{/* Active indicator bar */}@@ -130,7 +132,7 @@ export default function SidebarModal<T extends string>({<div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 rounded-full bg-primary" />)}<div- className={`flex items-center justify-center h-6 w-6 rounded-md shrink-0 transition-all duration-100 ${+ className={`flex items-center justify-center h-6 w-6 rounded-md shrink-0 transition-colors duration-100 ${isActive ? "bg-primary/10 dark:bg-primary/15" : "bg-transparent"}`}>@@ -138,7 +140,7 @@ export default function SidebarModal<T extends string>({className={`h-4 w-4 shrink-0 transition-colors duration-100 ${isActive? "text-primary"- : "text-muted-foreground/60 dark:text-foreground/40 group-hover:text-foreground/80"+ : "text-muted-foreground/70 dark:text-foreground/55 group-hover:text-foreground/80"}`}/></div>@@ -149,7 +151,7 @@ export default function SidebarModal<T extends string>({</span>{renderBadge(item)}{item.shortcut && !item.badge && (- <kbd className="ml-auto text-[9px] text-muted-foreground/25 font-mono shrink-0">+ <kbd className="ml-auto text-xs text-muted-foreground/25 font-mono shrink-0">{item.shortcut}</kbd>)}@@ -166,7 +168,7 @@ export default function SidebarModal<T extends string>({<div className="px-3 py-2.5 border-t border-border/20 dark:border-border-subtle"><div className="flex items-center gap-1.5"><div className="h-1 w-1 rounded-full bg-success/60" />- <span className="text-[9px] text-muted-foreground/40 tabular-nums tracking-wide">+ <span className="text-xs text-muted-foreground/40 tabular-nums tracking-wide">v{version}</span></div>diff --git a/src/components/ui/StepProgress.tsx b/src/components/ui/StepProgress.tsxindex db3515919..e4fa91a25 100644--- a/src/components/ui/StepProgress.tsx+++ b/src/components/ui/StepProgress.tsx@@ -23,7 +23,7 @@ export default function StepProgress({ steps, currentStep, className = "" }: Stereturn (<React.Fragment key={index}><div- className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md transition-all duration-150 ${+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md transition-colors duration-150 ${isActive? "bg-primary/10 text-primary": isCompleted@@ -32,7 +32,7 @@ export default function StepProgress({ steps, currentStep, className = "" }: Ste}`}><div- className={`w-4.5 h-4.5 rounded-md flex items-center justify-center shrink-0 transition-all duration-150 ${+ className={`w-4.5 h-4.5 rounded-md flex items-center justify-center shrink-0 transition-colors duration-150 ${isActive? "bg-primary text-primary-foreground": isCompleted@@ -47,7 +47,7 @@ export default function StepProgress({ steps, currentStep, className = "" }: Ste)}</div><span- className={`text-[10px] font-medium hidden md:block tracking-wide ${+ className={`text-xs font-medium hidden md:block tracking-wide ${isActive? "text-primary": isCompleteddiff --git a/src/components/ui/SupportDropdown.tsx b/src/components/ui/SupportDropdown.tsxindex b1d3c8d59..a6f5ac36d 100644--- a/src/components/ui/SupportDropdown.tsx+++ b/src/components/ui/SupportDropdown.tsx@@ -1,4 +1,5 @@import React from "react";+import { useTranslation } from "react-i18next";import { Button } from "./button";import { HelpCircle, Mail, Bug } from "lucide-react";import {@@ -8,6 +9,7 @@ import {DropdownMenuTrigger,} from "./dropdown-menu";import { cn } from "../lib/utils";+import logger from "../../utils/logger";function DiscordIcon({ className }: { className?: string }) {return (@@ -19,38 +21,42 @@ function DiscordIcon({ className }: { className?: string }) {interface SupportDropdownProps {className?: string;+ trigger?: React.ReactNode;}const openExternal = async (url: string) => {try {const result = await window.electronAPI?.openExternal(url);if (!result?.success) {- console.error("Failed to open URL:", result?.error);+ logger.error("Failed to open URL", { error: result?.error }, "support");}} catch (error) {- console.error("Error opening URL:", error);+ logger.error("Error opening URL", { error }, "support");}};-export default function SupportDropdown({ className }: SupportDropdownProps) {+export default function SupportDropdown({ className, trigger }: SupportDropdownProps) {+ const { t } = useTranslation();return (<DropdownMenu><DropdownMenuTrigger asChild>- <Button- variant="ghost"- size="icon"- className={cn(- "text-foreground/70 hover:text-foreground hover:bg-foreground/10",- className- )}- >- <HelpCircle size={16} />- </Button>+ {trigger || (+ <Button+ variant="ghost"+ size="icon"+ className={cn(+ "text-foreground/70 hover:text-foreground hover:bg-foreground/10",+ className+ )}+ >+ <HelpCircle size={16} />+ </Button>+ )}</DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem onClick={() => openExternal("https://discord.gg/yZWC9WTtX7")}><DiscordIcon className="mr-2 h-4 w-4" />- Join Discord+ {t("support.joinDiscord")}</DropdownMenuItem><DropdownMenuItemonClick={async () => {@@ -61,13 +67,13 @@ export default function SupportDropdown({ className }: SupportDropdownProps) {}}><Mail className="mr-2 h-4 w-4" />- Contact Support+ {t("support.contactSupport")}</DropdownMenuItem><DropdownMenuItemonClick={() => openExternal("https://github.com/OpenWhispr/openwhispr/issues")}><Bug className="mr-2 h-4 w-4" />- Submit Bug+ {t("support.submitBug")}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsxindex d856cfafa..ef6b26100 100644--- a/src/components/ui/Toast.tsx+++ b/src/components/ui/Toast.tsx@@ -148,7 +148,7 @@ const ToastViewport: React.FC<{return (<divclassName={cn(- "fixed z-50 flex flex-col gap-1.5 pointer-events-none",+ "fixed z-[100] flex flex-col gap-1.5 pointer-events-none",isDictationPanel ? "bottom-20 right-6" : "bottom-5 right-5")}>@@ -236,7 +236,7 @@ const Toast: React.FC<className={cn("group toast-surface pointer-events-auto relative flex w-75 overflow-hidden","rounded-[5px]",- "transition-all duration-200 ease-out",+ "transition-[opacity,transform] duration-200 ease-out",isExiting? "opacity-0 translate-x-2 scale-[0.98]": "opacity-100 translate-x-0 scale-100 animate-in slide-in-from-right-4 fade-in-0 duration-300"@@ -249,13 +249,13 @@ const Toast: React.FC<<div className="flex items-start gap-2 flex-1 min-w-0 px-2.5 py-2 pr-7"><div className="flex-1 min-w-0">{message && (- <div className="text-[12px] font-medium leading-tight text-white/90">{message}</div>+ <div className="text-xs font-medium leading-tight text-white/90">{message}</div>)}{detail &&(isDestructive ? (<divclassName={cn(- "text-[11px] leading-snug mt-1 px-1.5 py-1 rounded-[3px] font-mono",+ "text-xs leading-snug mt-1 px-1.5 py-1 rounded-[3px] font-mono","bg-white/4 border border-white/6","text-red-300/80")}@@ -268,7 +268,7 @@ const Toast: React.FC<"shrink-0 p-0.5 rounded-xs mt-px","text-white/30 hover:text-white/70","hover:bg-white/6",- "transition-all duration-150"+ "transition-colors duration-150")}aria-label="Copy error">@@ -277,7 +277,7 @@ const Toast: React.FC<</div></div>) : (- <div className="text-[11px] leading-snug mt-0.5 text-white/45">{detail}</div>+ <div className="text-xs leading-snug mt-0.5 text-white/45">{detail}</div>))}</div>@@ -291,7 +291,7 @@ const Toast: React.FC<"absolute right-1 top-1 p-1 rounded-[3px]","text-white/0 group-hover:text-white/50 hover:!text-white/80","hover:bg-white/6",- "transition-all duration-150",+ "transition-colors duration-150","focus:outline-none focus-visible:ring-1 focus-visible:ring-white/20")}>diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsxindex 17ba7cea2..adf2d8305 100644--- a/src/components/ui/TranscriptionItem.tsx+++ b/src/components/ui/TranscriptionItem.tsx@@ -1,102 +1,49 @@import { useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "./button";-import { Copy, Trash2, ChevronDown, ChevronUp } from "lucide-react";+import { Copy, Trash2 } from "lucide-react";import type { TranscriptionItem as TranscriptionItemType } from "../../types/electron";import { cn } from "../lib/utils";interface TranscriptionItemProps {item: TranscriptionItemType;- index: number;- total: number;onCopy: (text: string) => void;onDelete: (id: number) => void;}-const TEXT_PREVIEW_LENGTH = 120;--export default function TranscriptionItem({- item,- index,- total,- onCopy,- onDelete,-}: TranscriptionItemProps) {- const { i18n, t } = useTranslation();- const [isExpanded, setIsExpanded] = useState(false);+export default function TranscriptionItem({ item, onCopy, onDelete }: TranscriptionItemProps) {+ const { i18n } = useTranslation();const [isHovered, setIsHovered] = useState(false);const timestampSource = item.timestamp.endsWith("Z") ? item.timestamp : `${item.timestamp}Z`;const timestampDate = new Date(timestampSource);- const formattedTimestamp = Number.isNaN(timestampDate.getTime())- ? item.timestamp- : timestampDate.toLocaleString(i18n.language, {- month: "short",- day: "numeric",+ const formattedTime = Number.isNaN(timestampDate.getTime())+ ? ""+ : timestampDate.toLocaleTimeString(i18n.language, {hour: "2-digit",minute: "2-digit",});- const isLongText = item.text.length > TEXT_PREVIEW_LENGTH;- const displayText =- isExpanded || !isLongText ? item.text : `${item.text.slice(0, TEXT_PREVIEW_LENGTH)}…`;-return (<div- className="group relative px-3 py-2.5 transition-colors duration-150 hover:bg-muted/30 dark:hover:bg-white/2"+ className="group rounded-md border border-border/40 dark:border-border-subtle/60 bg-card/50 dark:bg-surface-2/60 px-3 py-2.5 transition-colors duration-150 hover:bg-muted/30 dark:hover:bg-surface-2/80"onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}><div className="flex items-start gap-3">- {/* Number badge - compact pill */}- <div className="flex-shrink-0 mt-0.5">- <span className="inline-flex items-center justify-center min-w-[28px] h-5 px-1.5 rounded-sm bg-primary/10 dark:bg-primary/15 text-primary text-[10px] font-semibold tabular-nums">- {total - index}+ {formattedTime && (+ <span className="shrink-0 text-[11px] text-muted-foreground tabular-nums pt-0.5">+ {formattedTime}</span>- </div>+ )}- {/* Content */}- <div className="flex-1 min-w-0">- {/* Text */}- <p- className={cn(- "text-foreground text-[13px] leading-[1.5] break-words",- !isExpanded && isLongText && "line-clamp-2"- )}- >- {displayText}- </p>-- {/* Metadata row */}- <div className="flex items-center gap-2 mt-1">- <span className="text-[11px] text-muted-foreground tabular-nums">- {formattedTimestamp}- </span>- {isLongText && (- <button- onClick={() => setIsExpanded(!isExpanded)}- className="inline-flex items-center gap-0.5 text-[11px] text-primary/80 hover:text-primary transition-colors"- >- {isExpanded ? (- <>- <span>{t("common.less")}</span>- <ChevronUp size={12} />- </>- ) : (- <>- <span>{t("common.more")}</span>- <ChevronDown size={12} />- </>- )}- </button>- )}- </div>- </div>+ <p className="flex-1 min-w-0 text-foreground text-sm leading-[1.5] break-words">+ {item.text}+ </p>- {/* Actions - fade in on hover */}<divclassName={cn(- "flex items-center gap-0.5 flex-shrink-0 transition-opacity duration-150",+ "flex items-center gap-0.5 shrink-0 transition-opacity duration-150",isHovered ? "opacity-100" : "opacity-0")}>diff --git a/src/components/ui/accordion.tsx b/src/components/ui/accordion.tsxindex 15c924296..fadc6d725 100644--- a/src/components/ui/accordion.tsx+++ b/src/components/ui/accordion.tsx@@ -25,7 +25,7 @@ const AccordionTrigger = React.forwardRef<<AccordionPrimitive.Triggerref={ref}className={cn(- "flex flex-1 items-center justify-between py-3 text-sm font-semibold text-gray-800 transition-all hover:text-gray-900 [&[data-state=open]>svg]:rotate-180",+ "flex flex-1 items-center justify-between py-3 text-sm font-semibold text-gray-800 transition-colors hover:text-gray-900 [&[data-state=open]>svg]:rotate-180",className)}{...props}diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex 8fb814da2..fc22cfb64 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -8,7 +8,7 @@ const buttonVariants = cva(["inline-flex items-center justify-center gap-2 whitespace-nowrap","rounded text-sm font-medium cursor-pointer select-none",- "transition-all duration-200 ease-out",+ "transition-[background-color,border-color,color,transform] duration-200 ease-out","outline-none focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed","[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 shrink-0",@@ -24,7 +24,7 @@ const buttonVariants = cva("shadow-sm","hover:bg-primary/95 hover:shadow","active:bg-primary/85 active:scale-[0.985]",- "transition-all duration-200 ease-out",+ "transition-[background-color,border-color,color,transform] duration-200 ease-out",].join(" "),// Success — uses design tokens@@ -56,7 +56,7 @@ const buttonVariants = cva("hover:bg-muted hover:border-border-hover","active:scale-[0.985]","dark:bg-surface-raised/90 dark:border-border-hover dark:hover:bg-surface-raised",- "transition-all duration-200 ease-out",+ "transition-[background-color,border-color,color,transform] duration-200 ease-out",].join(" "),// Secondary — uses design tokens@@ -95,7 +95,7 @@ const buttonVariants = cva("hover:bg-surface-2/90 hover:border-border-hover hover:shadow","active:scale-[0.985] active:shadow-sm","dark:bg-surface-raised/80 dark:border-border-hover dark:hover:bg-surface-raised/95",- "transition-all duration-200 ease-out",+ "transition-[background-color,border-color,color,transform] duration-200 ease-out",].join(" "),},size: {diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsxindex 2cc46f7ae..cf4d30751 100644--- a/src/components/ui/card.tsx+++ b/src/components/ui/card.tsx@@ -7,7 +7,7 @@ const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElemen<divref={ref}className={cn(- "rounded-lg border border-border bg-card text-card-foreground shadow-sm transition-all duration-150",+ "rounded-lg border border-border bg-card text-card-foreground shadow-sm transition-colors duration-150","dark:bg-card dark:border-border-subtle dark:hover:border-border-hover",className)}diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsxindex c41fb5ea9..1546b31e1 100644--- a/src/components/ui/dialog.tsx+++ b/src/components/ui/dialog.tsx@@ -45,7 +45,7 @@ const DialogContent = React.forwardRef<{...props}>{children}- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-full opacity-50 ring-offset-background transition-all hover:opacity-100 hover:bg-muted/50 dark:hover:bg-surface-raised focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none p-1.5">+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-full opacity-50 ring-offset-background transition-[opacity,background-color] hover:opacity-100 hover:bg-muted/50 dark:hover:bg-surface-raised focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none p-1.5"><X className="h-4 w-4 text-muted-foreground" /><span className="sr-only">Close</span></DialogPrimitive.Close>diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsxindex fe10136f1..12320496a 100644--- a/src/components/ui/input.tsx+++ b/src/components/ui/input.tsx@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {type={type}data-slot="input"className={cn(- "flex h-10 w-full min-w-0 rounded border border-border/70 bg-input px-3 py-2 text-sm text-foreground shadow-none transition-all duration-200 outline-none",+ "flex h-10 w-full min-w-0 rounded border border-border/70 bg-input px-3 py-2 text-sm text-foreground shadow-none transition-colors duration-200 outline-none","placeholder:text-muted-foreground/40","selection:bg-primary selection:text-primary-foreground","file:text-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium",diff --git a/src/components/ui/progress.tsx b/src/components/ui/progress.tsxindex d09e43d41..202889092 100644--- a/src/components/ui/progress.tsx+++ b/src/components/ui/progress.tsx@@ -16,7 +16,7 @@ const Progress = React.forwardRef<{...props}><ProgressPrimitive.Indicator- className="h-full w-full flex-1 bg-primary transition-all duration-300"+ className="h-full w-full flex-1 bg-primary transition-transform duration-300"style={{ transform: `translateX(-${100 - (value || 0)}%)` }}/></ProgressPrimitive.Root>diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsxindex 469d53054..5032b89e1 100644--- a/src/components/ui/select.tsx+++ b/src/components/ui/select.tsx@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<<SelectPrimitive.Triggerref={ref}className={cn(- "flex h-10 w-full items-center justify-between rounded-xl border border-border bg-input px-3.5 py-2 text-sm text-foreground shadow-none ring-offset-background transition-all duration-200",+ "flex h-10 w-full items-center justify-between rounded-xl border border-border bg-input px-3.5 py-2 text-sm text-foreground shadow-none ring-offset-background transition-colors duration-200","placeholder:text-muted-foreground","[&>span]:line-clamp-1","focus:outline-none focus:ring-[3px] focus:ring-primary/15 focus:border-primary",diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsxindex 5b1be6320..c7e0fb8d3 100644--- a/src/components/ui/tabs.tsx+++ b/src/components/ui/tabs.tsx@@ -27,7 +27,7 @@ const TabsTrigger = React.forwardRef<<TabsPrimitive.Triggerref={ref}className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-all duration-200",+ "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-colors duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:pointer-events-none disabled:opacity-50","data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-sm",diff --git a/src/components/ui/textarea.tsx b/src/components/ui/textarea.tsxindex 5a1b926e3..522116bc2 100644--- a/src/components/ui/textarea.tsx+++ b/src/components/ui/textarea.tsx@@ -9,7 +9,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(return (<textareaclassName={cn(- "flex min-h-[80px] w-full rounded-xl border border-neutral-200 bg-white px-3.5 py-3 text-sm text-neutral-900 shadow-sm transition-all duration-200 outline-none resize-y cursor-text",+ "flex min-h-[80px] w-full rounded-xl border border-neutral-200 bg-white px-3.5 py-3 text-sm text-neutral-900 shadow-sm transition-colors duration-200 outline-none resize-y cursor-text","placeholder:text-neutral-400","hover:border-neutral-300","focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20",diff --git a/src/components/ui/toggle.tsx b/src/components/ui/toggle.tsxindex caffb3615..4b0a930b5 100644--- a/src/components/ui/toggle.tsx+++ b/src/components/ui/toggle.tsx@@ -20,12 +20,12 @@ export const Toggle = ({ checked, onChange, disabled = false }: ToggleProps) =><buttononClick={() => !disabled && onChange(!checked)}disabled={disabled}- className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 ${getTrackClasses()} ${+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 ${getTrackClasses()} ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`}><span- className={`inline-block h-4 w-4 transform rounded-full transition-all duration-150 ${+ className={`inline-block h-4 w-4 transform rounded-full transition-transform duration-150 ${checked ? "translate-x-6" : "translate-x-1"} ${disabled ? "bg-muted-foreground/50" : "bg-background shadow-sm"}`}/>diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex fa17f3ece..71f609a77 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -5,7 +5,7 @@ import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";import { isSecureEndpoint } from "../utils/urlUtils";import { withSessionRefresh } from "../lib/neonAuth";import { getBaseLanguageCode, validateLanguageForModel } from "../utils/languageSupport";-import { hasStoredByokKey } from "../utils/byokDetection";+import { getSettings, getEffectiveReasoningModel } from "../stores/settingsStore";const SHORT_CLIP_DURATION_SECONDS = 2.5;const REASONING_CACHE_TTL = 30000; // 30 seconds@@ -64,6 +64,7 @@ class AudioManager {this.stopRequestedDuringStreamingStart = false;this.streamingFallbackRecorder = null;this.streamingFallbackChunks = [];+ this.skipReasoning = false;}getWorkletBlobUrl() {@@ -111,27 +112,31 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}getCustomDictionaryPrompt() {- try {- const raw = localStorage.getItem("customDictionary");- if (!raw) return null;- const parsed = JSON.parse(raw);- if (Array.isArray(parsed) && parsed.length > 0) return parsed.join(", ");- } catch {- // ignore parse errors- }- return null;+ const words = getSettings().customDictionary;+ return words.length > 0 ? words.join(", ") : null;}- setCallbacks({ onStateChange, onError, onTranscriptionComplete, onPartialTranscript }) {+ setCallbacks({+ onStateChange,+ onError,+ onTranscriptionComplete,+ onPartialTranscript,+ onStreamingCommit,+ }) {this.onStateChange = onStateChange;this.onError = onError;this.onTranscriptionComplete = onTranscriptionComplete;this.onPartialTranscript = onPartialTranscript;+ this.onStreamingCommit = onStreamingCommit;+ }++ setSkipReasoning(skip) {+ this.skipReasoning = skip;}async getAudioConstraints() {- const preferBuiltIn = localStorage.getItem("preferBuiltInMic") !== "false";- const selectedDeviceId = localStorage.getItem("selectedMicDeviceId") || "";+ const { preferBuiltInMic: preferBuiltIn, selectedMicDeviceId: selectedDeviceId } =+ getSettings();// Disable browser audio processing — dictation doesn't need it and it adds ~48ms latencyconst noProcessing = {@@ -185,8 +190,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);async cacheMicrophoneDeviceId() {if (this.cachedMicDeviceId) return; // Already cached- const preferBuiltIn = localStorage.getItem("preferBuiltInMic") !== "false";- if (!preferBuiltIn) return; // Only needed for built-in mic detection+ if (!getSettings().preferBuiltInMic) return; // Only needed for built-in mic detectiontry {const devices = await navigator.mediaDevices.enumerateDevices();@@ -332,15 +336,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const pipelineStart = performance.now();try {- const useLocalWhisper = localStorage.getItem("useLocalWhisper") === "true";- const localProvider = localStorage.getItem("localTranscriptionProvider") || "whisper";- const whisperModel = localStorage.getItem("whisperModel") || "base";- const parakeetModel = localStorage.getItem("parakeetModel") || "parakeet-tdt-0.6b-v3";+ const s = getSettings();+ const useLocalWhisper = s.useLocalWhisper;+ const localProvider = s.localTranscriptionProvider;+ const whisperModel = s.whisperModel;+ const parakeetModel = s.parakeetModel || "parakeet-tdt-0.6b-v3";- const cloudTranscriptionMode =- localStorage.getItem("cloudTranscriptionMode") ||- (hasStoredByokKey() ? "byok" : "openwhispr");- const isSignedIn = localStorage.getItem("isSignedIn") === "true";+ const cloudTranscriptionMode = s.cloudTranscriptionMode;+ const isSignedIn = s.isSignedIn;const isOpenWhisprCloudMode = !useLocalWhisper && cloudTranscriptionMode === "openwhispr";const useCloud = isOpenWhisprCloudMode && isSignedIn;@@ -437,7 +440,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// Send original audio to main process - FFmpeg in main process handles conversion// (renderer-side AudioContext conversion was unreliable with WebM/Opus format)const arrayBuffer = await audioBlob.arrayBuffer();- const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));+ const language = getBaseLanguageCode(getSettings().preferredLanguage);const options = { model };if (language) {options.language = language;@@ -493,8 +496,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);throw error;}- const allowOpenAIFallback = localStorage.getItem("allowOpenAIFallback") === "true";- const isLocalMode = localStorage.getItem("useLocalWhisper") === "true";+ const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();if (allowOpenAIFallback && isLocalMode) {try {@@ -516,7 +518,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);try {const arrayBuffer = await audioBlob.arrayBuffer();- const language = validateLanguageForModel(localStorage.getItem("preferredLanguage"), model);+ const language = validateLanguageForModel(getSettings().preferredLanguage, model);const options = { model };if (language) {options.language = language;@@ -567,8 +569,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);throw error;}- const allowOpenAIFallback = localStorage.getItem("allowOpenAIFallback") === "true";- const isLocalMode = localStorage.getItem("useLocalWhisper") === "true";+ const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();if (allowOpenAIFallback && isLocalMode) {try {@@ -586,11 +587,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async getAPIKey() {- // Get the current transcription provider- const provider =- typeof localStorage !== "undefined"- ? localStorage.getItem("cloudTranscriptionProvider") || "openai"- : "openai";+ const s = getSettings();+ const provider = s.cloudTranscriptionProvider || "openai";// Check cache (invalidate if provider changed)if (this.cachedApiKey !== null && this.cachedApiKeyProvider === provider) {@@ -600,8 +598,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);let apiKey = null;if (provider === "custom") {- // Prefer localStorage (user-entered via UI) over main process (.env)- apiKey = localStorage.getItem("customTranscriptionApiKey") || "";+ // Prefer store value (user-entered via UI) over main process (.env)+ apiKey = s.customTranscriptionApiKey || "";if (!apiKey.trim()) {try {apiKey = await window.electronAPI.getCustomTranscriptionKey?.();@@ -631,9 +629,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);apiKey = null;}} else if (provider === "mistral") {- // Prefer localStorage (user-entered via UI) over main process (.env)+ // Prefer store value (user-entered via UI) over main process (.env)// to avoid stale keys in process.env after auth mode transitions- apiKey = localStorage.getItem("mistralApiKey");+ apiKey = s.mistralApiKey;if (!isValidApiKey(apiKey, "mistral")) {apiKey = await window.electronAPI.getMistralKey?.();}@@ -641,8 +639,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);throw new Error("Mistral API key not found. Please set your API key in the Control Panel.");}} else if (provider === "groq") {- // Prefer localStorage (user-entered via UI) over main process (.env)- apiKey = localStorage.getItem("groqApiKey");+ // Prefer store value (user-entered via UI) over main process (.env)+ apiKey = s.groqApiKey;if (!isValidApiKey(apiKey, "groq")) {apiKey = await window.electronAPI.getGroqKey?.();}@@ -651,9 +649,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}} else {// Default to OpenAI- // Prefer localStorage (user-entered via UI) over main process (.env)+ // Prefer store value (user-entered via UI) over main process (.env)// to avoid stale keys in process.env after auth mode transitions- apiKey = localStorage.getItem("openaiApiKey");+ apiKey = s.openaiApiKey;if (!isValidApiKey(apiKey, "openai")) {apiKey = await window.electronAPI.getOpenAIKey();}@@ -778,36 +776,31 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async isReasoningAvailable() {- if (typeof window === "undefined" || !window.localStorage) {+ if (typeof window === "undefined") {return false;}- const storedValue = localStorage.getItem("useReasoningModel");+ const useReasoning = getSettings().useReasoningModel;const now = Date.now();const cacheValid =this.reasoningAvailabilityCache &&now < this.reasoningAvailabilityCache.expiresAt &&- this.cachedReasoningPreference === storedValue;+ this.cachedReasoningPreference === useReasoning;if (cacheValid) {return this.reasoningAvailabilityCache.value;}logger.logReasoning("REASONING_STORAGE_CHECK", {- storedValue,- typeOfStoredValue: typeof storedValue,- isTrue: storedValue === "true",- isTruthy: !!storedValue && storedValue !== "false",+ useReasoning,});- const useReasoning = storedValue === "true" || (!!storedValue && storedValue !== "false");-if (!useReasoning) {this.reasoningAvailabilityCache = {value: false,expiresAt: now + REASONING_CACHE_TTL,};- this.cachedReasoningPreference = storedValue;+ this.cachedReasoningPreference = useReasoning;return false;}@@ -824,7 +817,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);value: isAvailable,expiresAt: now + REASONING_CACHE_TTL,};- this.cachedReasoningPreference = storedValue;+ this.cachedReasoningPreference = useReasoning;return isAvailable;} catch (error) {@@ -837,7 +830,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);value: false,expiresAt: now + REASONING_CACHE_TTL,};- this.cachedReasoningPreference = storedValue;+ this.cachedReasoningPreference = useReasoning;return false;}}@@ -852,14 +845,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);timestamp: new Date().toISOString(),});- const reasoningModel =- typeof window !== "undefined" && window.localStorage- ? localStorage.getItem("reasoningModel") || ""- : "";- const reasoningProvider =- typeof window !== "undefined" && window.localStorage- ? localStorage.getItem("reasoningProvider") || "auto"- : "auto";+ const reasoningModel = getEffectiveReasoningModel();+ const reasoningProvider = getSettings().reasoningProvider || "auto";const agentName =typeof window !== "undefined" && window.localStorage? localStorage.getItem("agentName") || null@@ -907,7 +894,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);stack: error.stack,fallbackToCleanup: true,});- console.error(`Reasoning failed (${source}):`, error.message);+ logger.error("Reasoning failed", { source, error: error.message }, "notes");}}@@ -1081,7 +1068,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}const timings = {};- const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));+ const settings = getSettings();+ const language = getBaseLanguageCode(settings.preferredLanguage);const arrayBuffer = await audioBlob.arrayBuffer();const opts = {};@@ -1105,20 +1093,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// Process with reasoning if enabledlet processedText = result.text;- const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";- if (useReasoningModel && processedText) {+ if (settings.useReasoningModel && processedText && !this.skipReasoning) {const reasoningStart = performance.now();const agentName = localStorage.getItem("agentName") || "";- const cloudReasoningMode = localStorage.getItem("cloudReasoningMode") || "openwhispr";+ const cloudReasoningMode = settings.cloudReasoningMode || "openwhispr";if (cloudReasoningMode === "openwhispr") {const reasonResult = await withSessionRefresh(async () => {const res = await window.electronAPI.cloudReason(processedText, {agentName,- customDictionary: this.getCustomDictionaryArray(),+ customDictionary: settings.customDictionary,customPrompt: this.getCustomPrompt(),- language: localStorage.getItem("preferredLanguage") || "auto",- locale: localStorage.getItem("uiLanguage") || "en",+ language: settings.preferredLanguage || "auto",+ locale: settings.uiLanguage || "en",});if (!res.success) {const err = new Error(res.error || "Cloud reasoning failed");@@ -1132,11 +1119,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);processedText = reasonResult.text;}} else {- const reasoningModel = localStorage.getItem("reasoningModel") || "";- if (reasoningModel) {+ const effectiveModel = getEffectiveReasoningModel();+ if (effectiveModel) {const result = await this.processWithReasoningModel(processedText,- reasoningModel,+ effectiveModel,agentName);if (result) {@@ -1159,14 +1146,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}getCustomDictionaryArray() {- try {- const raw = localStorage.getItem("customDictionary");- if (!raw) return [];- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }+ return getSettings().customDictionary;}getCustomPrompt() {@@ -1186,9 +1166,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);async processWithOpenAIAPI(audioBlob, metadata = {}) {const timings = {};- const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));- const allowLocalFallback = localStorage.getItem("allowLocalFallback") === "true";- const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";+ const apiSettings = getSettings();+ const language = getBaseLanguageCode(apiSettings.preferredLanguage);+ const allowLocalFallback = apiSettings.allowLocalFallback;+ const fallbackModel = apiSettings.fallbackWhisperModel || "base";try {const durationSeconds = metadata.durationSeconds ?? null;@@ -1198,7 +1179,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);durationSeconds < SHORT_CLIP_DURATION_SECONDS;const model = this.getTranscriptionModel();- const provider = localStorage.getItem("cloudTranscriptionProvider") || "openai";+ const provider = apiSettings.cloudTranscriptionProvider || "openai";logger.debug("Transcription request starting",@@ -1490,7 +1471,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor););}} catch (error) {- const isOpenAIMode = localStorage.getItem("useLocalWhisper") !== "true";+ const isOpenAIMode = !getSettings().useLocalWhisper;if (allowLocalFallback && isOpenAIMode) {try {@@ -1522,17 +1503,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);getTranscriptionModel() {try {- const provider =- typeof localStorage !== "undefined"- ? localStorage.getItem("cloudTranscriptionProvider") || "openai"- : "openai";-- const model =- typeof localStorage !== "undefined"- ? localStorage.getItem("cloudTranscriptionModel") || ""- : "";-- const trimmedModel = model.trim();+ const s = getSettings();+ const provider = s.cloudTranscriptionProvider || "openai";+ const trimmedModel = (s.cloudTranscriptionModel || "").trim();// For custom provider, use whatever model is set (or fallback to whisper-1)if (provider === "custom") {@@ -1567,15 +1540,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}getTranscriptionEndpoint() {- // Get current provider and base URL to check if cache is valid- const currentProvider =- typeof localStorage !== "undefined"- ? localStorage.getItem("cloudTranscriptionProvider") || "openai"- : "openai";- const currentBaseUrl =- typeof localStorage !== "undefined"- ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""- : "";+ const s = getSettings();+ const currentProvider = s.cloudTranscriptionProvider || "openai";+ const currentBaseUrl = s.cloudTranscriptionBaseUrl || "";// Only use custom URL when provider is explicitly "custom"const isCustomEndpoint = currentProvider === "custom";@@ -1731,11 +1698,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}shouldUseStreaming(isSignedInOverride) {- const cloudTranscriptionMode =- localStorage.getItem("cloudTranscriptionMode") ||- (hasStoredByokKey() ? "byok" : "openwhispr");- const isSignedIn = isSignedInOverride ?? localStorage.getItem("isSignedIn") === "true";- const useLocalWhisper = localStorage.getItem("useLocalWhisper") === "true";+ const s = getSettings();+ const cloudTranscriptionMode = s.cloudTranscriptionMode;+ const isSignedIn = isSignedInOverride ?? s.isSignedIn;+ const useLocalWhisper = s.useLocalWhisper;const streamingDisabled = localStorage.getItem("deepgramStreaming") === "false";return (@@ -1756,7 +1722,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const [, wsResult] = await Promise.all([this.cacheMicrophoneDeviceId(),withSessionRefresh(async () => {- const warmupLang = localStorage.getItem("preferredLanguage");+ const warmupLang = getSettings().preferredLanguage;const res = await window.electronAPI.deepgramStreamingWarmup({sampleRate: 16000,language: warmupLang && warmupLang !== "auto" ? warmupLang : undefined,@@ -1925,9 +1891,15 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);});const finalCleanup = window.electronAPI.onDeepgramFinalTranscript((text) => {+ // text = accumulated final text from deepgramStreaming.+ // Extract just the new segment (delta from previous accumulated final).+ const prevLen = this.streamingFinalText.length;this.streamingFinalText = text;this.streamingPartialText = "";- this.onPartialTranscript?.(text);+ const newSegment = text.slice(prevLen);+ if (newSegment) {+ this.onStreamingCommit?.(newSegment);+ }});const errorCleanup = window.electronAPI.onDeepgramError((error) => {@@ -1963,7 +1935,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// 4. Connect WebSocket — audio is already flowing from the pipeline above,// so Deepgram receives data immediately (no idle timeout).const result = await withSessionRefresh(async () => {- const preferredLang = localStorage.getItem("preferredLanguage");+ const preferredLang = getSettings().preferredLanguage;const res = await window.electronAPI.deepgramStreamingStart({sampleRate: 16000,language: preferredLang && preferredLang !== "auto" ? preferredLang : undefined,@@ -2111,7 +2083,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}const tAudioCleanup = performance.now();- // 3. Wait for flushed buffer to travel: port → main thread → IPC → WebSocket → server.+ // 3. Wait for flushed buffer to travel: port -> main thread -> IPC -> WebSocket -> server.// Then mark streaming done so no further audio is forwarded.await new Promise((resolve) => setTimeout(resolve, 120));this.isStreaming = false;@@ -2160,21 +2132,21 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"streaming");- const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";- if (useReasoningModel && finalText) {+ const stSettings = getSettings();+ if (stSettings.useReasoningModel && finalText && !this.skipReasoning) {const reasoningStart = performance.now();const agentName = localStorage.getItem("agentName") || "";- const cloudReasoningMode = localStorage.getItem("cloudReasoningMode") || "openwhispr";+ const cloudReasoningMode = stSettings.cloudReasoningMode || "openwhispr";try {if (cloudReasoningMode === "openwhispr") {const reasonResult = await withSessionRefresh(async () => {const res = await window.electronAPI.cloudReason(finalText, {agentName,- customDictionary: this.getCustomDictionaryArray(),+ customDictionary: stSettings.customDictionary,customPrompt: this.getCustomPrompt(),- language: localStorage.getItem("preferredLanguage") || "auto",- locale: localStorage.getItem("uiLanguage") || "en",+ language: stSettings.preferredLanguage || "auto",+ locale: stSettings.uiLanguage || "en",});if (!res.success) {const err = new Error(res.error || "Cloud reasoning failed");@@ -2197,11 +2169,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"streaming");} else {- const reasoningModel = localStorage.getItem("reasoningModel") || "";- if (reasoningModel) {+ const effectiveModel = getEffectiveReasoningModel();+ if (effectiveModel) {const result = await this.processWithReasoningModel(finalText,- reasoningModel,+ effectiveModel,agentName);if (result) {@@ -2255,7 +2227,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"Streaming total processing",{totalProcessingMs: Math.round(tBeforePaste - t0),- hasReasoning: useReasoningModel,+ hasReasoning: stSettings.useReasoningModel,},"streaming");@@ -2357,6 +2329,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.onError = null;this.onTranscriptionComplete = null;this.onPartialTranscript = null;+ this.onStreamingCommit = null;if (this._onApiKeyChanged) {window.removeEventListener("api-key-changed", this._onApiKeyChanged);}diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.jsindex 4275127d6..1e12397f8 100644--- a/src/helpers/clipboard.js+++ b/src/helpers/clipboard.js@@ -792,6 +792,7 @@ class ClipboardManager {"tabby","sakura","warp",+ "termius",];// Pre-detect the target window BEFORE our window takes focus or blurs,@@ -1017,8 +1018,8 @@ class ClipboardManager {// wlroots (Sway, Hyprland, etc.): wtype is native; then xdotool for XWayland; ydotool lastcandidates = [...wtypeEntry, ...xdotoolEntry, ...ydotoolEntry];} else {- // GNOME, KDE, or unknown Wayland: xdotool for XWayland apps first; ydotool fallback; wtype last resort- candidates = [...xdotoolEntry, ...ydotoolEntry, ...wtypeEntry];+ // GNOME, KDE, or unknown Wayland: ydotool (uinput) works for all windows; xdotool for XWayland only+ candidates = [...ydotoolEntry, ...xdotoolEntry, ...wtypeEntry];}const available = candidates.filter((c) => this.commandExists(c.cmd));diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 9d9e8e6dc..fdad8f7d5 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -1,7 +1,7 @@const Database = require("better-sqlite3");const path = require("path");const fs = require("fs");-const os = require("os");+const debugLogger = require("./debugLogger");const { app } = require("electron");class DatabaseManager {@@ -18,6 +18,7 @@ class DatabaseManager {const dbPath = path.join(app.getPath("userData"), dbFileName);this.db = new Database(dbPath);+ this.db.pragma("journal_mode = WAL");this.db.exec(`CREATE TABLE IF NOT EXISTS transcriptions (@@ -36,9 +37,114 @@ class DatabaseManager {)`);+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS notes (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ title TEXT NOT NULL DEFAULT 'Untitled Note',+ content TEXT NOT NULL DEFAULT '',+ note_type TEXT NOT NULL DEFAULT 'personal',+ source_file TEXT,+ audio_duration_seconds REAL,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);++ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN enhanced_content TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN enhancement_prompt TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN enhanced_at_content_hash TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ this.db.exec(`+ CREATE TABLE IF NOT EXISTS folders (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL UNIQUE,+ is_default INTEGER NOT NULL DEFAULT 0,+ sort_order INTEGER NOT NULL DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);++ const folderCount = this.db.prepare("SELECT COUNT(*) as count FROM folders").get();+ if (folderCount.count === 0) {+ const seedFolder = this.db.prepare(+ "INSERT INTO folders (name, is_default, sort_order) VALUES (?, 1, ?)"+ );+ seedFolder.run("Personal", 0);+ seedFolder.run("Meetings", 1);+ }++ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN folder_id INTEGER REFERENCES folders(id)");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ const personalFolder = this.db+ .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")+ .get();+ if (personalFolder) {+ this.db+ .prepare("UPDATE notes SET folder_id = ? WHERE folder_id IS NULL")+ .run(personalFolder.id);+ }++ this.db.exec(`+ CREATE TABLE IF NOT EXISTS actions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ prompt TEXT NOT NULL,+ icon TEXT NOT NULL DEFAULT 'sparkles',+ is_builtin INTEGER NOT NULL DEFAULT 0,+ sort_order INTEGER NOT NULL DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);++ try {+ this.db.exec("ALTER TABLE actions ADD COLUMN translation_key TEXT");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ const actionCount = this.db.prepare("SELECT COUNT(*) as count FROM actions").get();+ if (actionCount.count === 0) {+ this.db+ .prepare(+ "INSERT INTO actions (name, description, prompt, icon, is_builtin, sort_order, translation_key) VALUES (?, ?, ?, ?, 1, 0, ?)"+ )+ .run(+ "Clean Up Notes",+ "Fix grammar, structure, and formatting",+ "Clean up grammar, improve structure, and format these notes for readability while preserving all original meaning.",+ "sparkles",+ "notes.actions.builtin.cleanupNotes"+ );+ }++ // Back-fill translation_key for existing installs+ this.db+ .prepare(+ "UPDATE actions SET translation_key = ? WHERE is_builtin = 1 AND name = ? AND translation_key IS NULL"+ )+ .run("notes.actions.builtin.cleanupNotes", "Clean Up Notes");+return true;} catch (error) {- console.error("Database initialization failed:", error.message);+ debugLogger.error("Database initialization failed", { error: error.message }, "database");throw error;}}@@ -56,7 +162,7 @@ class DatabaseManager {return { id: result.lastInsertRowid, success: true, transcription };} catch (error) {- console.error("Error saving transcription:", error.message);+ debugLogger.error("Error saving transcription", { error: error.message }, "database");throw error;}}@@ -70,7 +176,7 @@ class DatabaseManager {const transcriptions = stmt.all(limit);return transcriptions;} catch (error) {- console.error("Error getting transcriptions:", error.message);+ debugLogger.error("Error getting transcriptions", { error: error.message }, "database");throw error;}}@@ -84,7 +190,7 @@ class DatabaseManager {const result = stmt.run();return { cleared: result.changes, success: true };} catch (error) {- console.error("Error clearing transcriptions:", error.message);+ debugLogger.error("Error clearing transcriptions", { error: error.message }, "database");throw error;}}@@ -96,10 +202,9 @@ 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}`);return { success: result.changes > 0, id };} catch (error) {- console.error("❌ Error deleting transcription:", error);+ debugLogger.error("Error deleting transcription", { error: error.message }, "database");throw error;}}@@ -113,7 +218,7 @@ class DatabaseManager {const rows = stmt.all();return rows.map((row) => row.word);} catch (error) {- console.error("Error getting dictionary:", error.message);+ debugLogger.error("Error getting dictionary", { error: error.message }, "database");throw error;}}@@ -136,13 +241,297 @@ class DatabaseManager {transaction(words);return { success: true };} catch (error) {- console.error("Error setting dictionary:", error.message);+ debugLogger.error("Error setting dictionary", { error: error.message }, "database");+ throw error;+ }+ }++ saveNote(+ title,+ content,+ noteType = "personal",+ sourceFile = null,+ audioDuration = null,+ folderId = null+ ) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ if (!folderId) {+ const personal = this.db+ .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")+ .get();+ folderId = personal?.id || null;+ }+ const stmt = this.db.prepare(+ "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id) VALUES (?, ?, ?, ?, ?, ?)"+ );+ const result = stmt.run(title, content, noteType, sourceFile, audioDuration, folderId);++ const fetchStmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");+ const note = fetchStmt.get(result.lastInsertRowid);++ return { success: true, note };+ } catch (error) {+ debugLogger.error("Error saving note", { error: error.message }, "notes");+ throw error;+ }+ }++ getNote(id) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const stmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");+ return stmt.get(id) || null;+ } catch (error) {+ debugLogger.error("Error getting note", { error: error.message }, "notes");+ throw error;+ }+ }++ getNotes(noteType = null, limit = 100, folderId = null) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const conditions = [];+ const params = [];+ if (noteType) {+ conditions.push("note_type = ?");+ params.push(noteType);+ }+ if (folderId) {+ conditions.push("folder_id = ?");+ params.push(folderId);+ }+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";+ const stmt = this.db.prepare(`SELECT * FROM notes ${where} ORDER BY updated_at DESC LIMIT ?`);+ params.push(limit);+ return stmt.all(...params);+ } catch (error) {+ debugLogger.error("Error getting notes", { error: error.message }, "notes");+ throw error;+ }+ }++ updateNote(id, updates) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const allowedFields = [+ "title",+ "content",+ "enhanced_content",+ "enhancement_prompt",+ "enhanced_at_content_hash",+ "folder_id",+ ];+ const fields = [];+ const values = [];+ for (const [key, value] of Object.entries(updates)) {+ if (allowedFields.includes(key) && value !== undefined) {+ fields.push(`${key} = ?`);+ values.push(value);+ }+ }+ if (fields.length === 0) return { success: false };+ fields.push("updated_at = CURRENT_TIMESTAMP");+ values.push(id);+ const stmt = this.db.prepare(`UPDATE notes SET ${fields.join(", ")} WHERE id = ?`);+ stmt.run(...values);+ const fetchStmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");+ const note = fetchStmt.get(id);+ return { success: true, note };+ } catch (error) {+ debugLogger.error("Error updating note", { error: error.message }, "notes");+ throw error;+ }+ }++ getFolders() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM folders ORDER BY sort_order ASC, created_at ASC").all();+ } catch (error) {+ debugLogger.error("Error getting folders", { error: error.message }, "notes");+ throw error;+ }+ }++ createFolder(name) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const trimmed = (name || "").trim();+ if (!trimmed) return { success: false, error: "Folder name is required" };+ const existing = this.db.prepare("SELECT id FROM folders WHERE name = ?").get(trimmed);+ if (existing) return { success: false, error: "A folder with that name already exists" };+ const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM folders").get();+ const sortOrder = (maxOrder?.max_order ?? 0) + 1;+ const result = this.db+ .prepare("INSERT INTO folders (name, sort_order) VALUES (?, ?)")+ .run(trimmed, sortOrder);+ const folder = this.db+ .prepare("SELECT * FROM folders WHERE id = ?")+ .get(result.lastInsertRowid);+ return { success: true, folder };+ } catch (error) {+ debugLogger.error("Error creating folder", { error: error.message }, "notes");+ throw error;+ }+ }++ deleteFolder(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ if (!folder) return { success: false, error: "Folder not found" };+ if (folder.is_default) return { success: false, error: "Cannot delete default folders" };+ const personal = this.db+ .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")+ .get();+ if (personal) {+ this.db.prepare("UPDATE notes SET folder_id = ? WHERE folder_id = ?").run(personal.id, id);+ }+ this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);+ return { success: true, id };+ } catch (error) {+ debugLogger.error("Error deleting folder", { error: error.message }, "notes");+ throw error;+ }+ }++ renameFolder(id, name) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ if (!folder) return { success: false, error: "Folder not found" };+ if (folder.is_default) return { success: false, error: "Cannot rename default folders" };+ const trimmed = (name || "").trim();+ if (!trimmed) return { success: false, error: "Folder name is required" };+ const existing = this.db+ .prepare("SELECT id FROM folders WHERE name = ? AND id != ?")+ .get(trimmed, id);+ if (existing) return { success: false, error: "A folder with that name already exists" };+ this.db.prepare("UPDATE folders SET name = ? WHERE id = ?").run(trimmed, id);+ const updated = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ return { success: true, folder: updated };+ } catch (error) {+ debugLogger.error("Error renaming folder", { error: error.message }, "notes");+ throw error;+ }+ }++ getFolderNoteCounts() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db+ .prepare("SELECT folder_id, COUNT(*) as count FROM notes GROUP BY folder_id")+ .all();+ } catch (error) {+ debugLogger.error("Error getting folder note counts", { error: error.message }, "notes");+ throw error;+ }+ }++ getActions() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM actions ORDER BY sort_order ASC, created_at ASC").all();+ } catch (error) {+ debugLogger.error("Error getting actions", { error: error.message }, "notes");+ throw error;+ }+ }++ getAction(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id) || null;+ } catch (error) {+ debugLogger.error("Error getting action", { error: error.message }, "notes");+ throw error;+ }+ }++ createAction(name, description, prompt, icon = "sparkles") {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const trimmedName = (name || "").trim();+ const trimmedPrompt = (prompt || "").trim();+ if (!trimmedName) return { success: false, error: "Action name is required" };+ if (!trimmedPrompt) return { success: false, error: "Action prompt is required" };+ const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM actions").get();+ const sortOrder = (maxOrder?.max_order ?? 0) + 1;+ const result = this.db+ .prepare(+ "INSERT INTO actions (name, description, prompt, icon, sort_order) VALUES (?, ?, ?, ?, ?)"+ )+ .run(trimmedName, (description || "").trim(), trimmedPrompt, icon || "sparkles", sortOrder);+ const action = this.db+ .prepare("SELECT * FROM actions WHERE id = ?")+ .get(result.lastInsertRowid);+ return { success: true, action };+ } catch (error) {+ debugLogger.error("Error creating action", { error: error.message }, "notes");+ throw error;+ }+ }++ updateAction(id, updates) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const allowedFields = ["name", "description", "prompt", "icon", "sort_order"];+ const fields = [];+ const values = [];+ for (const [key, value] of Object.entries(updates)) {+ if (allowedFields.includes(key) && value !== undefined) {+ fields.push(`${key} = ?`);+ values.push(value);+ }+ }+ if (fields.length === 0) return { success: false };+ fields.push("updated_at = CURRENT_TIMESTAMP");+ values.push(id);+ this.db.prepare(`UPDATE actions SET ${fields.join(", ")} WHERE id = ?`).run(...values);+ const action = this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id);+ return { success: true, action };+ } catch (error) {+ debugLogger.error("Error updating action", { error: error.message }, "notes");+ throw error;+ }+ }++ deleteAction(id) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const action = this.db.prepare("SELECT * FROM actions WHERE id = ?").get(id);+ if (!action) return { success: false, error: "Action not found" };+ if (action.is_builtin) return { success: false, error: "Cannot delete built-in actions" };+ this.db.prepare("DELETE FROM actions WHERE id = ?").run(id);+ return { success: true, id };+ } catch (error) {+ debugLogger.error("Error deleting action", { error: error.message }, "notes");+ throw error;+ }+ }++ deleteNote(id) {+ try {+ if (!this.db) {+ throw new Error("Database not initialized");+ }+ const stmt = this.db.prepare("DELETE FROM notes WHERE id = ?");+ const result = stmt.run(id);+ return { success: result.changes > 0, id };+ } catch (error) {+ debugLogger.error("Error deleting note", { error: error.message }, "notes");throw error;}}cleanup() {- console.log("Starting database cleanup...");try {const dbPath = path.join(app.getPath("userData"),@@ -150,10 +539,9 @@ class DatabaseManager {);if (fs.existsSync(dbPath)) {fs.unlinkSync(dbPath);- console.log("✅ Database file deleted:", dbPath);}} catch (error) {- console.error("❌ Error deleting database file:", error);+ debugLogger.error("Error deleting database file", { error: error.message }, "database");}}}diff --git a/src/helpers/globeKeyManager.js b/src/helpers/globeKeyManager.jsindex 9e414b02f..e2884973e 100644--- a/src/helpers/globeKeyManager.js+++ b/src/helpers/globeKeyManager.js@@ -2,6 +2,7 @@ const { spawn } = require("child_process");const path = require("path");const EventEmitter = require("events");const fs = require("fs");+const debugLogger = require("./debugLogger");class GlobeKeyManager extends EventEmitter {constructor() {@@ -12,12 +13,18 @@ class GlobeKeyManager extends EventEmitter {}start() {- if (!this.isSupported || this.process) {+ if (!this.isSupported) {+ debugLogger.info("[GlobeKeyManager] Skipped — not macOS");+ return;+ }+ if (this.process) {+ debugLogger.info("[GlobeKeyManager] Skipped — already running");return;}const listenerPath = this.resolveListenerBinary();if (!listenerPath) {+ debugLogger.info("[GlobeKeyManager] Binary not found in any candidate path");this.reportError(new Error("macOS Globe listener binary not found. Run `npm run compile:globe` before packaging."@@ -26,9 +33,12 @@ class GlobeKeyManager extends EventEmitter {return;}+ debugLogger.info("[GlobeKeyManager] Binary found", { path: listenerPath });+try {fs.accessSync(listenerPath, fs.constants.X_OK);} catch {+ debugLogger.info("[GlobeKeyManager] Binary not executable, attempting chmod");try {fs.chmodSync(listenerPath, 0o755);} catch {@@ -41,6 +51,7 @@ class GlobeKeyManager extends EventEmitter {this.hasReportedError = false;this.process = spawn(listenerPath);+ debugLogger.info("[GlobeKeyManager] Process spawned", { pid: this.process.pid });this.process.stdout.setEncoding("utf8");this.process.stdout.on("data", (chunk) => {@@ -76,17 +87,19 @@ class GlobeKeyManager extends EventEmitter {this.process.stderr.on("data", (data) => {const message = data.toString().trim();if (message.length > 0) {- console.error("GlobeKeyManager stderr:", message);+ debugLogger.info("[GlobeKeyManager] stderr", { message });this.reportError(new Error(message));}});this.process.on("error", (error) => {+ debugLogger.info("[GlobeKeyManager] Process error", { error: error.message });this.reportError(error);this.process = null;});this.process.on("exit", (code, signal) => {+ debugLogger.info("[GlobeKeyManager] Process exited", { code, signal });this.process = null;if (code !== 0 && signal !== "SIGINT" && signal !== "SIGTERM") {const error = new Error(@@ -118,7 +131,7 @@ class GlobeKeyManager extends EventEmitter {this.process = null;}}- console.error("GlobeKeyManager error:", error);+ debugLogger.error("GlobeKeyManager error", { error: error.message }, "hotkey");this.emit("error", error);}diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex cdc692e9f..8dae7984b 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -36,6 +36,16 @@ function isModifierOnlyHotkey(hotkey) {return hotkey.split("+").every((part) => MODIFIER_NAMES.has(part.toLowerCase()));}+function normalizeToAccelerator(hotkey) {+ let accelerator = hotkey.startsWith("Fn+") ? hotkey.slice(3) : hotkey;+ accelerator = accelerator+ .replace(/\bRight(Command|Cmd)\b/g, "Command")+ .replace(/\bRight(Control|Ctrl)\b/g, "Control")+ .replace(/\bRight(Alt|Option)\b/g, "Alt")+ .replace(/\bRightShift\b/g, "Shift");+ return accelerator;+}+// Suggested alternative hotkeys when registration failsconst SUGGESTED_HOTKEYS = {single: ["F8", "F9", "F10", "Pause", "ScrollLock"],@@ -115,7 +125,7 @@ class HotkeyManager {// If we're already using this hotkey AND it's actually registered, return success// Note: We need to check isRegistered because on first run, currentHotkey is set to the// default value but it's not actually registered yet.- const checkAccelerator = hotkey.startsWith("Fn+") ? hotkey.slice(3) : hotkey;+ const checkAccelerator = normalizeToAccelerator(hotkey);if (hotkey === this.currentHotkey &&hotkey !== "GLOBE" &&@@ -138,9 +148,7 @@ class HotkeyManager {!isRightSideModifier(this.currentHotkey) &&!isModifierOnlyHotkey(this.currentHotkey)) {- const prevAccelerator = this.currentHotkey.startsWith("Fn+")- ? this.currentHotkey.slice(3)- : this.currentHotkey;+ const prevAccelerator = normalizeToAccelerator(this.currentHotkey);try {debugLogger.log(`[HotkeyManager] Unregistering previous hotkey: "${prevAccelerator}"`);globalShortcut.unregister(prevAccelerator);@@ -183,9 +191,7 @@ class HotkeyManager {return { success: true, hotkey };}- // Fn+ prefix is a UI-level distinction (user holds Fn to get real F-keys on macOS).- // At the OS/Electron level, the accelerator is just the key without Fn.- const accelerator = hotkey.startsWith("Fn+") ? hotkey.slice(3) : hotkey;+ const accelerator = normalizeToAccelerator(hotkey);const alreadyRegistered = globalShortcut.isRegistered(accelerator);debugLogger.log(@@ -205,7 +211,7 @@ class HotkeyManager {return { success: true, hotkey };} else {const failureInfo = this.getFailureReason(accelerator);- console.error(`[HotkeyManager] Failed to register hotkey: ${hotkey}`, failureInfo);+ debugLogger.error("Failed to register hotkey", { error: hotkey, ...failureInfo }, "hotkey");debugLogger.log(`[HotkeyManager] Registration failed:`, failureInfo);this._restorePreviousHotkey(previousHotkey, callback);@@ -225,7 +231,7 @@ class HotkeyManager {};}} catch (error) {- console.error("[HotkeyManager] Error setting up shortcuts:", error);+ debugLogger.error("Error setting up shortcuts", { error: error.message }, "hotkey");debugLogger.log(`[HotkeyManager] Exception during registration:`, error.message);this._restorePreviousHotkey(previousHotkey, callback);return { success: false, error: error.message };@@ -241,7 +247,7 @@ class HotkeyManager {) {return;}- const prevAccel = previousHotkey.startsWith("Fn+") ? previousHotkey.slice(3) : previousHotkey;+ const prevAccel = normalizeToAccelerator(previousHotkey);try {const restored = globalShortcut.register(prevAccel, callback);if (restored) {@@ -404,8 +410,7 @@ class HotkeyManager {debugLogger.log("[HotkeyManager] All hotkey fallbacks failed");this.notifyHotkeyFailure(defaultHotkey, result);} catch (err) {- console.error("Failed to initialize hotkey:", err);- debugLogger.error("[HotkeyManager] Failed to initialize hotkey:", err.message);+ debugLogger.error("Failed to initialize hotkey", { error: err.message }, "hotkey");}}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 37a27c55b..8f6450074 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -12,6 +12,77 @@ const DeepgramStreaming = require("./deepgramStreaming");const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";+const AUDIO_MIME_TYPES = {+ mp3: "audio/mpeg",+ wav: "audio/wav",+ m4a: "audio/mp4",+ webm: "audio/webm",+ ogg: "audio/ogg",+ flac: "audio/flac",+ aac: "audio/aac",+};++function buildMultipartBody(fileBuffer, fileName, contentType, fields = {}) {+ const boundary = `----OpenWhispr${Date.now()}`;+ const parts = [];++ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n` ++ `Content-Type: ${contentType}\r\n\r\n`+ );+ parts.push(fileBuffer);+ parts.push("\r\n");++ for (const [name, value] of Object.entries(fields)) {+ if (value != null) {+ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="${name}"\r\n\r\n` ++ `${value}\r\n`+ );+ }+ }++ parts.push(`--${boundary}--\r\n`);++ const bodyParts = parts.map((p) => (typeof p === "string" ? Buffer.from(p) : p));+ return { body: Buffer.concat(bodyParts), boundary };+}++function postMultipart(url, body, boundary, headers = {}) {+ const httpModule = url.protocol === "https:" ? https : http;+ return new Promise((resolve, reject) => {+ const req = httpModule.request(+ {+ hostname: url.hostname,+ port: url.port || (url.protocol === "https:" ? 443 : 80),+ path: url.pathname,+ method: "POST",+ headers: {+ "Content-Type": `multipart/form-data; boundary=${boundary}`,+ "Content-Length": body.length,+ ...headers,+ },+ },+ (res) => {+ let responseData = "";+ res.on("data", (chunk) => (responseData += chunk));+ res.on("end", () => {+ try {+ resolve({ statusCode: res.statusCode, data: JSON.parse(responseData) });+ } catch (e) {+ reject(new Error(`Invalid JSON response: ${responseData.slice(0, 200)}`));+ }+ });+ }+ );+ req.on("error", reject);+ req.write(body);+ req.end();+ });+}+class IPCHandlers {constructor(managers) {this.environmentManager = managers.environmentManager;@@ -177,6 +248,204 @@ class IPCHandlers {return this.databaseManager.setDictionary(words);});+ // Note handlers+ ipcMain.handle(+ "db-save-note",+ async (event, title, content, noteType, sourceFile, audioDuration, folderId) => {+ const result = this.databaseManager.saveNote(+ title,+ content,+ noteType,+ sourceFile,+ audioDuration,+ folderId+ );+ if (result?.success && result?.note) {+ setImmediate(() => {+ this.broadcastToWindows("note-added", result.note);+ });+ }+ return result;+ }+ );++ ipcMain.handle("db-get-note", async (event, id) => {+ return this.databaseManager.getNote(id);+ });++ ipcMain.handle("db-get-notes", async (event, noteType, limit, folderId) => {+ return this.databaseManager.getNotes(noteType, limit, folderId);+ });++ ipcMain.handle("db-update-note", async (event, id, updates) => {+ const result = this.databaseManager.updateNote(id, updates);+ if (result?.success && result?.note) {+ setImmediate(() => {+ this.broadcastToWindows("note-updated", result.note);+ });+ }+ return result;+ });++ ipcMain.handle("db-delete-note", async (event, id) => {+ const result = this.databaseManager.deleteNote(id);+ if (result?.success) {+ setImmediate(() => {+ this.broadcastToWindows("note-deleted", { id });+ });+ }+ return result;+ });++ // Folder handlers+ ipcMain.handle("db-get-folders", async () => {+ return this.databaseManager.getFolders();+ });++ ipcMain.handle("db-create-folder", async (event, name) => {+ const result = this.databaseManager.createFolder(name);+ if (result?.success && result?.folder) {+ setImmediate(() => {+ this.broadcastToWindows("folder-created", result.folder);+ });+ }+ return result;+ });++ ipcMain.handle("db-delete-folder", async (event, id) => {+ const result = this.databaseManager.deleteFolder(id);+ if (result?.success) {+ setImmediate(() => {+ this.broadcastToWindows("folder-deleted", { id });+ });+ }+ return result;+ });++ ipcMain.handle("db-rename-folder", async (event, id, name) => {+ const result = this.databaseManager.renameFolder(id, name);+ if (result?.success && result?.folder) {+ setImmediate(() => {+ this.broadcastToWindows("folder-renamed", result.folder);+ });+ }+ return result;+ });++ ipcMain.handle("db-get-folder-note-counts", async () => {+ return this.databaseManager.getFolderNoteCounts();+ });++ // Action handlers+ ipcMain.handle("db-get-actions", async () => {+ return this.databaseManager.getActions();+ });++ ipcMain.handle("db-get-action", async (event, id) => {+ return this.databaseManager.getAction(id);+ });++ ipcMain.handle("db-create-action", async (event, name, description, prompt, icon) => {+ const result = this.databaseManager.createAction(name, description, prompt, icon);+ if (result?.success && result?.action) {+ setImmediate(() => {+ this.broadcastToWindows("action-created", result.action);+ });+ }+ return result;+ });++ ipcMain.handle("db-update-action", async (event, id, updates) => {+ const result = this.databaseManager.updateAction(id, updates);+ if (result?.success && result?.action) {+ setImmediate(() => {+ this.broadcastToWindows("action-updated", result.action);+ });+ }+ return result;+ });++ ipcMain.handle("db-delete-action", async (event, id) => {+ const result = this.databaseManager.deleteAction(id);+ if (result?.success) {+ setImmediate(() => {+ this.broadcastToWindows("action-deleted", { id });+ });+ }+ return result;+ });++ ipcMain.handle("export-note", async (event, noteId, format) => {+ try {+ const note = this.databaseManager.getNote(noteId);+ if (!note) return { success: false, error: "Note not found" };++ const { dialog } = require("electron");+ const fs = require("fs");+ const ext = format === "txt" ? "txt" : "md";+ const safeName = (note.title || "Untitled").replace(/[/\\?%*:|"<>]/g, "-");++ const result = await dialog.showSaveDialog({+ defaultPath: `${safeName}.${ext}`,+ filters: [+ { name: "Markdown", extensions: ["md"] },+ { name: "Text", extensions: ["txt"] },+ ],+ });++ if (result.canceled || !result.filePath) return { success: false };++ let exportContent;+ if (format === "txt") {+ exportContent = (note.content || "")+ .replace(/#{1,6}\s+/g, "")+ .replace(/[*_~`]+/g, "")+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")+ .replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1")+ .replace(/^>\s+/gm, "")+ .trim();+ } else {+ exportContent = note.enhanced_content || note.content;+ }++ fs.writeFileSync(result.filePath, exportContent, "utf-8");+ return { success: true };+ } catch (error) {+ debugLogger.error("Error exporting note", { error: error.message }, "notes");+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("select-audio-file", async () => {+ const { dialog } = require("electron");+ const result = await dialog.showOpenDialog({+ properties: ["openFile"],+ filters: [+ { name: "Audio Files", extensions: ["mp3", "wav", "m4a", "webm", "ogg", "flac", "aac"] },+ ],+ });+ if (result.canceled || !result.filePaths.length) {+ return { canceled: true };+ }+ return { canceled: false, filePath: result.filePaths[0] };+ });++ ipcMain.handle("transcribe-audio-file", async (event, filePath, options = {}) => {+ const fs = require("fs");+ try {+ const audioBuffer = fs.readFileSync(filePath);+ if (options.provider === "nvidia") {+ const result = await this.parakeetManager.transcribeLocalParakeet(audioBuffer, options);+ return result;+ }+ const result = await this.whisperManager.transcribeLocalWhisper(audioBuffer, options);+ return result;+ } catch (error) {+ debugLogger.error("Audio file transcription error", { error: error.message });+ return { success: false, error: error.message };+ }+ });+// Clipboard handlersipcMain.handle("paste-text", async (event, text, options) => {// If the floating dictation panel currently has focus, blur it first so the@@ -476,12 +745,8 @@ class IPCHandlers {// Utility handlersipcMain.handle("cleanup-app", async (event) => {- try {- AppUtils.cleanup(this.windowManager.mainWindow);- return { success: true, message: "Cleanup completed successfully" };- } catch (error) {- throw error;- }+ AppUtils.cleanup(this.windowManager.mainWindow);+ return { success: true, message: "Cleanup completed successfully" };});ipcMain.handle("update-hotkey", async (event, hotkey) => {@@ -1211,56 +1476,13 @@ class IPCHandlers {if (!cookieHeader) throw new Error("No session cookies available");const audioData = Buffer.from(audioBuffer);- const boundary = `----OpenWhispr${Date.now()}`;- const parts = [];-- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="file"; filename="audio.webm"\r\n` +- `Content-Type: audio/webm\r\n\r\n`- );- parts.push(audioData);- parts.push("\r\n");-- if (opts.language) {- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="language"\r\n\r\n` +- `${opts.language}\r\n`- );- }-- if (opts.prompt) {- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="prompt"\r\n\r\n` +- `${opts.prompt}\r\n`- );- }-- // Add client metadata for logging- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="clientType"\r\n\r\n` +- `desktop\r\n`- );-- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="appVersion"\r\n\r\n` +- `${app.getVersion()}\r\n`- );-- parts.push(- `--${boundary}\r\n` +- `Content-Disposition: form-data; name="sessionId"\r\n\r\n` +- `${this.sessionId}\r\n`- );-- parts.push(`--${boundary}--\r\n`);-- const bodyParts = parts.map((p) => (typeof p === "string" ? Buffer.from(p) : p));- const body = Buffer.concat(bodyParts);+ const { body, boundary } = buildMultipartBody(audioData, "audio.webm", "audio/webm", {+ language: opts.language,+ prompt: opts.prompt,+ clientType: "desktop",+ appVersion: app.getVersion(),+ sessionId: this.sessionId,+ });debugLogger.debug("Cloud transcribe request",@@ -1269,38 +1491,7 @@ class IPCHandlers {);const url = new URL(`${apiUrl}/api/transcribe`);- const httpModule = url.protocol === "https:" ? https : http;-- const data = await new Promise((resolve, reject) => {- const req = httpModule.request(- {- hostname: url.hostname,- port: url.port || (url.protocol === "https:" ? 443 : 80),- path: url.pathname,- method: "POST",- headers: {- "Content-Type": `multipart/form-data; boundary=${boundary}`,- "Content-Length": body.length,- Cookie: cookieHeader,- },- },- (res) => {- let responseData = "";- res.on("data", (chunk) => (responseData += chunk));- res.on("end", () => {- try {- const parsed = JSON.parse(responseData);- resolve({ statusCode: res.statusCode, data: parsed });- } catch (e) {- reject(new Error(`Invalid JSON response: ${responseData.slice(0, 200)}`));- }- });- }- );- req.on("error", reject);- req.write(body);- req.end();- });+ const data = await postMultipart(url, body, boundary, { Cookie: cookieHeader });debugLogger.debug("Cloud transcribe response",@@ -1343,23 +1534,19 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- console.log("[cloud-reason] ⬇ IPC called", {- apiUrl,- model: opts.model || "(default)",- agentName: opts.agentName || "(none)",- language: opts.language || "(auto)",- locale: opts.locale || "en",- hasCustomPrompt: !!opts.customPrompt,- textLength: text?.length || 0,- textPreview: text?.substring(0, 80) || "(empty)",- });-const cookieHeader = await getSessionCookies(event);if (!cookieHeader) throw new Error("No session cookies available");- console.log(`[cloud-reason] → Fetching ${apiUrl}/api/reason ...`);+ debugLogger.debug(+ "Cloud reason request",+ {+ model: opts.model || "(default)",+ agentName: opts.agentName || "(none)",+ textLength: text?.length || 0,+ },+ "cloud-api"+ );- const fetchStart = Date.now();const response = await fetch(`${apiUrl}/api/reason`, {method: "POST",headers: {@@ -1372,6 +1559,7 @@ class IPCHandlers {agentName: opts.agentName,customDictionary: opts.customDictionary,customPrompt: opts.customPrompt,+ systemPrompt: opts.systemPrompt,language: opts.language,locale: opts.locale,sessionId: this.sessionId,@@ -1379,35 +1567,27 @@ class IPCHandlers {appVersion: app.getVersion(),}),});- const fetchMs = Date.now() - fetchStart;-- console.log("[cloud-reason] ← Response", {- status: response.status,- ok: response.ok,- fetchMs,- });if (!response.ok) {if (response.status === 401) {- console.log("[cloud-reason] ✗ 401 - session expired");return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };}const errorData = await response.json().catch(() => ({}));- console.log("[cloud-reason] ✗ API error", { status: response.status, errorData });throw new Error(errorData.error || `API error: ${response.status}`);}const data = await response.json();- console.log("[cloud-reason] ✓ Success", {- model: data.model,- provider: data.provider,- processingMs: data.processingMs,- resultLength: data.text?.length || 0,- resultPreview: data.text?.substring(0, 80) || "(empty)",- });+ debugLogger.debug(+ "Cloud reason response",+ {+ model: data.model,+ provider: data.provider,+ resultLength: data.text?.length || 0,+ },+ "cloud-api"+ );return { success: true, text: data.text, model: data.model, provider: data.provider };} catch (error) {- console.log("[cloud-reason] ✗ Error:", error.message);debugLogger.error("Cloud reasoning error:", error);return { success: false, error: error.message };}@@ -1440,7 +1620,7 @@ class IPCHandlers {}});- const fetchStripeUrl = async (event, endpoint, errorPrefix) => {+ const fetchStripeUrl = async (event, endpoint, errorPrefix, body) => {try {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");@@ -1448,10 +1628,14 @@ class IPCHandlers {const cookieHeader = await getSessionCookies(event);if (!cookieHeader) throw new Error("No session cookies available");- const response = await fetch(`${apiUrl}${endpoint}`, {- method: "POST",- headers: { Cookie: cookieHeader },- });+ const headers = { Cookie: cookieHeader };+ const fetchOpts = { method: "POST", headers };+ if (body) {+ headers["Content-Type"] = "application/json";+ fetchOpts.body = JSON.stringify(body);+ }++ const response = await fetch(`${apiUrl}${endpoint}`, fetchOpts);if (!response.ok) {if (response.status === 401) {@@ -1469,14 +1653,215 @@ class IPCHandlers {}};- ipcMain.handle("cloud-checkout", (event) =>- fetchStripeUrl(event, "/api/stripe/checkout", "Cloud checkout error")+ ipcMain.handle("cloud-checkout", (event, plan) =>+ fetchStripeUrl(+ event,+ "/api/stripe/checkout",+ "Cloud checkout error",+ plan ? { plan } : undefined+ ));ipcMain.handle("cloud-billing-portal", (event) =>fetchStripeUrl(event, "/api/stripe/portal", "Cloud billing portal error"));+ ipcMain.handle("transcribe-audio-file-cloud", async (event, filePath) => {+ const fs = require("fs");+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) throw new Error("No session cookies available");++ const audioBuffer = fs.readFileSync(filePath);+ const ext = path.extname(filePath).toLowerCase().replace(".", "");+ const contentType = AUDIO_MIME_TYPES[ext] || "audio/mpeg";+ const fileName = path.basename(filePath);++ const { body, boundary } = buildMultipartBody(audioBuffer, fileName, contentType, {+ source: "file_upload",+ clientType: "desktop",+ appVersion: app.getVersion(),+ sessionId: this.sessionId,+ });++ const url = new URL(`${apiUrl}/api/transcribe`);+ const data = await postMultipart(url, body, boundary, { Cookie: cookieHeader });++ if (data.statusCode === 401) {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ if (data.statusCode === 429) {+ return {+ success: false,+ error: "Daily word limit reached",+ code: "LIMIT_REACHED",+ ...data.data,+ };+ }+ if (data.statusCode !== 200) {+ throw new Error(data.data?.error || `API error: ${data.statusCode}`);+ }++ return { success: true, text: data.data.text };+ } catch (error) {+ debugLogger.error("Cloud audio file transcription error", { error: error.message });+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle(+ "transcribe-audio-file-byok",+ async (event, { filePath, apiKey, baseUrl, model }) => {+ const fs = require("fs");+ try {+ if (!apiKey) throw new Error("No API key configured. Add your key in Settings.");+ if (!baseUrl) throw new Error("No transcription endpoint configured.");++ const audioBuffer = fs.readFileSync(filePath);+ const ext = path.extname(filePath).toLowerCase().replace(".", "");+ const contentType = AUDIO_MIME_TYPES[ext] || "audio/mpeg";+ const fileName = path.basename(filePath);++ let transcriptionUrl = baseUrl.replace(/\/+$/, "");+ if (!transcriptionUrl.endsWith("/audio/transcriptions")) {+ transcriptionUrl += "/audio/transcriptions";+ }++ const { body, boundary } = buildMultipartBody(audioBuffer, fileName, contentType, {+ model: model || "whisper-1",+ });++ const url = new URL(transcriptionUrl);+ const data = await postMultipart(url, body, boundary, {+ Authorization: `Bearer ${apiKey}`,+ });++ if (data.statusCode === 401) {+ return { success: false, error: "Invalid API key. Check your key in Settings." };+ }+ if (data.statusCode === 429) {+ return { success: false, error: "Rate limit exceeded. Please try again later." };+ }+ if (data.statusCode !== 200) {+ throw new Error(+ data.data?.error?.message || data.data?.error || `API error: ${data.statusCode}`+ );+ }++ return { success: true, text: data.data.text };+ } catch (error) {+ debugLogger.error("BYOK audio file transcription error", { error: error.message });+ return { success: false, error: error.message };+ }+ }+ );++ // Referral stats handler+ ipcMain.handle("get-referral-stats", async (event) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ throw new Error("OpenWhispr API URL not configured");+ }++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) {+ throw new Error("No session cookies available");+ }++ const response = await fetch(`${apiUrl}/api/referrals/stats`, {+ headers: {+ Cookie: cookieHeader,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 401) {+ throw new Error("Unauthorized - please sign in");+ }+ throw new Error(`Failed to fetch referral stats: ${response.status}`);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ debugLogger.error("Error fetching referral stats:", error);+ throw error;+ }+ });++ ipcMain.handle("send-referral-invite", async (event, email) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ throw new Error("OpenWhispr API URL not configured");+ }++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) {+ throw new Error("No session cookies available");+ }++ const response = await fetch(`${apiUrl}/api/referrals/invite`, {+ method: "POST",+ headers: {+ Cookie: cookieHeader,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ email }),+ });++ const data = await response.json();++ if (!response.ok) {+ throw new Error(data.error || `Failed to send invite: ${response.status}`);+ }++ return data;+ } catch (error) {+ debugLogger.error("Error sending referral invite:", error);+ throw error;+ }+ });++ ipcMain.handle("get-referral-invites", async (event) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ throw new Error("OpenWhispr API URL not configured");+ }++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) {+ throw new Error("No session cookies available");+ }++ const response = await fetch(`${apiUrl}/api/referrals/invites`, {+ headers: {+ Cookie: cookieHeader,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 401) {+ throw new Error("Unauthorized - please sign in");+ }+ throw new Error(`Failed to fetch referral invites: ${response.status}`);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ debugLogger.error("Error fetching referral invites:", error);+ throw error;+ }+ });+ipcMain.handle("open-whisper-models-folder", async () => {try {const modelsDir = this.whisperManager.getModelsDir();diff --git a/src/helpers/llamaServer.js b/src/helpers/llamaServer.jsindex 3728282e9..2d4512c01 100644--- a/src/helpers/llamaServer.js+++ b/src/helpers/llamaServer.js@@ -159,6 +159,7 @@ class LlamaServerManager {let stderrBuffer = "";let exitCode = null;+ let exitSignal = null;this.process.stdout.on("data", (data) => {debugLogger.debug("llama-server stdout", { data: data.toString().trim() });@@ -174,15 +175,16 @@ class LlamaServerManager {this.ready = false;});- this.process.on("close", (code) => {+ this.process.on("close", (code, signal) => {exitCode = code;- debugLogger.debug("llama-server process exited", { code });+ exitSignal = signal;+ debugLogger.debug("llama-server process exited", { code, signal });this.ready = false;this.process = null;this.stopHealthCheck();});- await this.waitForReady(() => ({ stderr: stderrBuffer, exitCode }));+ await this.waitForReady(() => ({ stderr: stderrBuffer, exitCode, exitSignal }));this.startHealthCheck();debugLogger.info("llama-server started successfully", {@@ -198,9 +200,20 @@ class LlamaServerManager {while (Date.now() - startTime < STARTUP_TIMEOUT_MS) {if (!this.process || this.process.killed) {const info = getProcessInfo ? getProcessInfo() : {};- const stderr = info.stderr ? info.stderr.trim().slice(0, 500) : "";- const details = stderr || (info.exitCode !== null ? `exit code: ${info.exitCode}` : "");- throw new Error(`llama-server process died during startup${details ? `: ${details}` : ""}`);+ const signal = info.exitSignal;+ const diagParts = [];+ if (signal) diagParts.push(`signal: ${signal}`);+ else if (info.exitCode !== null && info.exitCode !== undefined)+ diagParts.push(`exit code: ${info.exitCode}`);+ const oomHint =+ signal === "SIGKILL"+ ? " — the process was killed by the OS, likely due to insufficient memory. Try a smaller/more quantized model, or reduce the context size."+ : "";+ const stderr = info.stderr ? info.stderr.trim().slice(-800) : "";+ const diagStr = diagParts.length ? ` (${diagParts.join(", ")})` : "";+ throw new Error(+ `llama-server process died during startup${diagStr}${oomHint}${stderr ? `\nProcess output: ${stderr}` : ""}`+ );}pollCount++;diff --git a/src/helpers/parakeetWsServer.js b/src/helpers/parakeetWsServer.jsindex 5eafbced6..e71b82c5e 100644--- a/src/helpers/parakeetWsServer.js+++ b/src/helpers/parakeetWsServer.js@@ -76,7 +76,7 @@ class ParakeetWsServer {`--decoder=${path.join(modelDir, "decoder.int8.onnx")}`,`--joiner=${path.join(modelDir, "joiner.int8.onnx")}`,`--port=${this.port}`,- `--num-threads=${Math.max(1, Math.floor(os.cpus().length * 0.75))}`,+ `--num-threads=${Math.max(1, Math.min(4, Math.floor(os.cpus().length * 0.75)))}`,];debugLogger.debug("Starting parakeet WS server", { port: this.port, modelName, args });diff --git a/src/helpers/tray.js b/src/helpers/tray.jsindex c91786458..d9b13cdd3 100644--- a/src/helpers/tray.js+++ b/src/helpers/tray.js@@ -1,6 +1,7 @@const { Tray, Menu, nativeImage, app } = require("electron");const path = require("path");const fs = require("fs");+const debugLogger = require("./debugLogger");const { i18nMain } = require("./i18nMain");class TrayManager {@@ -96,19 +97,17 @@ class TrayManager {return;}- console.error("No control panel callback available");+ debugLogger.error("No control panel callback available", undefined, "tray");} catch (error) {- console.error("Failed to open control panel:", error);+ debugLogger.error("Failed to open control panel", { error: error?.message }, "tray");}}async createTray() {- if (process.platform !== "darwin" && process.platform !== "win32") return;-try {const trayIcon = await this.loadTrayIcon();if (!trayIcon || trayIcon.isEmpty()) {- console.error("Failed to load tray icon");+ debugLogger.error("Failed to load tray icon", undefined, "tray");return;}@@ -121,7 +120,7 @@ class TrayManager {this.updateTrayMenu();this.setupTrayEventHandlers();} catch (error) {- console.error("Error creating tray icon:", error.message);+ debugLogger.error("Error creating tray icon", { error: error.message }, "tray");}}@@ -175,16 +174,20 @@ class TrayManager {if (platform === "darwin") {icon.setTemplateImage(true);}- console.log("Using tray icon:", testPath);+ debugLogger.debug("Using tray icon", { path: testPath }, "tray");return icon;}}} catch (error) {- console.error("Error checking tray icon path:", testPath, error.message);+ debugLogger.error(+ "Error checking tray icon path",+ { path: testPath, error: error.message },+ "tray"+ );}}- console.error("Could not find tray icon in any expected location");+ debugLogger.error("Could not find tray icon in any expected location", undefined, "tray");return this.createFallbackIcon();}@@ -202,10 +205,10 @@ class TrayManager {const buffer = canvas.toBuffer("image/png");const fallbackIcon = nativeImage.createFromBuffer(buffer);- console.log("✅ Created fallback tray icon");+ debugLogger.info("Created fallback tray icon", undefined, "tray");return fallbackIcon;} catch (fallbackError) {- console.warn("Canvas not available, creating minimal fallback icon");+ debugLogger.warn("Canvas not available, creating minimal fallback icon", undefined, "tray");// Create a minimal 16x16 black square PNG as fallbackconst pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,@@ -216,7 +219,7 @@ class TrayManager {]);const fallbackIcon = nativeImage.createFromBuffer(pngData);- console.log("✅ Created minimal fallback tray icon");+ debugLogger.info("Created minimal fallback tray icon", undefined, "tray");return fallbackIcon;}}@@ -249,7 +252,7 @@ class TrayManager {{label: i18nMain.t("tray.quit"),click: () => {- console.log("Quitting app via tray menu");+ debugLogger.info("Quitting app via tray menu", undefined, "tray");app.quit();},},@@ -269,21 +272,14 @@ class TrayManager {return;}- if (process.platform === "win32") {+ if (process.platform !== "darwin") {this.tray.on("click", () => {void this.showControlPanelFromTray();});- this.tray.on("right-click", () => {- this.tray?.popUpContextMenu();- });- } else {- this.tray.on("click", () => {- this.tray?.popUpContextMenu();- });}this.tray.on("destroyed", () => {- console.log("Tray icon destroyed");+ debugLogger.debug("Tray icon destroyed", undefined, "tray");this.tray = null;});}diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 865193f69..a22212af3 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -1,4 +1,5 @@const { app, screen, BrowserWindow, shell, dialog } = require("electron");+const debugLogger = require("./debugLogger");const HotkeyManager = require("./hotkeyManager");const DragManager = require("./dragManager");const MenuManager = require("./menuManager");@@ -209,7 +210,7 @@ class WindowManager {const safetyTimeoutId = setTimeout(() => {if (this.macCompoundPushState?.active) {- console.warn("[WindowManager] Compound PTT safety timeout triggered - stopping recording");+ debugLogger.warn("Compound PTT safety timeout", undefined, "ptt");this.forceStopMacCompoundPush("timeout");}}, MAX_PUSH_DURATION_MS);@@ -287,6 +288,8 @@ class WindowManager {switch (part) {case "Command":case "Cmd":+ case "RightCommand":+ case "RightCmd":case "CommandOrControl":case "Super":case "Meta":@@ -294,13 +297,18 @@ class WindowManager {break;case "Control":case "Ctrl":+ case "RightControl":+ case "RightCtrl":required.add("control");break;case "Alt":case "Option":+ case "RightAlt":+ case "RightOption":required.add("option");break;case "Shift":+ case "RightShift":required.add("shift");break;case "Fn":@@ -495,11 +503,7 @@ class WindowManager {this.controlPanelWindow.on("close", (event) => {if (!this.isQuitting) {event.preventDefault();- if (process.platform === "darwin") {- this.hideControlPanelToTray();- } else {- this.controlPanelWindow.minimize();- }+ this.hideControlPanelToTray();}});diff --git a/src/hooks/useActionProcessing.ts b/src/hooks/useActionProcessing.tsnew file mode 100644index 000000000..107f22ae3--- /dev/null+++ b/src/hooks/useActionProcessing.ts@@ -0,0 +1,89 @@+import { useState, useEffect, useRef, useCallback } from "react";+import reasoningService from "../services/ReasoningService";+import type { ActionItem } from "../types/electron";+import { getEffectiveReasoningModel } from "../stores/settingsStore";++export type ActionProcessingState = "idle" | "processing" | "success";++const BASE_SYSTEM_PROMPT =+ "You are a note enhancement assistant. The user will provide raw notes — possibly voice-transcribed, rough, or unstructured. Your job is to clean them up according to the instructions below while preserving all original meaning and information. Output clean markdown.\n\nInstructions: ";++interface UseActionProcessingOptions {+ onSuccess: (enhancedContent: string, prompt: string) => void;+ onError: (errorMessage: string) => void;+}++export function useActionProcessing({ onSuccess, onError }: UseActionProcessingOptions) {+ const [state, setState] = useState<ActionProcessingState>("idle");+ const [actionName, setActionName] = useState<string | null>(null);+ const cancelledRef = useRef(false);+ const successTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const processingRef = useRef(false);++ useEffect(() => {+ return () => {+ if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);+ };+ }, []);++ const runAction = useCallback(+ async (+ action: ActionItem,+ noteContent: string,+ options: { isCloudMode: boolean; modelId: string }+ ) => {+ if (processingRef.current) return;++ const modelId = getEffectiveReasoningModel() || options.modelId;++ if (!modelId && !options.isCloudMode) {+ onError("No AI model selected. Configure one in Settings.");+ return;+ }++ cancelledRef.current = false;+ processingRef.current = true;+ setActionName(action.name);+ setState("processing");++ try {+ const systemPrompt = BASE_SYSTEM_PROMPT + action.prompt;+ const enhanced = await reasoningService.processText(noteContent, modelId, null, {+ systemPrompt,+ temperature: 0.3,+ });++ if (cancelledRef.current) return;++ setState("success");+ onSuccess(enhanced, action.prompt);++ successTimeoutRef.current = setTimeout(() => {+ processingRef.current = false;+ setState("idle");+ setActionName(null);+ }, 600);+ } catch (err) {+ if (cancelledRef.current) return;+ processingRef.current = false;+ setState("idle");+ setActionName(null);+ onError(err instanceof Error ? err.message : "Action failed");+ }+ },+ [onSuccess, onError]+ );++ const cancel = useCallback(() => {+ cancelledRef.current = true;+ processingRef.current = false;+ if (successTimeoutRef.current) {+ clearTimeout(successTimeoutRef.current);+ successTimeoutRef.current = null;+ }+ setState("idle");+ setActionName(null);+ }, []);++ return { state, actionName, runAction, cancel };+}diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex dcaae77f9..af2fdbfbd 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -3,6 +3,8 @@ import { useTranslation } from "react-i18next";import AudioManager from "../helpers/audioManager";import logger from "../utils/logger";import { playStartCue, playStopCue } from "../utils/dictationCues";+import { getSettings } from "../stores/settingsStore";+import { getRecordingErrorTitle } from "../utils/recordingErrors";export const useAudioRecording = (toast, options = {}) => {const { t } = useTranslation();@@ -78,16 +80,7 @@ export const useAudioRecording = (toast, options = {}) => {}},onError: (error) => {- // Provide specific titles for cloud error codes- const title =- error.code === "AUTH_EXPIRED"- ? t("hooks.audioRecording.errorTitles.sessionExpired")- : error.code === "OFFLINE"- ? t("hooks.audioRecording.errorTitles.offline")- : error.code === "LIMIT_REACHED"- ? t("hooks.audioRecording.errorTitles.dailyLimitReached")- : error.title;-+ const title = getRecordingErrorTitle(error, t);toast({title,description: error.description,@@ -120,7 +113,7 @@ export const useAudioRecording = (toast, options = {}) => {audioManagerRef.current.saveTranscription(result.text);- if (result.source === "openai" && localStorage.getItem("useLocalWhisper") === "true") {+ if (result.source === "openai" && getSettings().useLocalWhisper) {toast({title: t("hooks.audioRecording.fallback.title"),description: t("hooks.audioRecording.fallback.description"),diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.tsindex 801bcf775..68c6db302 100644--- a/src/hooks/useAuth.ts+++ b/src/hooks/useAuth.ts@@ -1,6 +1,7 @@import { useEffect, useRef } from "react";import { authClient, isWithinGracePeriod } from "../lib/neonAuth";import logger from "../utils/logger";+import { useSettingsStore } from "../stores/settingsStore";const useStaticSession = () => ({data: null,@@ -16,24 +17,21 @@ export function useAuth() {const rawIsSignedIn = Boolean(user);const gracePeriodActive = isWithinGracePeriod();- // CRITICAL: During the grace period after OAuth, session cookies may not- // be fully established yet. The Neon Auth SDK's useSession hook can return- // null during this time, but we should NOT report signed out to the UI.- // Instead, we keep reporting signed in and let withSessionRefresh handle retries.+ // Only sync true to the store — signOut() handles setting false via localStorage + reload.+ // The Neon SDK's useSession() flickers in Electron (renderer can't access main process cookies).const isSignedIn = rawIsSignedIn || gracePeriodActive;- // Track last synced state to prevent duplicate syncs- const lastSyncedStateRef = useRef<boolean | null>(null);+ const lastSyncedRef = useRef(false);useEffect(() => {- if (!isPending && lastSyncedStateRef.current !== isSignedIn) {+ if (!isPending && isSignedIn && !lastSyncedRef.current) {logger.debug("Auth state sync",{ isSignedIn, rawIsSignedIn, gracePeriod: gracePeriodActive },"auth");- localStorage.setItem("isSignedIn", String(isSignedIn));- lastSyncedStateRef.current = isSignedIn;+ useSettingsStore.getState().setIsSignedIn(true);+ lastSyncedRef.current = true;}}, [isSignedIn, rawIsSignedIn, gracePeriodActive, isPending]);diff --git a/src/hooks/useFolderManagement.ts b/src/hooks/useFolderManagement.tsnew file mode 100644index 000000000..dcbd2ca3c--- /dev/null+++ b/src/hooks/useFolderManagement.ts@@ -0,0 +1,225 @@+import { useState, useEffect, useRef, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { useToast } from "../components/ui/Toast";+import type { FolderItem } from "../types/electron";+import {+ useActiveFolderId,+ setActiveFolderId,+ setActiveNoteId,+ getActiveFolderIdValue,+ getActiveNoteIdValue,+ initializeNotes,+} from "../stores/noteStore";++export interface UseFolderManagementReturn {+ folders: FolderItem[];+ folderCounts: Record<number, number>;+ isLoading: boolean;+ isCreatingFolder: boolean;+ newFolderName: string;+ renamingFolderId: number | null;+ renameValue: string;+ showAddNotesDialog: boolean;+ newFolderInputRef: React.RefObject<HTMLInputElement>;+ renameInputRef: React.RefObject<HTMLInputElement>;+ setIsCreatingFolder: (v: boolean) => void;+ setNewFolderName: (v: string) => void;+ setRenamingFolderId: (id: number | null) => void;+ setRenameValue: (v: string) => void;+ setShowAddNotesDialog: (v: boolean) => void;+ loadFolders: () => Promise<FolderItem[]>;+ handleCreateFolder: () => Promise<void>;+ handleConfirmRename: () => Promise<void>;+ handleDeleteFolder: (id: number) => Promise<void>;+}++export function useFolderManagement(): UseFolderManagementReturn {+ const { t } = useTranslation();+ const { toast } = useToast();+ const activeFolderId = useActiveFolderId();++ const [folders, setFolders] = useState<FolderItem[]>([]);+ const [folderCounts, setFolderCounts] = useState<Record<number, number>>({});+ const [isLoading, setIsLoading] = useState(true);+ const [isCreatingFolder, setIsCreatingFolder] = useState(false);+ const [newFolderName, setNewFolderName] = useState("");+ const [renamingFolderId, setRenamingFolderId] = useState<number | null>(null);+ const [renameValue, setRenameValue] = useState("");+ const [showAddNotesDialog, setShowAddNotesDialog] = useState(false);++ const newFolderInputRef = useRef<HTMLInputElement>(null);+ const renameInputRef = useRef<HTMLInputElement>(null);+ const prevFolderIdRef = useRef<number | null>(null);+ const isMountedRef = useRef(true);++ const loadFolders = useCallback(async () => {+ try {+ const [items, counts] = await Promise.all([+ window.electronAPI.getFolders(),+ window.electronAPI.getFolderNoteCounts(),+ ]);+ if (!isMountedRef.current) return items;+ setFolders(items);+ const countMap: Record<number, number> = {};+ counts.forEach((c) => {+ countMap[c.folder_id] = c.count;+ });+ setFolderCounts(countMap);+ return items;+ } catch {+ return [];+ }+ }, []);++ // Load folders on mount, determine initial active folder+ useEffect(() => {+ const load = async () => {+ try {+ setIsLoading(true);+ const items = await loadFolders();+ if (!isMountedRef.current) return;++ // Respect pre-set activeFolderId (e.g., navigating from "Open Note")+ const presetFolderId = getActiveFolderIdValue();+ const isPresetValid = presetFolderId != null && items.some((f) => f.id === presetFolderId);++ const initialFolderId = isPresetValid+ ? presetFolderId+ : (items.find((f) => f.name === "Personal" && f.is_default)?.id ?? items[0]?.id ?? null);++ if (initialFolderId !== presetFolderId) {+ setActiveFolderId(initialFolderId);+ }+ if (initialFolderId) {+ const notes = await initializeNotes(null, 50, initialFolderId);+ if (!isMountedRef.current) return;+ const presetNoteId = getActiveNoteIdValue();+ if (!presetNoteId && notes.length > 0) {+ setActiveNoteId(notes[0].id);+ }+ }+ prevFolderIdRef.current = initialFolderId;+ } finally {+ if (isMountedRef.current) setIsLoading(false);+ }+ };+ load();+ return () => {+ isMountedRef.current = false;+ };+ }, []);++ // Re-initialize notes when active folder changes+ useEffect(() => {+ if (!activeFolderId || isLoading) return;+ // Skip if folder hasn't changed (e.g., initial load completing)+ if (prevFolderIdRef.current === activeFolderId) return;+ prevFolderIdRef.current = activeFolderId;+ const loadForFolder = async () => {+ const notes = await initializeNotes(null, 50, activeFolderId);+ setActiveNoteId(notes.length > 0 ? notes[0].id : null);+ };+ loadForFolder();+ }, [activeFolderId, isLoading]);++ // Focus new folder input when creating+ useEffect(() => {+ if (isCreatingFolder && newFolderInputRef.current) {+ newFolderInputRef.current.focus();+ }+ }, [isCreatingFolder]);++ // Focus rename input when renaming+ useEffect(() => {+ if (renamingFolderId && renameInputRef.current) {+ renameInputRef.current.focus();+ renameInputRef.current.select();+ }+ }, [renamingFolderId]);++ const handleCreateFolder = useCallback(async () => {+ const trimmed = newFolderName.trim();+ if (!trimmed) {+ setIsCreatingFolder(false);+ setNewFolderName("");+ return;+ }+ const result = await window.electronAPI.createFolder(trimmed);+ if (result.success && result.folder) {+ await loadFolders();+ setActiveFolderId(result.folder.id);+ } else if (result.error) {+ toast({+ title: t("notes.folders.couldNotCreate"),+ description: result.error,+ variant: "destructive",+ });+ }+ setIsCreatingFolder(false);+ setNewFolderName("");+ }, [newFolderName, loadFolders, toast, t]);++ const handleConfirmRename = useCallback(async () => {+ if (!renamingFolderId) return;+ const trimmed = renameValue.trim();+ if (!trimmed) {+ setRenamingFolderId(null);+ setRenameValue("");+ return;+ }+ const result = await window.electronAPI.renameFolder(renamingFolderId, trimmed);+ if (result.success) {+ await loadFolders();+ } else if (result.error) {+ toast({+ title: t("notes.folders.couldNotRename"),+ description: result.error,+ variant: "destructive",+ });+ }+ setRenamingFolderId(null);+ setRenameValue("");+ }, [renamingFolderId, renameValue, loadFolders, toast, t]);++ const handleDeleteFolder = useCallback(+ async (folderId: number) => {+ const result = await window.electronAPI.deleteFolder(folderId);+ if (result.success) {+ const personalFolder = folders.find((f) => f.name === "Personal" && f.is_default);+ if (activeFolderId === folderId && personalFolder) {+ setActiveFolderId(personalFolder.id);+ }+ await loadFolders();+ } else if (result.error) {+ toast({+ title: t("notes.folders.couldNotDelete"),+ description: result.error,+ variant: "destructive",+ });+ }+ },+ [folders, activeFolderId, loadFolders, toast, t]+ );++ return {+ folders,+ folderCounts,+ isLoading,+ isCreatingFolder,+ newFolderName,+ renamingFolderId,+ renameValue,+ showAddNotesDialog,+ newFolderInputRef,+ renameInputRef,+ setIsCreatingFolder,+ setNewFolderName,+ setRenamingFolderId,+ setRenameValue,+ setShowAddNotesDialog,+ loadFolders,+ handleCreateFolder,+ handleConfirmRename,+ handleDeleteFolder,+ };+}diff --git a/src/hooks/useHotkey.js b/src/hooks/useHotkey.jsindex b43c9e36a..281fe6935 100644--- a/src/hooks/useHotkey.js+++ b/src/hooks/useHotkey.js@@ -1,18 +1,9 @@-import { useState, useEffect } from "react";+import { useSettingsStore } from "../stores/settingsStore";import { getDefaultHotkey } from "../utils/hotkeys";export const useHotkey = () => {- const [hotkey, setHotkey] = useState(getDefaultHotkey());-- useEffect(() => {- // Load hotkey from localStorage on mount- const savedHotkey = localStorage.getItem("dictationKey");- if (savedHotkey) {- setHotkey(savedHotkey);- } else {- setHotkey(getDefaultHotkey());- }- }, []);+ const hotkey = useSettingsStore((s) => s.dictationKey) || getDefaultHotkey();+ const setHotkey = useSettingsStore((s) => s.setDictationKey);return {hotkey,diff --git a/src/hooks/useNoteDragAndDrop.ts b/src/hooks/useNoteDragAndDrop.tsnew file mode 100644index 000000000..6b3a8d301--- /dev/null+++ b/src/hooks/useNoteDragAndDrop.ts@@ -0,0 +1,134 @@+import { useState, useCallback, useRef, useEffect } from "react";++interface DragState {+ draggingNoteId: number | null;+ dragOverFolderId: number | null;+ dropSuccessFolderId: number | null;+}++interface UseNoteDragAndDropOptions {+ onMoveToFolder: (noteId: number, folderId: number) => Promise<void>;+ currentFolderId: number | null;+}++export function useNoteDragAndDrop({ onMoveToFolder, currentFolderId }: UseNoteDragAndDropOptions) {+ const [dragState, setDragState] = useState<DragState>({+ draggingNoteId: null,+ dragOverFolderId: null,+ dropSuccessFolderId: null,+ });++ const successTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const enterCounterRef = useRef<Map<number, number>>(new Map());++ useEffect(() => {+ return () => {+ if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);+ };+ }, []);++ const noteDragHandlers = useCallback(+ (noteId: number, noteTitle: string) => ({+ draggable: true as const,+ onDragStart: (e: React.DragEvent) => {+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData("application/x-note-id", String(noteId));++ const ghost = document.createElement("div");+ const label = noteTitle || "Untitled";+ ghost.textContent = label.length > 24 ? label.slice(0, 24) + "…" : label;+ ghost.style.cssText = `+ position: fixed; top: -200px; left: -200px;+ padding: 4px 12px;+ background: oklch(0.27 0.008 260 / 0.95);+ color: oklch(0.9 0 0);+ font-size: 11px;+ font-weight: 500;+ border-radius: 6px;+ border: 1px solid oklch(0.38 0.008 260);+ white-space: nowrap;+ pointer-events: none;+ `;+ document.body.appendChild(ghost);+ e.dataTransfer.setDragImage(ghost, 0, 0);+ requestAnimationFrame(() => ghost.remove());++ setDragState((prev) => ({ ...prev, draggingNoteId: noteId }));+ enterCounterRef.current.clear();+ },+ onDragEnd: () => {+ setDragState((prev) => ({+ ...prev,+ draggingNoteId: null,+ dragOverFolderId: null,+ }));+ enterCounterRef.current.clear();+ },+ }),+ []+ );++ const folderDropHandlers = useCallback(+ (folderId: number, folderName: string) => {+ const isMeetings = folderName === "Meetings";+ const isSameFolder = folderId === currentFolderId;+ const canDrop = !isMeetings && !isSameFolder;++ return {+ onDragOver: (e: React.DragEvent) => {+ if (!canDrop) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "move";+ },+ onDragEnter: (e: React.DragEvent) => {+ e.preventDefault();+ if (!canDrop) return;+ const count = (enterCounterRef.current.get(folderId) ?? 0) + 1;+ enterCounterRef.current.set(folderId, count);+ if (count === 1) {+ setDragState((prev) => ({ ...prev, dragOverFolderId: folderId }));+ }+ },+ onDragLeave: () => {+ if (!canDrop) return;+ const count = (enterCounterRef.current.get(folderId) ?? 0) - 1;+ enterCounterRef.current.set(folderId, Math.max(0, count));+ if (count <= 0) {+ enterCounterRef.current.set(folderId, 0);+ setDragState((prev) =>+ prev.dragOverFolderId === folderId ? { ...prev, dragOverFolderId: null } : prev+ );+ }+ },+ onDrop: async (e: React.DragEvent) => {+ e.preventDefault();+ if (!canDrop) return;++ const noteIdStr = e.dataTransfer.getData("application/x-note-id");+ const noteId = parseInt(noteIdStr, 10);+ if (isNaN(noteId)) return;++ enterCounterRef.current.clear();+ setDragState((prev) => ({+ ...prev,+ draggingNoteId: null,+ dragOverFolderId: null,+ dropSuccessFolderId: folderId,+ }));++ if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);+ successTimeoutRef.current = setTimeout(() => {+ setDragState((prev) =>+ prev.dropSuccessFolderId === folderId ? { ...prev, dropSuccessFolderId: null } : prev+ );+ }, 800);++ await onMoveToFolder(noteId, folderId);+ },+ };+ },+ [currentFolderId, onMoveToFolder]+ );++ return { dragState, noteDragHandlers, folderDropHandlers };+}diff --git a/src/hooks/useNoteRecording.ts b/src/hooks/useNoteRecording.tsnew file mode 100644index 000000000..5637c8177--- /dev/null+++ b/src/hooks/useNoteRecording.ts@@ -0,0 +1,158 @@+import { useState, useEffect, useRef, useCallback } from "react";+import { useTranslation } from "react-i18next";+import AudioManager from "../helpers/audioManager";+import logger from "../utils/logger";+import { getRecordingErrorTitle } from "../utils/recordingErrors";++interface UseNoteRecordingOptions {+ onTranscriptionComplete: (text: string) => void;+ onPartialTranscript?: (text: string) => void;+ onError?: (error: { title: string; description: string }) => void;+}++interface UseNoteRecordingReturn {+ isRecording: boolean;+ isProcessing: boolean;+ isStreaming: boolean;+ partialTranscript: string;+ streamingCommit: string | null;+ consumeStreamingCommit: () => void;+ startRecording: () => Promise<void>;+ stopRecording: () => Promise<void>;+ cancelRecording: () => void;+}++export function useNoteRecording({+ onTranscriptionComplete,+ onPartialTranscript,+ onError,+}: UseNoteRecordingOptions): UseNoteRecordingReturn {+ const { t } = useTranslation();+ const [isRecording, setIsRecording] = useState(false);+ const [isProcessing, setIsProcessing] = useState(false);+ const [isStreaming, setIsStreaming] = useState(false);+ const [partialTranscript, setPartialTranscript] = useState("");+ const [streamingCommits, setStreamingCommits] = useState<string[]>([]);+ const audioManagerRef = useRef<InstanceType<typeof AudioManager> | null>(null);++ const callbacksRef = useRef({ onTranscriptionComplete, onPartialTranscript, onError });+ callbacksRef.current = { onTranscriptionComplete, onPartialTranscript, onError };++ useEffect(() => {+ const manager = new AudioManager();+ audioManagerRef.current = manager;+ manager.setSkipReasoning(true);++ manager.setCallbacks({+ onStateChange: ({+ isRecording,+ isProcessing,+ isStreaming,+ }: {+ isRecording: boolean;+ isProcessing: boolean;+ isStreaming?: boolean;+ }) => {+ setIsRecording(isRecording);+ setIsProcessing(isProcessing);+ setIsStreaming(isStreaming ?? false);+ if (!isStreaming) {+ setPartialTranscript("");+ setStreamingCommits([]);+ }+ },+ onError: (error: { title: string; description: string; code?: string }) => {+ const title = getRecordingErrorTitle(error, t);+ callbacksRef.current.onError?.({ title, description: error.description });+ },+ onPartialTranscript: (text: string) => {+ setPartialTranscript(text);+ callbacksRef.current.onPartialTranscript?.(text);+ },+ onStreamingCommit: (text: string) => {+ setStreamingCommits((pending) => [...pending, text]);+ },+ onTranscriptionComplete: (result: {+ success: boolean;+ text: string;+ source?: string;+ limitReached?: boolean;+ wordsUsed?: number;+ wordsRemaining?: number;+ }) => {+ if (result.success) {+ callbacksRef.current.onTranscriptionComplete(result.text);+ manager.warmupStreamingConnection();+ }+ },+ });++ manager.warmupStreamingConnection();++ return () => {+ manager.cleanup();+ audioManagerRef.current = null;+ };+ }, []);++ const startRecording = useCallback(async () => {+ const manager = audioManagerRef.current;+ if (!manager) return;++ const state = manager.getState();+ if (state.isRecording || state.isProcessing) return;++ const didStart = manager.shouldUseStreaming()+ ? await manager.startStreamingRecording()+ : await manager.startRecording();++ if (!didStart) {+ logger.debug("Note recording failed to start", {}, "notes");+ }+ }, []);++ const stopRecording = useCallback(async () => {+ const manager = audioManagerRef.current;+ if (!manager) return;++ const state = manager.getState();+ if (!state.isRecording) return;++ if (state.isStreaming) {+ await manager.stopStreamingRecording();+ } else {+ manager.stopRecording();+ }+ }, []);++ const cancelRecording = useCallback(() => {+ const manager = audioManagerRef.current;+ if (!manager) return;++ const state = manager.getState();+ if (state.isStreaming) {+ manager.stopStreamingRecording();+ } else {+ manager.cancelRecording();+ }+ }, []);++ const consumeStreamingCommit = useCallback(+ () => setStreamingCommits((pending) => pending.slice(1)),+ []+ );++ const streamingCommit = streamingCommits[0] ?? null;++ return {+ isRecording,+ isProcessing,+ isStreaming,+ partialTranscript,+ streamingCommit,+ consumeStreamingCommit,+ startRecording,+ stopRecording,+ cancelRecording,+ };+}diff --git a/src/hooks/useNotesOnboarding.ts b/src/hooks/useNotesOnboarding.tsnew file mode 100644index 000000000..292f1632d--- /dev/null+++ b/src/hooks/useNotesOnboarding.ts@@ -0,0 +1,38 @@+import { useState, useCallback } from "react";+import {+ useSettingsStore,+ selectEffectiveReasoningModel,+ selectIsCloudReasoningMode,+} from "../stores/settingsStore";+import { useUsage } from "./useUsage";++interface UseNotesOnboardingReturn {+ isComplete: boolean;+ isProUser: boolean;+ isProLoading: boolean;+ isLLMConfigured: boolean;+ complete: () => void;+}++export function useNotesOnboarding(): UseNotesOnboardingReturn {+ const usage = useUsage();+ const isProUser = !!(usage?.isSubscribed || usage?.isTrial);+ const isProLoading = usage !== null && !usage.hasLoaded;+ const useReasoningModel = useSettingsStore((s) => s.useReasoningModel);+ const effectiveModel = useSettingsStore(selectEffectiveReasoningModel);+ const isCloudReasoning = useSettingsStore(selectIsCloudReasoningMode);++ const [isComplete, setIsComplete] = useState(+ () => localStorage.getItem("notesOnboardingComplete") === "true"+ );++ const isLLMConfigured = isCloudReasoning || (useReasoningModel && !!effectiveModel);++ const complete = useCallback(() => {+ localStorage.setItem("notesOnboardingComplete", "true");+ localStorage.setItem("uploadSetupComplete", "true");+ setIsComplete(true);+ }, []);++ return { isComplete, isProUser, isProLoading, isLLMConfigured, complete };+}diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex d3a8ea41c..f625b09f1 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -1,21 +1,8 @@-import React, { createContext, useCallback, useContext, useEffect, useRef } from "react";-import { useLocalStorage } from "./useLocalStorage";-import { useDebouncedCallback } from "./useDebouncedCallback";-import { API_ENDPOINTS } from "../config/constants";+import React, { createContext, useContext, useEffect, useRef } from "react";+import { useSettingsStore, initializeSettings } from "../stores/settingsStore";import logger from "../utils/logger";-import { ensureAgentNameInDictionary } from "../utils/agentName";-import i18n, { normalizeUiLanguage } from "../i18n";-import { hasStoredByokKey } from "../utils/byokDetection";import type { LocalTranscriptionProvider } from "../types/electron";-let _ReasoningService: typeof import("../services/ReasoningService").default | null = null;-function getReasoningService() {- if (!_ReasoningService) {- _ReasoningService = require("../services/ReasoningService").default;- }- return _ReasoningService!;-}-export interface TranscriptionSettings {uiLanguage: string;useLocalWhisper: boolean;@@ -71,587 +58,34 @@ export interface ThemeSettings {theme: "light" | "dark" | "auto";}-const LANGUAGE_MIGRATIONS: Record<string, string> = { zh: "zh-CN" };-let _migrated = false;-function migratePreferredLanguage() {- if (_migrated) return;- _migrated = true;- const stored = localStorage.getItem("preferredLanguage");- if (stored && LANGUAGE_MIGRATIONS[stored]) {- localStorage.setItem("preferredLanguage", LANGUAGE_MIGRATIONS[stored]);- }-}-function useSettingsInternal() {- migratePreferredLanguage();-- const [useLocalWhisper, setUseLocalWhisper] = useLocalStorage("useLocalWhisper", false, {- serialize: String,- deserialize: (value) => value === "true",- });-- const [whisperModel, setWhisperModel] = useLocalStorage("whisperModel", "base", {- serialize: String,- deserialize: String,- });-- const [localTranscriptionProvider, setLocalTranscriptionProvider] =- useLocalStorage<LocalTranscriptionProvider>("localTranscriptionProvider", "whisper", {- serialize: String,- deserialize: (value) => (value === "nvidia" ? "nvidia" : "whisper"),- });-- const [parakeetModel, setParakeetModel] = useLocalStorage("parakeetModel", "", {- serialize: String,- deserialize: String,- });-- const [allowOpenAIFallback, setAllowOpenAIFallback] = useLocalStorage(- "allowOpenAIFallback",- false,- {- serialize: String,- deserialize: (value) => value === "true",- }- );-- const [allowLocalFallback, setAllowLocalFallback] = useLocalStorage("allowLocalFallback", false, {- serialize: String,- deserialize: (value) => value === "true",- });-- const [fallbackWhisperModel, setFallbackWhisperModel] = useLocalStorage(- "fallbackWhisperModel",- "base",- {- serialize: String,- deserialize: String,- }- );-- const [preferredLanguage, setPreferredLanguage] = useLocalStorage("preferredLanguage", "auto", {- serialize: String,- deserialize: String,- });-- const [uiLanguage, setUiLanguageLocal] = useLocalStorage("uiLanguage", "en", {- serialize: String,- deserialize: (value) => normalizeUiLanguage(value),- });-- const setUiLanguage = useCallback(- (language: string) => {- setUiLanguageLocal(normalizeUiLanguage(language));- },- [setUiLanguageLocal]- );-- const hasRunUiLanguageSync = useRef(false);- const uiLanguageSyncReady = useRef(false);-- useEffect(() => {- if (hasRunUiLanguageSync.current) return;- hasRunUiLanguageSync.current = true;-- const sync = async () => {- let resolved = normalizeUiLanguage(uiLanguage);-- if (typeof window !== "undefined" && window.electronAPI?.getUiLanguage) {- const envLanguage = await window.electronAPI.getUiLanguage();- resolved = normalizeUiLanguage(envLanguage || resolved);- }-- if (resolved !== uiLanguage) {- setUiLanguageLocal(resolved);- }-- await i18n.changeLanguage(resolved);- uiLanguageSyncReady.current = true;- };-- sync().catch((err) => {- logger.warn(- "Failed to sync UI language on startup",- { error: (err as Error).message },- "settings"- );- uiLanguageSyncReady.current = true;- void i18n.changeLanguage(normalizeUiLanguage(uiLanguage));- });- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- useEffect(() => {- if (!uiLanguageSyncReady.current) return;-- const normalized = normalizeUiLanguage(uiLanguage);- void i18n.changeLanguage(normalized);-- if (typeof window !== "undefined" && window.electronAPI?.setUiLanguage) {- window.electronAPI.setUiLanguage(normalized).catch((err) => {- logger.warn(- "Failed to sync UI language to main process",- { error: (err as Error).message },- "settings"- );- });- }- }, [uiLanguage]);-- const [cloudTranscriptionProvider, setCloudTranscriptionProvider] = useLocalStorage(- "cloudTranscriptionProvider",- "openai",- {- serialize: String,- deserialize: String,- }- );-- const [cloudTranscriptionModel, setCloudTranscriptionModel] = useLocalStorage(- "cloudTranscriptionModel",- "gpt-4o-mini-transcribe",- {- serialize: String,- deserialize: String,- }- );-- const [cloudTranscriptionBaseUrl, setCloudTranscriptionBaseUrl] = useLocalStorage(- "cloudTranscriptionBaseUrl",- API_ENDPOINTS.TRANSCRIPTION_BASE,- {- serialize: String,- deserialize: String,- }- );-- const [cloudReasoningBaseUrl, setCloudReasoningBaseUrl] = useLocalStorage(- "cloudReasoningBaseUrl",- API_ENDPOINTS.OPENAI_BASE,- {- serialize: String,- deserialize: String,- }- );-- const [cloudTranscriptionMode, setCloudTranscriptionMode] = useLocalStorage(- "cloudTranscriptionMode",- hasStoredByokKey() ? "byok" : "openwhispr",- {- serialize: String,- deserialize: String,- }- );-- const [cloudReasoningMode, setCloudReasoningMode] = useLocalStorage(- "cloudReasoningMode",- "openwhispr",- {- serialize: String,- deserialize: String,- }- );-- // Custom dictionary for improving transcription of specific words- const [customDictionary, setCustomDictionaryRaw] = useLocalStorage<string[]>(- "customDictionary",- [],- {- serialize: JSON.stringify,- deserialize: (value) => {- try {- const parsed = JSON.parse(value);- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }- },- }- );-- // Assembly AI real-time streaming (enabled by default for signed-in users)- const [assemblyAiStreaming, setAssemblyAiStreaming] = useLocalStorage(- "assemblyAiStreaming",- true,- {- serialize: String,- deserialize: (value) => value !== "false", // Default to true unless explicitly disabled- }- );-- // Wrap setter to sync dictionary to SQLite- const setCustomDictionary = useCallback(- (words: string[]) => {- setCustomDictionaryRaw(words);- window.electronAPI?.setDictionary(words).catch((err) => {- logger.warn(- "Failed to sync dictionary to SQLite",- { error: (err as Error).message },- "settings"- );- });- },- [setCustomDictionaryRaw]- );-- // One-time sync: reconcile localStorage ↔ SQLite on startup- const hasRunDictionarySync = useRef(false);- useEffect(() => {- if (hasRunDictionarySync.current) return;- hasRunDictionarySync.current = true;-- const syncDictionary = async () => {- if (typeof window === "undefined" || !window.electronAPI?.getDictionary) return;- try {- const dbWords = await window.electronAPI.getDictionary();- if (dbWords.length === 0 && customDictionary.length > 0) {- // Seed SQLite from localStorage (first-time migration)- await window.electronAPI.setDictionary(customDictionary);- } else if (dbWords.length > 0 && customDictionary.length === 0) {- // Recover localStorage from SQLite (e.g. localStorage was cleared)- setCustomDictionaryRaw(dbWords);- }- } catch (err) {- logger.warn(- "Failed to sync dictionary on startup",- { error: (err as Error).message },- "settings"- );- }- };-- syncDictionary().then(() => {- // Ensure agent name is in dictionary for existing users who set it before this feature- ensureAgentNameInDictionary();- });- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- // Reasoning settings- const [useReasoningModel, setUseReasoningModel] = useLocalStorage("useReasoningModel", true, {- serialize: String,- deserialize: (value) => value !== "false", // Default true- });+ const store = useSettingsStore();- const [reasoningModel, setReasoningModel] = useLocalStorage("reasoningModel", "", {- serialize: String,- deserialize: String,- });-- const [reasoningProvider, setReasoningProvider] = useLocalStorage("reasoningProvider", "openai", {- serialize: String,- deserialize: String,- });-- // API keys - localStorage for UI, synced to Electron IPC for persistence- const [openaiApiKey, setOpenaiApiKeyLocal] = useLocalStorage("openaiApiKey", "", {- serialize: String,- deserialize: String,- });-- const [anthropicApiKey, setAnthropicApiKeyLocal] = useLocalStorage("anthropicApiKey", "", {- serialize: String,- deserialize: String,- });-- const [geminiApiKey, setGeminiApiKeyLocal] = useLocalStorage("geminiApiKey", "", {- serialize: String,- deserialize: String,- });-- const [groqApiKey, setGroqApiKeyLocal] = useLocalStorage("groqApiKey", "", {- serialize: String,- deserialize: String,- });-- const [mistralApiKey, setMistralApiKeyLocal] = useLocalStorage("mistralApiKey", "", {- serialize: String,- deserialize: String,- });-- // Theme setting- const [theme, setTheme] = useLocalStorage<"light" | "dark" | "auto">("theme", "auto", {- serialize: String,- deserialize: (value) => {- if (["light", "dark", "auto"].includes(value)) return value as "light" | "dark" | "auto";- return "auto";- },- });-- // Privacy settings — both default to OFF- const [cloudBackupEnabled, setCloudBackupEnabled] = useLocalStorage("cloudBackupEnabled", false, {- serialize: String,- deserialize: (value) => value === "true",- });-- const [telemetryEnabled, setTelemetryEnabled] = useLocalStorage("telemetryEnabled", false, {- serialize: String,- deserialize: (value) => value === "true",- });-- // Custom endpoint API keys - synced to .env like other keys- const [customTranscriptionApiKey, setCustomTranscriptionApiKeyLocal] = useLocalStorage(- "customTranscriptionApiKey",- "",- {- serialize: String,- deserialize: String,- }- );-- const [customReasoningApiKey, setCustomReasoningApiKeyLocal] = useLocalStorage(- "customReasoningApiKey",- "",- {- serialize: String,- deserialize: String,- }- );-- // Sync API keys from main process on first mount (if localStorage was cleared)- const hasRunApiKeySync = useRef(false);+ // One-time initialization: sync API keys, dictation key, activation mode,+ // UI language, and dictionary from the main process / SQLite.+ const hasInitialized = useRef(false);useEffect(() => {- if (hasRunApiKeySync.current) return;- hasRunApiKeySync.current = true;-- const syncKeys = async () => {- if (typeof window === "undefined" || !window.electronAPI) return;-- // Only sync keys that are missing from localStorage- if (!openaiApiKey) {- const envKey = await window.electronAPI.getOpenAIKey?.();- if (envKey) setOpenaiApiKeyLocal(envKey);- }- if (!anthropicApiKey) {- const envKey = await window.electronAPI.getAnthropicKey?.();- if (envKey) setAnthropicApiKeyLocal(envKey);- }- if (!geminiApiKey) {- const envKey = await window.electronAPI.getGeminiKey?.();- if (envKey) setGeminiApiKeyLocal(envKey);- }- if (!groqApiKey) {- const envKey = await window.electronAPI.getGroqKey?.();- if (envKey) setGroqApiKeyLocal(envKey);- }- if (!mistralApiKey) {- const envKey = await window.electronAPI.getMistralKey?.();- if (envKey) setMistralApiKeyLocal(envKey);- }- if (!customTranscriptionApiKey) {- const envKey = await window.electronAPI.getCustomTranscriptionKey?.();- if (envKey) setCustomTranscriptionApiKeyLocal(envKey);- }- if (!customReasoningApiKey) {- const envKey = await window.electronAPI.getCustomReasoningKey?.();- if (envKey) setCustomReasoningApiKeyLocal(envKey);- }- };-- syncKeys().catch((err) => {+ if (hasInitialized.current) return;+ hasInitialized.current = true;+ initializeSettings().catch((err) => {logger.warn(- "Failed to sync API keys on startup",+ "Failed to initialize settings store",{ error: (err as Error).message },"settings");});- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const debouncedPersistToEnv = useDebouncedCallback(() => {- if (typeof window !== "undefined" && window.electronAPI?.saveAllKeysToEnv) {- window.electronAPI.saveAllKeysToEnv().catch((err) => {- logger.warn(- "Failed to persist API keys to .env",- { error: (err as Error).message },- "settings"- );- });- }- }, 1000);-- const invalidateApiKeyCaches = useCallback(- (provider?: "openai" | "anthropic" | "gemini" | "groq" | "mistral" | "custom") => {- if (provider) {- getReasoningService().clearApiKeyCache(provider);- }- window.dispatchEvent(new Event("api-key-changed"));- debouncedPersistToEnv();- },- [debouncedPersistToEnv]- );-- const setOpenaiApiKey = useCallback(- (key: string) => {- setOpenaiApiKeyLocal(key);- window.electronAPI?.saveOpenAIKey?.(key);- invalidateApiKeyCaches("openai");- },- [setOpenaiApiKeyLocal, invalidateApiKeyCaches]- );-- const setAnthropicApiKey = useCallback(- (key: string) => {- setAnthropicApiKeyLocal(key);- window.electronAPI?.saveAnthropicKey?.(key);- invalidateApiKeyCaches("anthropic");- },- [setAnthropicApiKeyLocal, invalidateApiKeyCaches]- );-- const setGeminiApiKey = useCallback(- (key: string) => {- setGeminiApiKeyLocal(key);- window.electronAPI?.saveGeminiKey?.(key);- invalidateApiKeyCaches("gemini");- },- [setGeminiApiKeyLocal, invalidateApiKeyCaches]- );-- const setGroqApiKey = useCallback(- (key: string) => {- setGroqApiKeyLocal(key);- window.electronAPI?.saveGroqKey?.(key);- invalidateApiKeyCaches("groq");- },- [setGroqApiKeyLocal, invalidateApiKeyCaches]- );-- const setMistralApiKey = useCallback(- (key: string) => {- setMistralApiKeyLocal(key);- window.electronAPI?.saveMistralKey?.(key);- invalidateApiKeyCaches("mistral");- },- [setMistralApiKeyLocal, invalidateApiKeyCaches]- );-- const setCustomTranscriptionApiKey = useCallback(- (key: string) => {- setCustomTranscriptionApiKeyLocal(key);- window.electronAPI?.saveCustomTranscriptionKey?.(key);- invalidateApiKeyCaches();- },- [setCustomTranscriptionApiKeyLocal, invalidateApiKeyCaches]- );-- const setCustomReasoningApiKey = useCallback(- (key: string) => {- setCustomReasoningApiKeyLocal(key);- window.electronAPI?.saveCustomReasoningKey?.(key);- invalidateApiKeyCaches("custom");- },- [setCustomReasoningApiKeyLocal, invalidateApiKeyCaches]- );-- const [dictationKey, setDictationKeyLocal] = useLocalStorage("dictationKey", "", {- serialize: String,- deserialize: String,- });-- const setDictationKey = useCallback(- (key: string) => {- setDictationKeyLocal(key);- if (typeof window !== "undefined" && window.electronAPI?.notifyHotkeyChanged) {- window.electronAPI.notifyHotkeyChanged(key);- }- if (typeof window !== "undefined" && window.electronAPI?.saveDictationKey) {- window.electronAPI.saveDictationKey(key);- }- },- [setDictationKeyLocal]- );-- const [activationMode, setActivationModeLocal] = useLocalStorage<"tap" | "push">(- "activationMode",- "tap",- {- serialize: String,- deserialize: (value) => (value === "push" ? "push" : "tap"),- }- );-- const setActivationMode = useCallback(- (mode: "tap" | "push") => {- setActivationModeLocal(mode);- if (typeof window !== "undefined" && window.electronAPI?.notifyActivationModeChanged) {- window.electronAPI.notifyActivationModeChanged(mode);- }- },- [setActivationModeLocal]- );-- // Sync activation mode from main process on first mount (handles localStorage cleared)- const hasRunActivationModeSync = useRef(false);- useEffect(() => {- if (hasRunActivationModeSync.current) return;- hasRunActivationModeSync.current = true;-- const sync = async () => {- if (!window.electronAPI?.getActivationMode) return;- const envMode = await window.electronAPI.getActivationMode();- if (envMode && envMode !== activationMode) {- setActivationModeLocal(envMode);- }- };- sync().catch(() => {});- // eslint-disable-next-line react-hooks/exhaustive-deps}, []);- // Sync dictation key from main process on first mount (handles localStorage cleared)- const hasRunDictationKeySync = useRef(false);- useEffect(() => {- if (hasRunDictationKeySync.current) return;- hasRunDictationKeySync.current = true;-- const sync = async () => {- if (!window.electronAPI?.getDictationKey) return;- const envKey = await window.electronAPI.getDictationKey();- if (envKey && envKey !== dictationKey) {- setDictationKeyLocal(envKey);- }- };- sync().catch(() => {});- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const [audioCuesEnabled, setAudioCuesEnabled] = useLocalStorage("audioCuesEnabled", true, {- serialize: String,- deserialize: (value) => value !== "false",- });-- // Floating icon auto-hide setting- const [floatingIconAutoHide, setFloatingIconAutoHideLocal] = useLocalStorage(- "floatingIconAutoHide",- false,- {- serialize: String,- deserialize: (value) => value === "true",- }- );-- const setFloatingIconAutoHide = useCallback(- (enabled: boolean) => {- setFloatingIconAutoHideLocal(enabled);- if (typeof window !== "undefined" && window.electronAPI?.notifyFloatingIconAutoHideChanged) {- window.electronAPI.notifyFloatingIconAutoHideChanged(enabled);- }- },- [setFloatingIconAutoHideLocal]- );-- // Microphone settings- const [preferBuiltInMic, setPreferBuiltInMic] = useLocalStorage("preferBuiltInMic", true, {- serialize: String,- deserialize: (value) => value !== "false",- });-- const [selectedMicDeviceId, setSelectedMicDeviceId] = useLocalStorage("selectedMicDeviceId", "", {- serialize: String,- deserialize: String,- });-// Sync startup pre-warming preferences to main process+ const {+ useLocalWhisper,+ localTranscriptionProvider,+ whisperModel,+ parakeetModel,+ reasoningProvider,+ reasoningModel,+ } = store;+useEffect(() => {if (typeof window === "undefined" || !window.electronAPI?.syncStartupPreferences) return;@@ -680,156 +114,82 @@ function useSettingsInternal() {reasoningModel,]);- // Batch operations- const updateTranscriptionSettings = useCallback(- (settings: Partial<TranscriptionSettings>) => {- if (settings.useLocalWhisper !== undefined) setUseLocalWhisper(settings.useLocalWhisper);- if (settings.uiLanguage !== undefined) setUiLanguage(settings.uiLanguage);- if (settings.whisperModel !== undefined) setWhisperModel(settings.whisperModel);- if (settings.localTranscriptionProvider !== undefined)- setLocalTranscriptionProvider(settings.localTranscriptionProvider);- if (settings.parakeetModel !== undefined) setParakeetModel(settings.parakeetModel);- if (settings.allowOpenAIFallback !== undefined)- setAllowOpenAIFallback(settings.allowOpenAIFallback);- if (settings.allowLocalFallback !== undefined)- setAllowLocalFallback(settings.allowLocalFallback);- if (settings.fallbackWhisperModel !== undefined)- setFallbackWhisperModel(settings.fallbackWhisperModel);- if (settings.preferredLanguage !== undefined)- setPreferredLanguage(settings.preferredLanguage);- if (settings.cloudTranscriptionProvider !== undefined)- setCloudTranscriptionProvider(settings.cloudTranscriptionProvider);- if (settings.cloudTranscriptionModel !== undefined)- setCloudTranscriptionModel(settings.cloudTranscriptionModel);- if (settings.cloudTranscriptionBaseUrl !== undefined)- setCloudTranscriptionBaseUrl(settings.cloudTranscriptionBaseUrl);- if (settings.customDictionary !== undefined) setCustomDictionary(settings.customDictionary);- },- [- setUseLocalWhisper,- setUiLanguage,- setWhisperModel,- setLocalTranscriptionProvider,- setParakeetModel,- setAllowOpenAIFallback,- setAllowLocalFallback,- setFallbackWhisperModel,- setPreferredLanguage,- setCloudTranscriptionProvider,- setCloudTranscriptionModel,- setCloudTranscriptionBaseUrl,- setCustomDictionary,- ]- );-- const updateReasoningSettings = useCallback(- (settings: Partial<ReasoningSettings>) => {- if (settings.useReasoningModel !== undefined)- setUseReasoningModel(settings.useReasoningModel);- if (settings.reasoningModel !== undefined) setReasoningModel(settings.reasoningModel);- if (settings.reasoningProvider !== undefined)- setReasoningProvider(settings.reasoningProvider);- if (settings.cloudReasoningBaseUrl !== undefined)- setCloudReasoningBaseUrl(settings.cloudReasoningBaseUrl);- if (settings.cloudReasoningMode !== undefined)- setCloudReasoningMode(settings.cloudReasoningMode);- },- [- setUseReasoningModel,- setReasoningModel,- setReasoningProvider,- setCloudReasoningBaseUrl,- setCloudReasoningMode,- ]- );-- 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.mistralApiKey !== undefined) setMistralApiKey(keys.mistralApiKey);- },- [setOpenaiApiKey, setAnthropicApiKey, setGeminiApiKey, setGroqApiKey, setMistralApiKey]- );-return {- useLocalWhisper,- whisperModel,- uiLanguage,- localTranscriptionProvider,- parakeetModel,- allowOpenAIFallback,- allowLocalFallback,- fallbackWhisperModel,- preferredLanguage,- cloudTranscriptionProvider,- cloudTranscriptionModel,- cloudTranscriptionBaseUrl,- cloudReasoningBaseUrl,- cloudTranscriptionMode,- cloudReasoningMode,- customDictionary,- assemblyAiStreaming,- setAssemblyAiStreaming,- useReasoningModel,- reasoningModel,- reasoningProvider,- openaiApiKey,- anthropicApiKey,- geminiApiKey,- groqApiKey,- mistralApiKey,- dictationKey,- theme,- setUseLocalWhisper,- setWhisperModel,- setUiLanguage,- setLocalTranscriptionProvider,- setParakeetModel,- setAllowOpenAIFallback,- setAllowLocalFallback,- setFallbackWhisperModel,- setPreferredLanguage,- setCloudTranscriptionProvider,- setCloudTranscriptionModel,- setCloudTranscriptionBaseUrl,- setCloudReasoningBaseUrl,- setCloudTranscriptionMode,- setCloudReasoningMode,- setCustomDictionary,- setUseReasoningModel,- setReasoningModel,- setReasoningProvider,- setOpenaiApiKey,- setAnthropicApiKey,- setGeminiApiKey,- setGroqApiKey,- setMistralApiKey,- customTranscriptionApiKey,- setCustomTranscriptionApiKey,- customReasoningApiKey,- setCustomReasoningApiKey,- setDictationKey,- setTheme,- activationMode,- setActivationMode,- audioCuesEnabled,- setAudioCuesEnabled,- floatingIconAutoHide,- setFloatingIconAutoHide,- preferBuiltInMic,- selectedMicDeviceId,- setPreferBuiltInMic,- setSelectedMicDeviceId,- cloudBackupEnabled,- setCloudBackupEnabled,- telemetryEnabled,- setTelemetryEnabled,- updateTranscriptionSettings,- updateReasoningSettings,- updateApiKeys,+ useLocalWhisper: store.useLocalWhisper,+ whisperModel: store.whisperModel,+ uiLanguage: store.uiLanguage,+ localTranscriptionProvider: store.localTranscriptionProvider,+ parakeetModel: store.parakeetModel,+ allowOpenAIFallback: store.allowOpenAIFallback,+ allowLocalFallback: store.allowLocalFallback,+ fallbackWhisperModel: store.fallbackWhisperModel,+ preferredLanguage: store.preferredLanguage,+ cloudTranscriptionProvider: store.cloudTranscriptionProvider,+ cloudTranscriptionModel: store.cloudTranscriptionModel,+ cloudTranscriptionBaseUrl: store.cloudTranscriptionBaseUrl,+ cloudReasoningBaseUrl: store.cloudReasoningBaseUrl,+ cloudTranscriptionMode: store.cloudTranscriptionMode,+ cloudReasoningMode: store.cloudReasoningMode,+ customDictionary: store.customDictionary,+ assemblyAiStreaming: store.assemblyAiStreaming,+ setAssemblyAiStreaming: store.setAssemblyAiStreaming,+ useReasoningModel: store.useReasoningModel,+ reasoningModel: store.reasoningModel,+ reasoningProvider: store.reasoningProvider,+ openaiApiKey: store.openaiApiKey,+ anthropicApiKey: store.anthropicApiKey,+ geminiApiKey: store.geminiApiKey,+ groqApiKey: store.groqApiKey,+ mistralApiKey: store.mistralApiKey,+ dictationKey: store.dictationKey,+ theme: store.theme,+ setUseLocalWhisper: store.setUseLocalWhisper,+ setWhisperModel: store.setWhisperModel,+ setUiLanguage: store.setUiLanguage,+ setLocalTranscriptionProvider: store.setLocalTranscriptionProvider,+ setParakeetModel: store.setParakeetModel,+ setAllowOpenAIFallback: store.setAllowOpenAIFallback,+ setAllowLocalFallback: store.setAllowLocalFallback,+ setFallbackWhisperModel: store.setFallbackWhisperModel,+ setPreferredLanguage: store.setPreferredLanguage,+ setCloudTranscriptionProvider: store.setCloudTranscriptionProvider,+ setCloudTranscriptionModel: store.setCloudTranscriptionModel,+ setCloudTranscriptionBaseUrl: store.setCloudTranscriptionBaseUrl,+ setCloudReasoningBaseUrl: store.setCloudReasoningBaseUrl,+ setCloudTranscriptionMode: store.setCloudTranscriptionMode,+ setCloudReasoningMode: store.setCloudReasoningMode,+ setCustomDictionary: store.setCustomDictionary,+ setUseReasoningModel: store.setUseReasoningModel,+ setReasoningModel: store.setReasoningModel,+ setReasoningProvider: store.setReasoningProvider,+ setOpenaiApiKey: store.setOpenaiApiKey,+ setAnthropicApiKey: store.setAnthropicApiKey,+ setGeminiApiKey: store.setGeminiApiKey,+ setGroqApiKey: store.setGroqApiKey,+ setMistralApiKey: store.setMistralApiKey,+ customTranscriptionApiKey: store.customTranscriptionApiKey,+ setCustomTranscriptionApiKey: store.setCustomTranscriptionApiKey,+ customReasoningApiKey: store.customReasoningApiKey,+ setCustomReasoningApiKey: store.setCustomReasoningApiKey,+ setDictationKey: store.setDictationKey,+ setTheme: store.setTheme,+ activationMode: store.activationMode,+ setActivationMode: store.setActivationMode,+ audioCuesEnabled: store.audioCuesEnabled,+ setAudioCuesEnabled: store.setAudioCuesEnabled,+ floatingIconAutoHide: store.floatingIconAutoHide,+ setFloatingIconAutoHide: store.setFloatingIconAutoHide,+ preferBuiltInMic: store.preferBuiltInMic,+ selectedMicDeviceId: store.selectedMicDeviceId,+ setPreferBuiltInMic: store.setPreferBuiltInMic,+ setSelectedMicDeviceId: store.setSelectedMicDeviceId,+ cloudBackupEnabled: store.cloudBackupEnabled,+ setCloudBackupEnabled: store.setCloudBackupEnabled,+ telemetryEnabled: store.telemetryEnabled,+ setTelemetryEnabled: store.setTelemetryEnabled,+ updateTranscriptionSettings: store.updateTranscriptionSettings,+ updateReasoningSettings: store.updateReasoningSettings,+ updateApiKeys: store.updateApiKeys,};}diff --git a/src/hooks/useUsage.ts b/src/hooks/useUsage.tsindex f4f7f45bd..8633b0732 100644--- a/src/hooks/useUsage.ts+++ b/src/hooks/useUsage.ts@@ -13,6 +13,7 @@ interface UsageData {isTrial: boolean;trialDaysLeft: number | null;currentPeriodEnd: string | null;+ billingInterval: "monthly" | "annual" | null;resetAt: string;}@@ -27,6 +28,7 @@ interface UseUsageResult {isTrial: boolean;trialDaysLeft: number | null;currentPeriodEnd: string | null;+ billingInterval: "monthly" | "annual" | null;isOverLimit: boolean;isApproachingLimit: boolean;resetAt: string | null;@@ -35,7 +37,7 @@ interface UseUsageResult {error: string | null;checkoutLoading: boolean;refetch: () => Promise<void>;- openCheckout: () => Promise<{ success: boolean; error?: string }>;+ openCheckout: (plan?: "monthly" | "annual") => Promise<{ success: boolean; error?: string }>;openBillingPortal: () => Promise<{ success: boolean; error?: string }>;}@@ -71,6 +73,7 @@ export function useUsage(): UseUsageResult | null {isTrial: result.isTrial ?? false,trialDaysLeft: result.trialDaysLeft ?? null,currentPeriodEnd: result.currentPeriodEnd ?? null,+ billingInterval: result.billingInterval ?? null,resetAt: result.resetAt ?? "rolling",});lastFetchRef.current = Date.now();@@ -88,6 +91,8 @@ export function useUsage(): UseUsageResult | null {}}, []);+ const pendingRefetchRef = useRef(false);+useEffect(() => {if (!isLoaded || !isSignedIn) return;@@ -98,28 +103,42 @@ export function useUsage(): UseUsageResult | null {setIsLoading(false);setHasLoaded(true);}++ const handleFocus = () => {+ if (pendingRefetchRef.current) {+ pendingRefetchRef.current = false;+ lastFetchRef.current = 0;+ fetchUsage();+ }+ };+ window.addEventListener("focus", handleFocus);+ return () => window.removeEventListener("focus", handleFocus);}, [isLoaded, isSignedIn, fetchUsage]);- const openCheckout = useCallback(async (): Promise<{ success: boolean; error?: string }> => {- if (checkoutInFlightRef.current)- return { success: false, error: "Checkout already in progress" };- if (!window.electronAPI?.cloudCheckout || !window.electronAPI?.openExternal) {- return { success: false, error: "App not ready" };- }- checkoutInFlightRef.current = true;- setCheckoutLoading(true);- try {- const result = await window.electronAPI.cloudCheckout();- if (result.success && result.url) {- await window.electronAPI.openExternal(result.url);- return { success: true };+ const openCheckout = useCallback(+ async (plan?: "monthly" | "annual"): Promise<{ success: boolean; error?: string }> => {+ if (checkoutInFlightRef.current)+ return { success: false, error: "Checkout already in progress" };+ if (!window.electronAPI?.cloudCheckout || !window.electronAPI?.openExternal) {+ return { success: false, error: "App not ready" };}- return { success: false, error: result.error || "Failed to start checkout" };- } finally {- checkoutInFlightRef.current = false;- setCheckoutLoading(false);- }- }, []);+ checkoutInFlightRef.current = true;+ setCheckoutLoading(true);+ try {+ const result = await window.electronAPI.cloudCheckout(plan);+ if (result.success && result.url) {+ pendingRefetchRef.current = true;+ await window.electronAPI.openExternal(result.url);+ return { success: true };+ }+ return { success: false, error: result.error || "Failed to start checkout" };+ } finally {+ checkoutInFlightRef.current = false;+ setCheckoutLoading(false);+ }+ },+ []+ );const openBillingPortal = useCallback(async (): Promise<{ success: boolean; error?: string }> => {if (checkoutInFlightRef.current) return { success: false, error: "Already loading" };@@ -131,6 +150,7 @@ export function useUsage(): UseUsageResult | null {try {const result = await window.electronAPI.cloudBillingPortal();if (result.success && result.url) {+ pendingRefetchRef.current = true;await window.electronAPI.openExternal(result.url);return { success: true };}@@ -162,6 +182,7 @@ export function useUsage(): UseUsageResult | null {isTrial: data?.isTrial ?? false,trialDaysLeft: data?.trialDaysLeft ?? null,currentPeriodEnd: data?.currentPeriodEnd ?? null,+ billingInterval: data?.billingInterval ?? null,isOverLimit,isApproachingLimit,resetAt: data?.resetAt ?? null,diff --git a/src/i18n.ts b/src/i18n.tsindex e3e955e97..34bfb1640 100644--- a/src/i18n.ts+++ b/src/i18n.ts@@ -96,7 +96,7 @@ void i18n.use(initReactI18next).init({interpolation: {escapeValue: false,},- returnEmptyString: false,+ returnEmptyString: true,returnNull: false,});diff --git a/src/index.css b/src/index.cssindex 143fa44ed..b53ac24c1 100644--- a/src/index.css+++ b/src/index.css@@ -1,5 +1,7 @@@import "tailwindcss";+@custom-variant dark (&:where(.dark, .dark *));+@theme {/* OpenWhispr Theme — registers color tokens with Tailwind v4.These are the light-mode defaults; .dark overrides them below. */@@ -8,7 +10,7 @@--color-secondary: #f5f5f5;--color-secondary-foreground: #171717;--color-muted: #f5f5f5;- --color-muted-foreground: #737373;+ --color-muted-foreground: #525252;--color-accent: oklch(0.55 0.22 285);--color-accent-foreground: #ffffff;--color-destructive: #dc2626;@@ -78,57 +80,59 @@}.dark {- /* Dark mode — clear surface hierarchy: bg < muted < card < popover */- --color-background: oklch(0.1 0.005 270);- --color-foreground: oklch(0.95 0 0);- --color-card: oklch(0.15 0.008 270);- --color-card-foreground: oklch(0.95 0 0);- --color-popover: oklch(0.17 0.008 270);- --color-popover-foreground: oklch(0.95 0 0);- --color-primary: oklch(0.62 0.22 260);+ /* Dark mode — charcoal surfaces with clear elevation hierarchy+ Base L=0.22 (charcoal) with 0.05 steps between layers.+ Hue 260 (neutral blue) with minimal chroma for sophistication. */+ --color-background: oklch(0.22 0.006 260);+ --color-foreground: oklch(0.93 0 0);+ --color-card: oklch(0.27 0.008 260);+ --color-card-foreground: oklch(0.93 0 0);+ --color-popover: oklch(0.29 0.009 260);+ --color-popover-foreground: oklch(0.93 0 0);+ --color-primary: oklch(0.65 0.2 260);--color-primary-foreground: oklch(0.99 0 0);- --color-secondary: oklch(0.18 0.005 270);- --color-secondary-foreground: oklch(0.92 0 0);- --color-muted: oklch(0.13 0.005 270);- --color-muted-foreground: oklch(0.55 0 0);- --color-accent: oklch(0.68 0.2 285);+ --color-secondary: oklch(0.28 0.007 260);+ --color-secondary-foreground: oklch(0.9 0 0);+ --color-muted: oklch(0.24 0.006 260);+ --color-muted-foreground: oklch(0.65 0 0);+ --color-accent: oklch(0.68 0.18 285);--color-accent-foreground: oklch(0.99 0 0);- --color-destructive: oklch(0.6 0.25 25);+ --color-destructive: oklch(0.62 0.22 25);--color-destructive-foreground: oklch(0.99 0 0);- --color-border: oklch(0.23 0.005 270);- --color-input: oklch(0.12 0.005 270);- --color-ring: oklch(0.62 0.22 260);+ --color-border: oklch(0.35 0.007 260);+ --color-input: oklch(0.19 0.005 260);+ --color-ring: oklch(0.65 0.2 260);--color-success: oklch(0.7 0.18 145);--color-success-foreground: oklch(0.99 0 0);--color-warning: oklch(0.75 0.15 70);--color-warning-foreground: oklch(0.15 0 0);- --color-info: oklch(0.68 0.2 240);+ --color-info: oklch(0.68 0.18 240);--color-info-foreground: oklch(0.99 0 0);- /* Surface hierarchy — layered depth system */- --color-surface-0: oklch(0.1 0.005 270);- --color-surface-1: oklch(0.13 0.006 270);- --color-surface-2: oklch(0.155 0.008 270);- --color-surface-3: oklch(0.18 0.01 270);- --color-surface-raised: oklch(0.2 0.012 270);+ /* Surface hierarchy — charcoal depth system (0.22 → 0.33) */+ --color-surface-0: oklch(0.22 0.006 260);+ --color-surface-1: oklch(0.25 0.007 260);+ --color-surface-2: oklch(0.27 0.008 260);+ --color-surface-3: oklch(0.3 0.009 260);+ --color-surface-raised: oklch(0.33 0.01 260);/* Border states */- --color-border-subtle: oklch(0.2 0.004 270);- --color-border-hover: oklch(0.28 0.01 270);- --color-border-active: oklch(0.45 0.15 260);- --color-link: oklch(0.64 0.09 250);-- /* Card depth shadows — no glow, clean depth only */- --shadow-card: 0 1px 2px oklch(0 0 0 / 0.25);- --shadow-card-hover: 0 2px 8px oklch(0 0 0 / 0.35);- --shadow-elevated: 0 8px 24px oklch(0 0 0 / 0.4);- --shadow-modal: 0 24px 48px -12px oklch(0 0 0 / 0.5);-- /* Model picker premium effects */- --shadow-metallic-dark: inset 0 1px 0 rgba(255, 255, 255, 0.03), 0 2px 8px rgba(0, 0, 0, 0.3);+ --color-border-subtle: oklch(0.33 0.006 260);+ --color-border-hover: oklch(0.42 0.01 260);+ --color-border-active: oklch(0.5 0.15 260);+ --color-link: oklch(0.67 0.1 250);++ /* Card depth shadows — softer for charcoal, with top highlight for premium depth */+ --shadow-card: 0 1px 3px oklch(0 0 0 / 0.2), inset 0 1px 0 oklch(1 0 0 / 0.03);+ --shadow-card-hover: 0 4px 12px oklch(0 0 0 / 0.25), inset 0 1px 0 oklch(1 0 0 / 0.04);+ --shadow-elevated: 0 8px 24px oklch(0 0 0 / 0.3);+ --shadow-modal: 0 24px 48px -12px oklch(0 0 0 / 0.4);++ /* Premium effects */+ --shadow-metallic-dark: inset 0 1px 0 rgba(255, 255, 255, 0.05), 0 2px 8px rgba(0, 0, 0, 0.2);--shadow-selected-glow:- inset 0 0 0 1px oklch(0.62 0.22 260 / 0.15), 0 0 16px -4px oklch(0.62 0.22 260 / 0.25);- --shadow-card-hover-subtle: 0 2px 8px -2px rgba(0, 0, 0, 0.15);+ inset 0 0 0 1px oklch(0.65 0.2 260 / 0.2), 0 0 16px -4px oklch(0.65 0.2 260 / 0.2);+ --shadow-card-hover-subtle: 0 2px 8px -2px rgba(0, 0, 0, 0.12);}@layer base {@@ -137,8 +141,7 @@transition:background-color 150ms ease,border-color 150ms ease,- color 150ms ease,- box-shadow 150ms ease;+ color 150ms ease;}body {@@ -173,6 +176,16 @@}}+@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+}+/* OpenWhispr Brand Typography */.brand-heading {font-family: var(--font-family-sans);@@ -227,7 +240,11 @@ svg:hover,input,textarea {border-radius: var(--radius);- transition: all 0.2s ease;+ transition:+ background-color 0.2s ease,+ border-color 0.2s ease,+ color 0.2s ease,+ box-shadow 0.2s ease;font-family: var(--font-family-sans);box-shadow: inset 0 1px 2px oklch(from var(--color-foreground) l c h / 0.06);}@@ -270,7 +287,9 @@ textarea {border: 1px solid var(--color-border);border-radius: var(--radius-lg);box-shadow: var(--shadow-card, 0 1px 3px oklch(from var(--color-foreground) l c h / 0.08));- transition: all 0.2s ease;+ transition:+ box-shadow 0.2s ease,+ transform 0.2s ease;}.card:hover {@@ -349,7 +368,7 @@ a:hover {height: 1px;background: linear-gradient(90deg,- oklch(0.62 0.22 260 / 0.5),+ oklch(0.65 0.2 260 / 0.5),oklch(0.7 0.18 280 / 0.3),transparent 80%);@@ -369,8 +388,8 @@ a:hover {/* Toast — opaque dark HUD surface, same in light & dark mode */.toast-surface {- background: oklch(0.13 0.005 270);- border: 1px solid oklch(0.22 0.005 270);+ background: oklch(0.15 0.006 260);+ border: 1px solid oklch(0.25 0.006 260);box-shadow:inset 0 1px 0 oklch(1 0 0 / 0.04),0 8px 24px -4px oklch(0 0 0 / 0.5),@@ -390,11 +409,11 @@ a:hover {@keyframes pulse-glow {0%,100% {- box-shadow: 0 0 6px oklch(0.62 0.22 260 / 0.4);+ box-shadow: 0 0 6px oklch(0.65 0.2 260 / 0.4);opacity: 0.8;}50% {- box-shadow: 0 0 8px oklch(0.62 0.22 260 / 0.6);+ box-shadow: 0 0 8px oklch(0.65 0.2 260 / 0.6);opacity: 1;}}@@ -421,6 +440,115 @@ a:hover {}}+@keyframes waveform-bar {+ 0%,+ 100% {+ transform: scaleY(0.3);+ }+ 50% {+ transform: scaleY(1);+ }+}++@keyframes float-up {+ from {+ opacity: 0;+ transform: translateY(8px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes grow-to-bar {+ from {+ transform: scale(0.55);+ opacity: 0;+ border-radius: 28px;+ }+ to {+ transform: scale(1);+ opacity: 1;+ border-radius: 12px;+ }+}++@keyframes fade-in-content {+ from {+ opacity: 0;+ transform: translateY(3px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes ring-fill {+ from {+ stroke-dashoffset: 94.25;+ }+ to {+ stroke-dashoffset: 0;+ }+}++@keyframes draw-check {+ from {+ stroke-dashoffset: 24;+ }+ to {+ stroke-dashoffset: 0;+ }+}++@keyframes drag-pulse {+ 0%,+ 100% {+ transform: scale(1);+ opacity: 0.4;+ }+ 50% {+ transform: scale(1.02);+ opacity: 0.7;+ }+}++@keyframes shimmer-slide {+ from {+ transform: translateX(-100%);+ }+ to {+ transform: translateX(100%);+ }+}++@keyframes fade-in-up {+ from {+ opacity: 0;+ transform: translateY(4px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes check-pop {+ 0% {+ transform: scale(0);+ opacity: 0;+ }+ 50% {+ transform: scale(1.2);+ }+ 100% {+ transform: scale(1);+ opacity: 1;+ }+}+/* Indeterminate progress bar sweep */@keyframes indeterminate {0% {@@ -431,6 +559,213 @@ a:hover {}}+/* Action processing scanner sweep */+@keyframes scanner-sweep {+ 0% {+ top: 0%;+ opacity: 0;+ }+ 5% {+ opacity: 1;+ }+ 95% {+ opacity: 1;+ }+ 100% {+ top: 100%;+ opacity: 0;+ }+}++/* ---- Referral Modal v2 ---- */++/* Animated mesh gradient — slow-drifting color blobs */+.referral-mesh-bg {+ position: absolute;+ inset: 0;+ overflow: hidden;+ z-index: 0;+ pointer-events: none;+}++.referral-mesh-bg::before,+.referral-mesh-bg::after {+ content: "";+ position: absolute;+ border-radius: 50%;+ filter: blur(80px);+ animation: mesh-drift 25s ease-in-out infinite alternate;+}++.referral-mesh-bg::before {+ width: 300px;+ height: 300px;+ background: oklch(0.65 0.2 260);+ opacity: 0.04;+ top: -80px;+ right: -60px;+}++.referral-mesh-bg::after {+ width: 250px;+ height: 250px;+ background: oklch(0.6 0.18 180);+ opacity: 0.04;+ bottom: -60px;+ left: -40px;+ animation-delay: -12s;+ animation-direction: alternate-reverse;+}++@keyframes mesh-drift {+ 0% {+ transform: translate(0, 0) scale(1);+ }+ 33% {+ transform: translate(30px, -20px) scale(1.05);+ }+ 66% {+ transform: translate(-20px, 15px) scale(0.95);+ }+ 100% {+ transform: translate(10px, -10px) scale(1.02);+ }+}++/* 3D perspective-tilt card */+.tilt-card {+ --tilt-x: 0deg;+ --tilt-y: 0deg;+ --highlight-x: 50%;+ --highlight-y: 50%;+ --highlight-opacity: 0;+ transform-style: preserve-3d;+ transform: perspective(800px) rotateX(var(--tilt-x)) rotateY(var(--tilt-y));+ transition: transform 0.6s cubic-bezier(0.03, 0.98, 0.52, 0.99);+ position: relative;+ isolation: isolate;+ will-change: transform;+}++.tilt-card::before {+ content: "";+ position: absolute;+ inset: 0;+ border-radius: inherit;+ background: radial-gradient(+ circle at var(--highlight-x) var(--highlight-y),+ oklch(1 0 0 / 0.07),+ transparent 60%+ );+ opacity: var(--highlight-opacity);+ transition: opacity 0.3s ease;+ pointer-events: none;+ z-index: 2;+}++.tilt-card::after {+ content: "";+ position: absolute;+ inset: -1px;+ border-radius: inherit;+ background: conic-gradient(+ from 180deg at 50% 50%,+ oklch(0.65 0.2 260 / 0.2),+ oklch(0.55 0.2 320 / 0.1),+ oklch(0.6 0.18 180 / 0.15),+ oklch(0.55 0.2 100 / 0.1),+ oklch(0.65 0.2 260 / 0.2)+ );+ z-index: -1;+ opacity: 0;+ transition: opacity 0.4s ease;+}++.tilt-card:hover::after {+ opacity: 1;+}++/* Stat gauge — accent bottom bar */+.stat-gauge {+ position: relative;+ overflow: hidden;+}++.stat-gauge::after {+ content: "";+ position: absolute;+ bottom: 0;+ left: 0;+ right: 0;+ height: 2px;+ background: oklch(0.65 0.2 260 / 0.4);+ transform: scaleX(0);+ transform-origin: left;+ transition: transform 0.6s cubic-bezier(0.22, 1, 0.36, 1) 0.3s;+}++.stat-gauge[data-active="true"]::after {+ transform: scaleX(1);+}++/* Spectrogram playback scan line — synced to audio */+@keyframes spectrogram-play {+ 0% {+ left: 0%;+ opacity: 1;+ }+ 95% {+ opacity: 1;+ }+ 100% {+ left: 100%;+ opacity: 0;+ }+}++.spectrogram-play {+ animation: spectrogram-play linear both;+}++/* Reduced motion: disable all referral effects */+@media (prefers-reduced-motion: reduce) {+ .referral-mesh-bg::before,+ .referral-mesh-bg::after {+ animation: none;+ }++ .tilt-card {+ transform: none !important;+ transition: none;+ }++ .tilt-card::before,+ .tilt-card::after {+ display: none;+ }++ .stat-gauge::after {+ transition: none;+ transform: scaleX(1);+ }++ .spectrogram-play {+ animation: none;+ opacity: 0;+ }++ .scanner-sweep-line {+ animation: none !important;+ top: 50% !important;+ opacity: 0.5 !important;+ }++ [data-scanner-progress] {+ animation: none !important;+ width: 60% !important;+ }+}+::-webkit-scrollbar {width: 6px;height: 6px;diff --git a/src/lib/neonAuth.ts b/src/lib/neonAuth.tsindex 58181aa44..6d80c7c0c 100644--- a/src/lib/neonAuth.ts+++ b/src/lib/neonAuth.ts@@ -73,7 +73,7 @@ function createAuthExpiredError(originalError: unknown): Error {return error;}-export function clearLastSignInTime(): void {+function clearLastSignInTime(): void {lastSignInTime = null;persistLastSignInTime(null);}@@ -98,19 +98,6 @@ export function isWithinGracePeriod(): boolean {return elapsed < GRACE_PERIOD_MS;}-export async function refreshSession(): Promise<boolean> {- if (!authClient) {- return false;- }-- try {- const result = await authClient.getSession();- return Boolean((result.data?.session as any)?.user);- } catch {- return false;- }-}-export async function signOut(): Promise<void> {try {if (window.electronAPI?.authClearSession) {@@ -128,7 +115,6 @@ export async function signOut(): Promise<void> {export async function withSessionRefresh<T>(operation: () => Promise<T>): Promise<T> {const startedInGracePeriod = isWithinGracePeriod();let graceRetriesUsed = 0;- let refreshAttempted = false;while (true) {try {@@ -150,15 +136,6 @@ export async function withSessionRefresh<T>(operation: () => Promise<T>): Promiscontinue;}- if (!refreshAttempted) {- refreshAttempted = true;- const refreshed = await refreshSession();- if (refreshed) {- continue;- }- }-- markSignedOutState();throw createAuthExpiredError(error);}}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 00af0b1ff..0687f5822 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "OpenWhispr wird geladen...",- "oauth": {- "redirectTitle": "Weiterleitung zu OpenWhispr",- "closeTab": "Sie können diesen Tab schließen"- },- "buttons": {- "cancelRecording": "Aufnahme abbrechen",- "cancelProcessing": "Verarbeitung abbrechen"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] zum Sprechen",- "recording": "Aufnahme läuft...",- "processing": "Verarbeitung...",- "clickToSpeak": "Klicken zum Sprechen"- },- "toasts": {- "hotkeyChanged": {- "title": "Hotkey geändert"- },- "hotkeyUnavailable": {- "title": "Hotkey nicht verfügbar",- "description": "Hotkey konnte nicht registriert werden. Bitte wählen Sie einen anderen in den Einstellungen."- }- },- "commandMenu": {- "startListening": "Aufnahme starten",- "stopListening": "Aufnahme stoppen",- "hideForNow": "Vorerst ausblenden"- }- },"settings": {"language": {"sectionTitle": "Sprache",@@ -119,7 +87,7 @@},"systemSettings": {"microphone": "Bitte öffnen Sie die Systemeinstellungen, um Mikrofonberechtigungen zu konfigurieren.",- "sound": "Bitte öffnen Sie die Sound-Einstellungen des Systems (z. B. pavucontrol).",+ "sound": "Bitte öffnen Sie die Sound-Einstellungen des Systems (z. B. pavucontrol).","accessibility": "Bedienungshilfen-Einstellungen sind auf dieser Plattform nicht verfügbar."},"titleBar": {@@ -172,10 +140,10 @@"availableModels": "Verfügbare Modelle","fast": "Schnell","hold": "Halten",- "less": "Weniger",- "more": "Mehr","private": "Privat",- "tap": "Tippen"+ "tap": "Tippen",+ "close": "Schließen",+ "dismiss": "Verwerfen"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "Zahlung aktualisieren"},"history": {- "title": "Transkriptionen","couldNotLoadTitle": "Verlauf konnte nicht geladen werden","couldNotLoadDescription": "Beim Laden der Transkriptionen ist ein Fehler aufgetreten. Bitte schließen Sie die App und öffnen Sie sie erneut.","copiedTitle": "Kopiert!","copiedDescription": "Text wurde in die Zwischenablage kopiert","couldNotCopyTitle": "Kopieren fehlgeschlagen","couldNotCopyDescription": "Beim Kopieren in die Zwischenablage ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.",- "clearTitle": "Verlauf löschen",- "clearDescription": "Dadurch werden alle Transkriptionen entfernt. Dies kann nicht rückgängig gemacht werden.",- "clearedTitle": "Verlauf gelöscht",- "clearedDescription": "{{count}} Transkription entfernt",- "clearedDescription_other": "{{count}} Transkriptionen entfernt",- "couldNotClearTitle": "Verlauf konnte nicht gelöscht werden",- "couldNotClearDescription": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.","deleteTitle": "Transkription löschen","deleteDescription": "Diese Transkription wird dauerhaft entfernt.","couldNotDeleteTitle": "Löschen fehlgeschlagen","couldNotDeleteDescription": "Diese Transkription wurde möglicherweise bereits entfernt.","couldNotDeleteDescriptionGeneric": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",- "clear": "Löschen","empty": "Noch keine Transkriptionen","press": "Drücken Sie",- "toStart": "zum Starten"+ "toStart": "zum Starten",+ "dateGroups": {+ "today": "Heute",+ "yesterday": "Gestern"+ }},"cloudMigration": {"title": "Willkommen bei OpenWhispr Pro",@@ -292,10 +255,8 @@"localDescription": "Läuft auf Ihrem Gerät. Volle Privatsphäre, funktioniert offline.","cloudDescription": "Leistungsstarke Modelle über API. Schnell und leistungsfähig, erfordert Internet."},- "enableTitle": "KI-Textverbesserung aktivieren",- "enableDescription": "KI verwenden, um die Transkriptionsqualität automatisch zu verbessern","custom": {- "endpointWithProtocol": "Geben Sie eine vollständige Basis-URL mit Protokoll ein (z. B. https://server/v1).",+ "endpointWithProtocol": "Geben Sie eine vollständige Basis-URL mit Protokoll ein (z. B. https://server/v1).","httpsRequired": "HTTPS erforderlich (HTTP nur im lokalen Netzwerk erlaubt).","endpointUnauthorized": "Der Endpoint hat die Anfrage abgelehnt (401/403). Fügen Sie einen API-Schlüssel hinzu oder passen Sie die Server-Authentifizierung an.","endpointTitle": "Endpoint-URL",@@ -536,7 +497,8 @@"continueWithGoogle": "Weiter mit Google"},"welcomeSubtitle": "Diktieren Sie überall mit Ihrer Stimme",- "welcomeTitle": "Willkommen bei OpenWhispr"+ "welcomeTitle": "Willkommen bei OpenWhispr",+ "sessionExpired": "Sitzung abgelaufen"},"cleanupPrompt": "Textbereinigung","developerSection": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Konto","app": "App",- "intelligence": "Intelligenz",- "profile": "Profil",- "speech": "Sprache",+ "speechAi": "Sprache & KI","system": "System"},"sections": {"account": {- "description": "Anmeldung & Nutzung",+ "description": "Profil & Anmeldung","label": "Konto"},- "agentConfig": {- "description": "Sprachagent-Einrichtung",- "label": "Agent"- },- "aiModels": {- "description": "Textbereinigung & -verbesserung",- "label": "KI-Modelle"- },- "developer": {- "description": "Protokolle, Diagnose & Daten",- "label": "Entwickler"- },- "dictionary": {- "description": "Eigene Wörter & Phrasen",- "label": "Wörterbuch"+ "plansBilling": {+ "description": "Tarife, Nutzung & Abrechnung",+ "label": "Tarife & Abrechnung"},"general": {- "description": "Darstellung, Hotkey & Start",+ "description": "Darstellung, Töne & Start","label": "Einstellungen"},- "permissions": {- "description": "Mikrofon & Bedienungshilfen",- "label": "Berechtigungen"- },- "privacy": {- "description": "Cloud-Backup & Analysen",- "label": "Datenschutz"- },- "prompts": {- "description": "System-Prompt-Studio",- "label": "Prompts"+ "hotkeys": {+ "description": "Diktat-Hotkey & Aktivierung",+ "label": "Hotkeys"},"transcription": {"description": "Sprache-zu-Text-Engine","label": "Transkription"+ },+ "intelligence": {+ "description": "KI-Modelle, Agent & Prompts",+ "label": "Intelligenz"+ },+ "privacyData": {+ "description": "Datenschutz, Berechtigungen & Analyse",+ "label": "Datenschutz & Daten"+ },+ "system": {+ "description": "Updates, Speicher & Entwicklertools",+ "label": "System"}},"title": "Einstellungen"@@ -933,6 +886,51 @@"trial": "Testversion"},"planTitle": "Tarif",+ "pricing": {+ "title": "Tarife",+ "monthly": "Monatlich",+ "annual": "Jährlich",+ "annualBadge": "17 % sparen",+ "free": {+ "name": "Kostenlos",+ "price": "$0",+ "period": "für immer",+ "trialNote": "Enthält 7 Tage OpenWhispr Pro gratis",+ "features": [+ "2.000 Wörter/Woche",+ "Lokale KI-Modelle",+ "Eigene Schlüssel verwenden",+ "Wörterbuch und Snippets",+ "Unterstützung für 100+ Sprachen",+ "Keine Datenspeicherung"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/Monat",+ "annualPrice": "$80",+ "annualPeriod": "/Jahr",+ "features": [+ "Alles aus Kostenlos",+ "Unbegrenzte Nutzung",+ "Echtzeit-Transkription",+ "Neueste Audio- & KI-Modelle",+ "iOS/Android (demnächst)",+ "Keine Datenspeicherung",+ "Vorrangiger Support"+ ],+ "cta": "Jetzt starten",+ "switchToAnnual": "Zu Jährlich wechseln"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "Individuell",+ "features": ["Cloud-Synchronisation", "Team-Funktionen (demnächst)", "SSO & Compliance"],+ "cta": "Kontakt aufnehmen"+ },+ "currentPlan": "Aktueller Tarif"+ },"rollingWeeklyLimit": "Rollierendes Wochenlimit","signOut": {"failedDescription": "Beim Abmelden ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.",@@ -941,6 +939,9 @@"signingOut": "Abmeldung läuft..."},"signedIn": "Angemeldet",+ "signedOutPlans": {+ "button": "Kostenloses Konto erstellen"+ },"title": "Konto","toasts": {"approachingLimit": {@@ -970,7 +971,7 @@"howItWorksDescription": "Wenn Sie 'Hey {{agentName}}' gefolgt von einer Anweisung sagen, wechselt die KI vom Bereinigungsmodus in den Anweisungsmodus. Ohne die Triggerphrase wird Ihr Diktat einfach bereinigt.","howItWorksTitle": "So funktioniert es","instructionMode": "Anweisung",- "placeholder": "z. B. Jarvis, Nova, Atlas...",+ "placeholder": "z. B. Jarvis, Nova, Atlas...","save": "Speichern","title": "Sprachagent"},@@ -1023,26 +1024,6 @@"resetAppData": "App-Daten zurücksetzen","resetAppDataDescription": "Alle Einstellungen, Transkriptionen und zwischengespeicherten Daten dauerhaft löschen"},- "dictionary": {- "add": "Hinzufügen",- "addWordOrPhrase": "Wort oder Phrase hinzufügen",- "agentNameAutoManaged": "Agent-Name (automatisch verwaltet)",- "clearAll": "Alle löschen",- "clearDictionaryDescription": "Dadurch werden alle Wörter aus Ihrem benutzerdefinierten Wörterbuch entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",- "clearDictionaryTitle": "Wörterbuch leeren?",- "description": "Fügen Sie Wörter, Namen oder Fachbegriffe hinzu, um die Transkriptionsgenauigkeit zu verbessern",- "howItWorksDescription": "Hinzugefügte Wörter werden in den KI-Prompt aufgenommen, damit das Modell diese Begriffe bei der Transkriptionsbereinigung erkennt und beibehält.",- "howItWorksTitle": "So funktioniert es",- "noWords": "Noch keine Wörter hinzugefügt",- "placeholder": "z. B. OpenWhispr, Kubernetes, Dr. Martinez...",- "pressEnterToAdd": "Enter drücken zum Hinzufügen",- "removeWord": "Wort entfernen",- "tipDescription": "Fügen Sie Eigennamen, Fachbegriffe oder andere Wörter hinzu, die möglicherweise falsch transkribiert werden.",- "tipLabel": "Tipp",- "title": "Benutzerdefiniertes Wörterbuch",- "wordsAppearHere": "Hinzugefügte Wörter erscheinen hier",- "yourWords": "Ihre Wörter"- },"general": {"appearance": {"auto": "Auto",@@ -1062,6 +1043,7 @@"hotkey": {"activationMode": "Aktivierungsmodus","description": "Die Tastenkombination, die das Sprachdiktat startet und stoppt",+ "resetToDefault": "Auf {{hotkey}} zurücksetzen","title": "Diktat-Hotkey"},"microphone": {@@ -1245,5 +1227,284 @@"openai_oss_gpt_oss_20b_mxfp4": "Open-Weight-Modell von OpenAI für Consumer-Hardware"}}+ },+ "referral": {+ "title": "Empfehlen und Belohnungen erhalten",+ "subtitle": "Schenke einen Monat. Erhalte einen Monat.",+ "modalTitle": "Freunde einladen",+ "tabs": {+ "refer": "Empfehlen",+ "pastInvites": "Vergangene Einladungen"+ },+ "howItWorks": {+ "shareLink": "Teile deinen Einladungslink",+ "theySignUp": "Sie registrieren sich und erhalten einen ",+ "freeMonthOfPro": "kostenlosen Monat Pro",+ "youGet": "Du erhältst einen ",+ "freeMonth": "kostenlosen Monat",+ "whenTheyDictate": " wenn sie 2.000 Wörter diktieren"+ },+ "inviteLink": {+ "title": "Dein Einladungslink",+ "copy": "Kopieren",+ "copied": "Kopiert"+ },+ "sendInvites": {+ "title": "Einladungen senden",+ "placeholder": "[email protected]",+ "send": "Senden",+ "sending": "Wird gesendet"+ },+ "stats": {+ "referred": "Empfohlen",+ "converted": "Umgewandelt",+ "monthsEarned": "Verdiente Monate"+ },+ "status": {+ "converted": "Umgewandelt",+ "opened": "Geöffnet",+ "failed": "Fehlgeschlagen",+ "sent": "Gesendet"+ },+ "empty": {+ "title": "Noch keine Einladungen gesendet",+ "description": "Teile deinen Link oder sende eine Einladung, um loszulegen"+ },+ "toasts": {+ "copiedTitle": "Kopiert!",+ "copiedDescription": "Empfehlungslink in die Zwischenablage kopiert",+ "copyFailedTitle": "Kopieren fehlgeschlagen",+ "copyFailedDescription": "Link konnte nicht in die Zwischenablage kopiert werden",+ "invalidEmailTitle": "Ungültige E-Mail",+ "invalidEmailDescription": "Bitte gib eine gültige E-Mail-Adresse ein",+ "inviteSentTitle": "Einladung gesendet!",+ "inviteSentDescription": "Einladung an {{email}} gesendet",+ "sendFailedTitle": "Senden fehlgeschlagen",+ "sendFailedDescription": "Einladung konnte nicht gesendet werden. Bitte versuche es erneut."+ },+ "errors": {+ "unableToLoad": "Empfehlungsdaten konnten nicht geladen werden",+ "unableToLoadStats": "Empfehlungsstatistiken konnten nicht geladen werden. Bitte versuche es später erneut."+ },+ "tryAgain": "Erneut versuchen",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Deine Audio-Signatur",+ "stop": "Stopp",+ "playSignal": "Signal abspielen"+ },+ "friends": {+ "title": "Freunde",+ "completed": "Abgeschlossen",+ "sentInvites": "Gesendete Einladungen"+ }+ },+ "notes": {+ "folders": {+ "title": "Ordner",+ "soon": "Demnächst",+ "folderName": "Ordnername",+ "couldNotCreate": "Ordner konnte nicht erstellt werden",+ "couldNotRename": "Ordner konnte nicht umbenannt werden",+ "couldNotDelete": "Ordner konnte nicht gelöscht werden"+ },+ "list": {+ "title": "Notizen",+ "newNote": "Neue Notiz",+ "untitled": "Unbenannt",+ "untitledNote": "Unbenannte Notiz",+ "timeNow": "Jetzt",+ "minutesAgo": "vor {{count}}m",+ "hoursAgo": "vor {{count}}h",+ "daysAgo": "vor {{count}}T"+ },+ "editor": {+ "untitled": "Unbenannt",+ "noteTitle": "Notiztitel",+ "stop": "Stopp",+ "transcribe": "Transkribieren",+ "processing": "Verarbeitung...",+ "export": "Exportieren",+ "asMarkdown": "Als Markdown",+ "asPlainText": "Als Klartext",+ "raw": "Roh",+ "enhanced": "Verbessert",+ "saving": "Wird gespeichert",+ "wordsCount": "{{count}} Wörter",+ "startWriting": "Schreibe los...",+ "staleIndicator": "Der Inhalt hat sich seit der Verbesserung geändert"+ },+ "upload": {+ "title": "Audio hochladen",+ "using": "Verwendet {{model}}",+ "dropOrBrowse": "Audiodatei ablegen oder klicken zum Durchsuchen",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Zum Hochladen ablegen",+ "transcribe": "Transkribieren",+ "cancel": "Abbrechen",+ "transcribingCloud": "Wird über die Cloud transkribiert...",+ "transcribingLocal": "Wird lokal transkribiert...",+ "transcribingProvider": "Wird über {{provider}} transkribiert...",+ "transcriptionComplete": "Transkription abgeschlossen",+ "openNote": "Notiz öffnen",+ "uploadAnother": "Weitere hochladen",+ "retry": "Erneut versuchen",+ "startOver": "Neu beginnen",+ "transcriptionSettings": "Transkriptionseinstellungen",+ "newFolder": "Neuer Ordner",+ "folderName": "Ordnername",+ "create": "Erstellen",+ "setupTitle": "Transkription einrichten",+ "setupDescription": "Wähle, wie dein Audio transkribiert werden soll. Dies gilt auch für die Live-Diktierfunktion.",+ "continue": "Weiter",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Benutzerdefiniert",+ "selectFolder": "Ordner auswählen",+ "transcriptionFailed": "Transkription fehlgeschlagen",+ "errorOccurred": "Ein Fehler ist aufgetreten",+ "noProviderTitle": "Kein Transkriptionsanbieter eingerichtet",+ "noProviderDescription": "Fügen Sie einen API-Schlüssel hinzu oder laden Sie ein lokales Modell herunter, um mit der Transkription zu beginnen.",+ "noProviderAction": "Transkriptionseinstellungen öffnen"+ },+ "meeting": {+ "title": "Besprechungsnotizen",+ "description": "Sprechererkennung und strukturierte Zusammenfassungen",+ "comingSoon": "Demnächst verfügbar"+ },+ "context": {+ "moveToFolder": "In Ordner verschieben",+ "delete": "Löschen",+ "rename": "Umbenennen",+ "searchFolders": "Ordner suchen...",+ "noResults": "Keine Ordner gefunden",+ "newFolder": "Neuer Ordner"+ },+ "actions": {+ "manage": "Aktionen verwalten...",+ "manageTitle": "Benutzerdefinierte Aktionen",+ "addAction": "Neue Aktion",+ "editAction": "Aktion bearbeiten",+ "namePlaceholder": "Name der Aktion",+ "descriptionPlaceholder": "Kurzbeschreibung (optional)",+ "promptPlaceholder": "Was soll die KI mit dem Notizeninhalt tun?",+ "builtIn": "Integriert",+ "save": "Speichern",+ "update": "Aktualisieren",+ "cancel": "Abbrechen",+ "noActions": "Noch keine benutzerdefinierten Aktionen",+ "runAction": "{{name}} ausführen",+ "selectAction": "Aktion auswählen",+ "done": "Fertig",+ "builtin": {+ "cleanupNotes": {+ "name": "Notizen bereinigen",+ "description": "Grammatik, Struktur und Formatierung verbessern"+ }+ }+ },+ "empty": {+ "title": "Noch keine Notizen hier",+ "description": "Erstelle deine erste Notiz, um loszuschreiben",+ "selectTitle": "Notiz auswählen",+ "selectDescription": "Wähle eine Notiz aus der Seitenleiste",+ "createNote": "Notiz erstellen",+ "emptyFolder": "Keine Notizen in diesem Ordner"+ },+ "addToFolder": {+ "title": "Notizen hinzufügen",+ "searchPlaceholder": "Notizen zum Hinzufügen suchen...",+ "addExisting": "Vorhandene hinzufügen",+ "addCount": "{{count}} Notizen hinzufügen",+ "noResults": "Keine passenden Notizen",+ "noNotesAvailable": "Keine weiteren Notizen verfügbar",+ "today": "Heute",+ "yesterday": "Gestern"+ },+ "onboarding": {+ "llm": {+ "title": "KI-Modell konfigurieren",+ "description": "Aktionen verwenden KI, um Ihre Notizen zu transformieren. Richten Sie ein Sprachmodell ein, um loszulegen.",+ "configured": "KI-Modell konfiguriert"+ },+ "actions": {+ "title": "KI-gestützte Aktionen",+ "description": "Aktionen transformieren Ihre Notizen – bereinigen Transkriptionen, fassen Besprechungen zusammen und mehr. Verwenden Sie integrierte Aktionen oder erstellen Sie eigene.",+ "builtInLabel": "Integriert",+ "createTitle": "Eigene Aktion erstellen",+ "createDescription": "Definieren Sie eine benutzerdefinierte Aktion mit Ihrem eigenen KI-Prompt. Sie können später jederzeit weitere hinzufügen oder bearbeiten.",+ "created": "Erstellt!"+ },+ "getStarted": "Loslegen"+ },+ "realtimeBanner": {+ "message": "Echtzeit-Transkription mit Pro verfügbar",+ "upgrade": "Upgraden"+ }+ },+ "dictionary": {+ "addWord": "Wort hinzufügen",+ "removeWord": "{{word}} entfernen",+ "clearAll": "Alle löschen",+ "howItWorks": "So funktioniert es",+ "howItWorksDetail": "Hinzugefügte Wörter werden in den KI-Prompt aufgenommen, damit das Modell diese Begriffe bei der Transkriptionsbereinigung erkennt und beibehält.",+ "autoManaged": "Agent-Name (automatisch verwaltet)",+ "inputHint": "Enter drücken zum Hinzufügen",+ "title": "Benutzerdefiniertes Wörterbuch",+ "description": "Bringe der KI dein Vokabular bei – Namen, Fachbegriffe und Ausdrücke, die sie sonst übersehen könnte",+ "clearTitle": "Wörterbuch leeren?",+ "clearDescription": "Dadurch werden alle Wörter aus deinem benutzerdefinierten Wörterbuch entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",+ "addPlaceholder": "Ein Wort oder eine Phrase hinzufügen..."+ },+ "sidebar": {+ "home": "Startseite",+ "notes": "Notizen",+ "upload": "Hochladen",+ "dictionary": "Wörterbuch",+ "referral": "Gratis-Monat erhalten",+ "settings": "Einstellungen",+ "support": "Support",+ "limitReached": "Wochenlimit erreicht",+ "limitReachedDescription": "Upgraden Sie auf Pro für unbegrenzte Transkriptionen.",+ "upgradeToPro": "Auf Pro upgraden",+ "upgradeTitle": "Auf Pro upgraden",+ "upgradeDescription": "Unbegrenzte Transkriptionen und mehr.",+ "learnMore": "Mehr erfahren",+ "defaultUser": "Benutzer",+ "notSignedIn": "Nicht angemeldet"+ },+ "usage": {+ "approachingLimit": "Wochenlimit fast erreicht",+ "approachingLimitDescription": "Du hast diese Woche {{wordsUsed}} von {{limit}} kostenlosen Wörtern verwendet.",+ "yourPlan": "Dein Tarif",+ "trial": "Testphase (noch {{days}} Tag)",+ "trial_other": "Testphase (noch {{days}} Tage)",+ "pro": "Pro",+ "unlimitedTrial": "Unbegrenzte Transkriptionen während deiner Testphase",+ "unlimited": "Unbegrenzte Transkriptionen",+ "manageSubscription": "Abonnement verwalten",+ "weeklyUsage": "Wöchentliche Nutzung",+ "limitReached": "Limit erreicht",+ "free": "Kostenlos",+ "wordsRemaining": "Noch {{remaining}} Wörter",+ "rollingLimit": "Rollierendes Wochenlimit",+ "upgradeToPro": "Auf Pro upgraden",+ "useYourOwnKey": "Eigenen API-Schlüssel verwenden",+ "upgradeUnlimited": "Auf Pro upgraden – unbegrenzte Transkriptionen"+ },+ "support": {+ "joinDiscord": "Discord beitreten",+ "contactSupport": "Support kontaktieren",+ "submitBug": "Fehler melden"+ },+ "apiKeyInput": {+ "placeholder": "API-Schlüssel eingeben",+ "label": "API-Schlüssel",+ "save": "Speichern",+ "cancelEdit": "Bearbeitung abbrechen",+ "edit": "Bearbeiten",+ "add": "Hinzufügen",+ "editButton": "Bearbeiten",+ "addButton": "Hinzufügen"}}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 8301ffd61..5587424a7 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Loading OpenWhispr...",- "oauth": {- "redirectTitle": "Redirecting to OpenWhispr",- "closeTab": "You can close this tab"- },- "buttons": {- "cancelRecording": "Cancel recording",- "cancelProcessing": "Cancel processing"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] to speak",- "recording": "Recording...",- "processing": "Processing...",- "clickToSpeak": "Click to speak"- },- "toasts": {- "hotkeyChanged": {- "title": "Hotkey Changed"- },- "hotkeyUnavailable": {- "title": "Hotkey Unavailable",- "description": "Could not register hotkey. Please set a different hotkey in Settings."- }- },- "commandMenu": {- "startListening": "Start listening",- "stopListening": "Stop listening",- "hideForNow": "Hide this for now"- }- },"settings": {"language": {"sectionTitle": "Language",@@ -172,10 +140,10 @@"availableModels": "Available Models","fast": "Fast","hold": "Hold",- "less": "Less",- "more": "More","private": "Private",- "tap": "Tap"+ "tap": "Tap",+ "close": "Close",+ "dismiss": "Dismiss"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "Update Payment"},"history": {- "title": "Transcriptions","couldNotLoadTitle": "Couldn't load your history","couldNotLoadDescription": "Something went wrong loading your transcriptions. Try closing and reopening the app.","copiedTitle": "Copied!","copiedDescription": "Text copied to your clipboard","couldNotCopyTitle": "Couldn't copy","couldNotCopyDescription": "Something went wrong copying to your clipboard. Try again.",- "clearTitle": "Clear History",- "clearDescription": "This will remove all your transcriptions. You can't undo this.",- "clearedTitle": "History cleared",- "clearedDescription": "{{count}} transcription removed",- "clearedDescription_other": "{{count}} transcriptions removed",- "couldNotClearTitle": "Couldn't clear history",- "couldNotClearDescription": "Something went wrong. Please try again.","deleteTitle": "Delete Transcription","deleteDescription": "This transcription will be permanently removed.","couldNotDeleteTitle": "Couldn't delete","couldNotDeleteDescription": "This transcription may have already been removed.","couldNotDeleteDescriptionGeneric": "Something went wrong. Please try again.",- "clear": "Clear","empty": "No transcriptions yet","press": "Press",- "toStart": "to start"+ "toStart": "to start",+ "dateGroups": {+ "today": "Today",+ "yesterday": "Yesterday"+ }},"cloudMigration": {"title": "Welcome to OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "Runs on your device. Complete privacy, works offline.","cloudDescription": "Advanced models via API. Fast and capable, requires internet."},- "enableTitle": "Enable AI Text Enhancement",- "enableDescription": "Use AI to automatically improve transcription quality","custom": {"endpointWithProtocol": "Enter a full base URL including protocol (for example, https://server/v1).","httpsRequired": "HTTPS required (HTTP allowed for local network only).",@@ -536,7 +497,8 @@"continueWithGoogle": "Continue with Google"},"welcomeSubtitle": "Dictate anywhere using your voice",- "welcomeTitle": "Welcome to OpenWhispr"+ "welcomeTitle": "Welcome to OpenWhispr",+ "sessionExpired": "Session expired. Please restart the sign-up process."},"cleanupPrompt": "Cleanup","developerSection": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Account","app": "App",- "intelligence": "Intelligence",- "profile": "Profile",- "speech": "Speech",+ "speechAi": "Speech & AI","system": "System"},"sections": {"account": {- "description": "Sign in & usage",+ "description": "Profile & sign in","label": "Account"},- "agentConfig": {- "description": "Voice agent setup",- "label": "Agent"- },- "aiModels": {- "description": "Text cleanup & enhancement",- "label": "AI Models"- },- "developer": {- "description": "Logs, diagnostics & data",- "label": "Developer"- },- "dictionary": {- "description": "Custom words & phrases",- "label": "Dictionary"+ "plansBilling": {+ "description": "Plans, usage & billing",+ "label": "Plans & Billing"},"general": {- "description": "Appearance, hotkey & startup",+ "description": "Appearance, sounds & startup","label": "Preferences"},- "permissions": {- "description": "Microphone & accessibility",- "label": "Permissions"- },- "privacy": {- "description": "Cloud backup & analytics",- "label": "Privacy"- },- "prompts": {- "description": "System prompt studio",- "label": "Prompts"+ "hotkeys": {+ "description": "Dictation hotkey & activation",+ "label": "Hotkeys"},"transcription": {"description": "Speech-to-text engine","label": "Transcription"+ },+ "intelligence": {+ "description": "AI models, agent & prompts",+ "label": "Intelligence"+ },+ "privacyData": {+ "description": "Privacy, permissions & analytics",+ "label": "Privacy & Data"+ },+ "system": {+ "description": "Updates, storage & developer tools",+ "label": "System"}},"title": "Settings"@@ -933,6 +886,51 @@"trial": "Trial"},"planTitle": "Plan",+ "pricing": {+ "title": "Plans",+ "monthly": "Monthly",+ "annual": "Annual",+ "annualBadge": "Save 17%",+ "free": {+ "name": "Free",+ "price": "$0",+ "period": "forever",+ "trialNote": "Includes 7 days free of OpenWhispr Pro",+ "features": [+ "2,000 words/week",+ "Local AI models",+ "Bring your own keys",+ "Dictionary and snippets",+ "Support for 100+ languages",+ "Zero data retention"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/mo",+ "annualPrice": "$80",+ "annualPeriod": "/yr",+ "features": [+ "Everything in Free",+ "Unlimited usage",+ "Real-time transcription",+ "Latest audio & AI models",+ "iOS/Android (coming soon)",+ "Zero data retention",+ "Priority support"+ ],+ "cta": "Get Started",+ "switchToAnnual": "Switch to Annual"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "Custom",+ "features": ["Cloud sync", "Team features (coming soon)", "SSO & compliance"],+ "cta": "Contact Us"+ },+ "currentPlan": "Current plan"+ },"rollingWeeklyLimit": "Rolling weekly limit","signOut": {"failedDescription": "Something went wrong signing out. Please try again.",@@ -953,6 +951,9 @@"description": "Unlimited transcriptions, priority processing, and more.","title": "Try Pro free for 7 days"},+ "signedOutPlans": {+ "button": "Create Free Account"+ },"user": "User","wordsRemaining": "{{remaining}} remaining"},@@ -1023,26 +1024,6 @@"resetAppData": "Reset app data","resetAppDataDescription": "Permanently delete all settings, transcriptions, and cached data"},- "dictionary": {- "add": "Add",- "addWordOrPhrase": "Add a word or phrase",- "agentNameAutoManaged": "Agent name (auto-managed)",- "clearAll": "Clear all",- "clearDictionaryDescription": "This will remove all words from your custom dictionary. This action cannot be undone.",- "clearDictionaryTitle": "Clear dictionary?",- "description": "Add words, names, or technical terms to improve transcription accuracy",- "howItWorksDescription": "Words you add are included in the AI prompt so the model knows to look for and preserve these terms during transcription cleanup.",- "howItWorksTitle": "How it works",- "noWords": "No words added yet",- "placeholder": "e.g. OpenWhispr, Kubernetes, Dr. Martinez...",- "pressEnterToAdd": "Press Enter to add",- "removeWord": "Remove word",- "tipDescription": "Add proper nouns, technical terms, or any word that might be transcribed incorrectly.",- "tipLabel": "Tip",- "title": "Custom Dictionary",- "wordsAppearHere": "Words you add will appear here",- "yourWords": "Your words"- },"general": {"appearance": {"auto": "Auto",@@ -1062,6 +1043,7 @@"hotkey": {"activationMode": "Activation Mode","description": "The key combination that starts and stops voice dictation",+ "resetToDefault": "Reset to {{hotkey}}","title": "Dictation Hotkey"},"microphone": {@@ -1245,5 +1227,284 @@"openai_oss_gpt_oss_20b_mxfp4": "OpenAI's open-weight model for consumer hardware"}}+ },+ "sidebar": {+ "home": "Home",+ "notes": "Notes",+ "upload": "Upload",+ "dictionary": "Dictionary",+ "referral": "Get a free month",+ "settings": "Settings",+ "support": "Support",+ "limitReached": "Weekly limit reached",+ "limitReachedDescription": "Upgrade to Pro for unlimited transcriptions.",+ "upgradeToPro": "Upgrade to Pro",+ "upgradeTitle": "Upgrade to Pro",+ "upgradeDescription": "Unlimited transcriptions and premium features.",+ "learnMore": "Learn more",+ "defaultUser": "User",+ "notSignedIn": "Not signed in"+ },+ "referral": {+ "title": "Refer and earn rewards",+ "modalTitle": "Refer and earn rewards",+ "subtitle": "Give a month. Get a month.",+ "tabs": {+ "refer": "Refer",+ "pastInvites": "Past invites"+ },+ "howItWorks": {+ "shareLink": "Share your invite link",+ "theySignUp": "They sign up and get a ",+ "freeMonthOfPro": "free month of Pro",+ "youGet": "You get a ",+ "freeMonth": "free month",+ "whenTheyDictate": " when they dictate 2,000 words"+ },+ "inviteLink": {+ "title": "Your invite link",+ "copy": "Copy",+ "copied": "Copied"+ },+ "sendInvites": {+ "title": "Send invites",+ "placeholder": "[email protected]",+ "send": "Send",+ "sending": "Sending"+ },+ "stats": {+ "referred": "Referred",+ "converted": "Converted",+ "monthsEarned": "Months earned"+ },+ "status": {+ "converted": "Converted",+ "opened": "Opened",+ "failed": "Failed",+ "sent": "Sent"+ },+ "friends": {+ "title": "Friends",+ "completed": "Completed",+ "sentInvites": "Sent invites"+ },+ "empty": {+ "title": "No invites sent yet",+ "description": "Share your link or send an invite to get started"+ },+ "toasts": {+ "copiedTitle": "Copied!",+ "copiedDescription": "Referral link copied to clipboard",+ "copyFailedTitle": "Copy Failed",+ "copyFailedDescription": "Failed to copy link to clipboard",+ "invalidEmailTitle": "Invalid Email",+ "invalidEmailDescription": "Please enter a valid email address",+ "inviteSentTitle": "Invite Sent!",+ "inviteSentDescription": "Invitation sent to {{email}}",+ "sendFailedTitle": "Send Failed",+ "sendFailedDescription": "Failed to send invitation. Please try again."+ },+ "errors": {+ "unableToLoad": "Unable to load referral data",+ "unableToLoadStats": "Unable to load referral stats. Please try again later."+ },+ "tryAgain": "Try Again",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Your audio signature",+ "stop": "Stop",+ "playSignal": "Play signal"+ }+ },+ "usage": {+ "approachingLimit": "Approaching Weekly Limit",+ "approachingLimitDescription": "You've used {{wordsUsed}} of {{limit}} free words this week.",+ "yourPlan": "Your Plan",+ "trial": "Trial ({{days}} day left)",+ "trial_other": "Trial ({{days}} days left)",+ "pro": "Pro",+ "unlimitedTrial": "Unlimited transcriptions during your trial",+ "unlimited": "Unlimited transcriptions",+ "manageSubscription": "Manage Subscription",+ "weeklyUsage": "Weekly Usage",+ "limitReached": "Limit reached",+ "free": "Free",+ "wordsRemaining": "{{remaining}} words remaining",+ "rollingLimit": "Rolling weekly limit",+ "upgradeToPro": "Upgrade to Pro",+ "useYourOwnKey": "Use Your Own Key",+ "upgradeUnlimited": "Upgrade to Pro — unlimited transcriptions"+ },+ "notes": {+ "folders": {+ "title": "Folders",+ "soon": "Soon",+ "folderName": "Folder name",+ "couldNotCreate": "Couldn't create folder",+ "couldNotRename": "Couldn't rename folder",+ "couldNotDelete": "Couldn't delete folder"+ },+ "list": {+ "title": "Notes",+ "newNote": "New note",+ "untitled": "Untitled",+ "untitledNote": "Untitled Note",+ "timeNow": "now",+ "minutesAgo": "{{count}}m",+ "hoursAgo": "{{count}}h",+ "daysAgo": "{{count}}d"+ },+ "editor": {+ "untitled": "Untitled",+ "noteTitle": "Note title",+ "stop": "Stop",+ "transcribe": "Transcribe",+ "processing": "Processing...",+ "export": "Export",+ "asMarkdown": "As Markdown",+ "asPlainText": "As Plain Text",+ "raw": "Raw",+ "enhanced": "Enhanced",+ "saving": "Saving",+ "wordsCount": "{{count}} words",+ "startWriting": "Start writing...",+ "staleIndicator": "Content has changed since enhancement"+ },+ "upload": {+ "title": "Upload Audio",+ "using": "Using {{model}}",+ "dropOrBrowse": "Drop audio file or click to browse",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Drop to upload",+ "transcribe": "Transcribe",+ "cancel": "Cancel",+ "transcribingCloud": "Transcribing via cloud...",+ "transcribingLocal": "Transcribing locally...",+ "transcribingProvider": "Transcribing via {{provider}}...",+ "transcriptionComplete": "Transcription complete",+ "openNote": "Open Note",+ "uploadAnother": "Upload Another",+ "retry": "Retry",+ "startOver": "Start Over",+ "transcriptionSettings": "Transcription Settings",+ "newFolder": "New Folder",+ "folderName": "Folder name",+ "create": "Create",+ "setupTitle": "Set up transcription",+ "setupDescription": "Choose how to transcribe your audio. This also applies to live dictation.",+ "continue": "Continue",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Custom",+ "selectFolder": "Select folder",+ "transcriptionFailed": "Transcription failed",+ "errorOccurred": "An error occurred",+ "noProviderTitle": "No transcription provider set up",+ "noProviderDescription": "Add an API key or download a local model to start transcribing.",+ "noProviderAction": "Open Transcription Settings"+ },+ "meeting": {+ "title": "Meeting Notes",+ "description": "Speaker identification & structured summaries",+ "comingSoon": "Coming Soon"+ },+ "empty": {+ "title": "No notes here yet",+ "description": "Create your first note to start writing",+ "selectTitle": "Select a note",+ "selectDescription": "Choose a note from the sidebar",+ "createNote": "Create note",+ "emptyFolder": "No notes in this folder"+ },+ "addToFolder": {+ "title": "Add notes",+ "searchPlaceholder": "Search notes to add...",+ "addExisting": "Add existing",+ "addCount": "Add {{count}} notes",+ "noResults": "No matching notes",+ "noNotesAvailable": "No other notes available",+ "today": "Today",+ "yesterday": "Yesterday"+ },+ "context": {+ "moveToFolder": "Move to folder",+ "delete": "Delete",+ "rename": "Rename",+ "searchFolders": "Search folders...",+ "noResults": "No folders found",+ "newFolder": "New folder"+ },+ "actions": {+ "done": "Done",+ "manage": "Manage Actions...",+ "manageTitle": "Custom Actions",+ "addAction": "New Action",+ "editAction": "Edit Action",+ "namePlaceholder": "Action name",+ "descriptionPlaceholder": "Brief description (optional)",+ "promptPlaceholder": "What should the AI do with the note content?",+ "builtIn": "Built-in",+ "save": "Save",+ "update": "Update",+ "cancel": "Cancel",+ "noActions": "No custom actions yet",+ "runAction": "Run {{name}}",+ "selectAction": "Select action",+ "builtin": {+ "cleanupNotes": {+ "name": "Clean Up Notes",+ "description": "Fix grammar, structure, and formatting"+ }+ }+ },+ "onboarding": {+ "llm": {+ "title": "Configure an AI model",+ "description": "Actions use AI to transform your notes. Set up a language model to get started.",+ "configured": "AI model configured"+ },+ "actions": {+ "title": "AI-Powered Actions",+ "description": "Actions transform your notes — clean up transcriptions, summarize meetings, and more. Use built-in actions or create your own.",+ "builtInLabel": "Built-in",+ "createTitle": "Create your own action",+ "createDescription": "Define a custom action with your own AI prompt. You can always edit or add more later in settings.",+ "created": "Created!"+ },+ "getStarted": "Get Started"+ },+ "realtimeBanner": {+ "message": "Real-time transcription available on Pro",+ "upgrade": "Upgrade"+ }+ },+ "dictionary": {+ "title": "Custom Dictionary",+ "description": "Teach the AI your vocabulary — names, jargon, and terms it might otherwise miss",+ "clearTitle": "Clear dictionary?",+ "clearDescription": "This will remove all words from your custom dictionary. This action cannot be undone.",+ "addWord": "Add word",+ "addPlaceholder": "Add a word or phrase...",+ "removeWord": "Remove {{word}}",+ "clearAll": "Clear all",+ "howItWorks": "How it works",+ "howItWorksDetail": "Words are fed as context hints to the speech model, helping it recognize uncommon terms. For difficult words, try adding context like \"The word is Synty\" alongside the word itself.",+ "autoManaged": "Auto-managed — synced from agent name",+ "inputHint": "Separate multiple words with commas. Add context phrases like \"The word is Synty\" for better recognition."+ },+ "support": {+ "joinDiscord": "Join Discord",+ "contactSupport": "Contact Support",+ "submitBug": "Submit Bug"+ },+ "apiKeyInput": {+ "placeholder": "Paste your API key",+ "label": "API Key",+ "save": "Save API key",+ "cancelEdit": "Cancel editing",+ "edit": "Edit API key",+ "add": "Add API key",+ "editButton": "edit",+ "addButton": "add"}}diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 0852278e4..fe5f08768 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Cargando OpenWhispr...",- "oauth": {- "redirectTitle": "Redirigiendo a OpenWhispr",- "closeTab": "Puedes cerrar esta pestaña"- },- "buttons": {- "cancelRecording": "Cancelar grabación",- "cancelProcessing": "Cancelar procesamiento"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] para hablar",- "recording": "Grabando...",- "processing": "Procesando...",- "clickToSpeak": "Haz clic para hablar"- },- "toasts": {- "hotkeyChanged": {- "title": "Atajo cambiado"- },- "hotkeyUnavailable": {- "title": "Atajo no disponible",- "description": "No se pudo registrar el atajo. Configura uno diferente en Ajustes."- }- },- "commandMenu": {- "startListening": "Iniciar escucha",- "stopListening": "Detener escucha",- "hideForNow": "Ocultar por ahora"- }- },"settings": {"language": {"sectionTitle": "Idioma",@@ -172,10 +140,10 @@"availableModels": "Modelos disponibles","fast": "Rápido","hold": "Mantener",- "less": "Menos",- "more": "Más","private": "Privado",- "tap": "Pulsar"+ "tap": "Pulsar",+ "close": "Cerrar",+ "dismiss": "Descartar"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "Actualizar pago"},"history": {- "title": "Transcripciones","couldNotLoadTitle": "No se pudo cargar tu historial","couldNotLoadDescription": "Ocurrió un problema al cargar tus transcripciones. Cierra y abre la app de nuevo.","copiedTitle": "¡Copiado!","copiedDescription": "Texto copiado al portapapeles","couldNotCopyTitle": "No se pudo copiar","couldNotCopyDescription": "Ocurrió un problema al copiar al portapapeles. Inténtalo de nuevo.",- "clearTitle": "Borrar historial",- "clearDescription": "Esto eliminará todas tus transcripciones. No se puede deshacer.",- "clearedTitle": "Historial borrado",- "clearedDescription": "{{count}} transcripción eliminada",- "clearedDescription_other": "{{count}} transcripciones eliminadas",- "couldNotClearTitle": "No se pudo borrar el historial",- "couldNotClearDescription": "Algo salió mal. Inténtalo de nuevo.","deleteTitle": "Eliminar transcripción","deleteDescription": "Esta transcripción se eliminará permanentemente.","couldNotDeleteTitle": "No se pudo eliminar","couldNotDeleteDescription": "Puede que esta transcripción ya se haya eliminado.","couldNotDeleteDescriptionGeneric": "Algo salió mal. Inténtalo de nuevo.",- "clear": "Borrar","empty": "Aún no hay transcripciones","press": "Pulsa",- "toStart": "para empezar"+ "toStart": "para empezar",+ "dateGroups": {+ "today": "Hoy",+ "yesterday": "Ayer"+ }},"cloudMigration": {"title": "Bienvenido a OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "Se ejecuta en tu dispositivo. Privacidad total y funciona sin internet.","cloudDescription": "Modelos avanzados por API. Rápido y potente, requiere internet."},- "enableTitle": "Activar mejora de texto con IA",- "enableDescription": "Usa IA para mejorar automáticamente la calidad de transcripción","custom": {"endpointWithProtocol": "Introduce una URL base completa con protocolo (por ejemplo, https://server/v1).","httpsRequired": "Se requiere HTTPS (HTTP solo para red local).",@@ -536,7 +497,8 @@"continueWithGoogle": "Continuar con Google"},"welcomeSubtitle": "Dicta en cualquier lugar usando tu voz",- "welcomeTitle": "Bienvenido a OpenWhispr"+ "welcomeTitle": "Bienvenido a OpenWhispr",+ "sessionExpired": "Sesión expirada"},"cleanupPrompt": "Corrección","developerSection": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Cuenta","app": "Aplicación",- "intelligence": "Inteligencia",- "profile": "Perfil",- "speech": "Voz",+ "speechAi": "Voz e IA","system": "Sistema"},"sections": {"account": {- "description": "Inicio de sesión y uso",+ "description": "Perfil e inicio de sesión","label": "Cuenta"},- "agentConfig": {- "description": "Configuración del agente de voz",- "label": "Agente"- },- "aiModels": {- "description": "Corrección y mejora de texto",- "label": "Modelos de IA"- },- "developer": {- "description": "Registros, diagnósticos y datos",- "label": "Desarrollador"- },- "dictionary": {- "description": "Palabras y frases personalizadas",- "label": "Diccionario"+ "plansBilling": {+ "description": "Planes, uso y facturación",+ "label": "Planes y facturación"},"general": {- "description": "Apariencia, atajo e inicio",+ "description": "Apariencia, sonidos e inicio","label": "Preferencias"},- "permissions": {- "description": "Micrófono y accesibilidad",- "label": "Permisos"- },- "privacy": {- "description": "Respaldo en la nube y analíticas",- "label": "Privacidad"- },- "prompts": {- "description": "Estudio de prompts del sistema",- "label": "Prompts"+ "hotkeys": {+ "description": "Atajo de dictado y activación",+ "label": "Atajos"},"transcription": {"description": "Motor de voz a texto","label": "Transcripción"+ },+ "intelligence": {+ "description": "Modelos de IA, agente y prompts",+ "label": "Inteligencia"+ },+ "privacyData": {+ "description": "Privacidad, permisos y análisis",+ "label": "Privacidad y datos"+ },+ "system": {+ "description": "Actualizaciones, almacenamiento y herramientas de desarrollo",+ "label": "Sistema"}},"title": "Ajustes"@@ -933,6 +886,55 @@"trial": "Prueba"},"planTitle": "Plan",+ "pricing": {+ "title": "Planes",+ "monthly": "Mensual",+ "annual": "Anual",+ "annualBadge": "Ahorra 17%",+ "free": {+ "name": "Gratis",+ "price": "$0",+ "period": "para siempre",+ "trialNote": "Incluye 7 días gratis de OpenWhispr Pro",+ "features": [+ "2.000 palabras/semana",+ "Modelos de IA locales",+ "Usa tus propias claves",+ "Diccionario y fragmentos",+ "Soporte para 100+ idiomas",+ "Sin retención de datos"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/mes",+ "annualPrice": "$80",+ "annualPeriod": "/año",+ "features": [+ "Todo lo de Gratis",+ "Uso ilimitado",+ "Transcripción en tiempo real",+ "Últimos modelos de audio e IA",+ "iOS/Android (próximamente)",+ "Sin retención de datos",+ "Soporte prioritario"+ ],+ "cta": "Comenzar",+ "switchToAnnual": "Cambiar a Anual"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "Personalizado",+ "features": [+ "Sincronización en la nube",+ "Funciones de equipo (próximamente)",+ "SSO y cumplimiento"+ ],+ "cta": "Contáctanos"+ },+ "currentPlan": "Plan actual"+ },"rollingWeeklyLimit": "Límite semanal móvil","signOut": {"failedDescription": "Algo salió mal al cerrar sesión. Inténtalo de nuevo.",@@ -941,6 +943,9 @@"signingOut": "Cerrando sesión..."},"signedIn": "Sesión iniciada",+ "signedOutPlans": {+ "button": "Crear cuenta gratuita"+ },"title": "Cuenta","toasts": {"approachingLimit": {@@ -1023,26 +1028,6 @@"resetAppData": "Restablecer datos de la app","resetAppDataDescription": "Elimina permanentemente todos los ajustes, transcripciones y datos en caché"},- "dictionary": {- "add": "Agregar",- "addWordOrPhrase": "Agrega una palabra o frase",- "agentNameAutoManaged": "Nombre del agente (gestionado automáticamente)",- "clearAll": "Borrar todo",- "clearDictionaryDescription": "Esto eliminará todas las palabras de tu diccionario personalizado. Esta acción no se puede deshacer.",- "clearDictionaryTitle": "¿Borrar diccionario?",- "description": "Agrega palabras, nombres o términos técnicos para mejorar la precisión de transcripción",- "howItWorksDescription": "Las palabras que agregas se incluyen en el prompt de IA para que el modelo las reconozca y preserve durante la corrección de transcripción.",- "howItWorksTitle": "Cómo funciona",- "noWords": "Aún no se han agregado palabras",- "placeholder": "p. ej. OpenWhispr, Kubernetes, Dr. Martínez...",- "pressEnterToAdd": "Pulsa Enter para agregar",- "removeWord": "Eliminar palabra",- "tipDescription": "Agrega nombres propios, términos técnicos o cualquier palabra que pueda transcribirse incorrectamente.",- "tipLabel": "Consejo",- "title": "Diccionario personalizado",- "wordsAppearHere": "Las palabras que agregues aparecerán aquí",- "yourWords": "Tus palabras"- },"general": {"appearance": {"auto": "Auto",@@ -1062,6 +1047,7 @@"hotkey": {"activationMode": "Modo de activación","description": "La combinación de teclas que inicia y detiene el dictado por voz",+ "resetToDefault": "Restablecer a {{hotkey}}","title": "Atajo de dictado"},"microphone": {@@ -1245,5 +1231,284 @@"openai_oss_gpt_oss_20b_mxfp4": "Modelo open-weight de OpenAI para hardware de consumo"}}+ },+ "referral": {+ "title": "Recomienda y gana recompensas",+ "subtitle": "Regala un mes. Recibe un mes.",+ "modalTitle": "Invitar amigos",+ "tabs": {+ "refer": "Recomendar",+ "pastInvites": "Invitaciones anteriores"+ },+ "howItWorks": {+ "shareLink": "Comparte tu enlace de invitación",+ "theySignUp": "Se registran y obtienen un ",+ "freeMonthOfPro": "mes gratis de Pro",+ "youGet": "Tú recibes un ",+ "freeMonth": "mes gratis",+ "whenTheyDictate": " cuando dicten 2.000 palabras"+ },+ "inviteLink": {+ "title": "Tu enlace de invitación",+ "copy": "Copiar",+ "copied": "Copiado"+ },+ "sendInvites": {+ "title": "Enviar invitaciones",+ "placeholder": "[email protected]",+ "send": "Enviar",+ "sending": "Enviando"+ },+ "stats": {+ "referred": "Recomendados",+ "converted": "Convertidos",+ "monthsEarned": "Meses ganados"+ },+ "status": {+ "converted": "Convertido",+ "opened": "Abierto",+ "failed": "Fallido",+ "sent": "Enviado"+ },+ "empty": {+ "title": "Aún no se han enviado invitaciones",+ "description": "Comparte tu enlace o envía una invitación para comenzar"+ },+ "toasts": {+ "copiedTitle": "¡Copiado!",+ "copiedDescription": "Enlace de referido copiado al portapapeles",+ "copyFailedTitle": "Error al copiar",+ "copyFailedDescription": "No se pudo copiar el enlace al portapapeles",+ "invalidEmailTitle": "Correo electrónico inválido",+ "invalidEmailDescription": "Por favor, introduce una dirección de correo electrónico válida",+ "inviteSentTitle": "¡Invitación enviada!",+ "inviteSentDescription": "Invitación enviada a {{email}}",+ "sendFailedTitle": "Error al enviar",+ "sendFailedDescription": "No se pudo enviar la invitación. Por favor, inténtalo de nuevo."+ },+ "errors": {+ "unableToLoad": "No se pudieron cargar los datos de referidos",+ "unableToLoadStats": "No se pudieron cargar las estadísticas de referidos. Por favor, inténtalo más tarde."+ },+ "tryAgain": "Intentar de nuevo",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Tu firma de audio",+ "stop": "Detener",+ "playSignal": "Reproducir señal"+ },+ "friends": {+ "title": "Amigos",+ "completed": "Completado",+ "sentInvites": "Invitaciones enviadas"+ }+ },+ "notes": {+ "folders": {+ "title": "Carpetas",+ "soon": "Próximamente",+ "folderName": "Nombre de la carpeta",+ "couldNotCreate": "No se pudo crear la carpeta",+ "couldNotRename": "No se pudo renombrar la carpeta",+ "couldNotDelete": "No se pudo eliminar la carpeta"+ },+ "list": {+ "title": "Notas",+ "newNote": "Nueva nota",+ "untitled": "Sin título",+ "untitledNote": "Nota sin título",+ "timeNow": "Ahora",+ "minutesAgo": "hace {{count}}m",+ "hoursAgo": "hace {{count}}h",+ "daysAgo": "hace {{count}}d"+ },+ "editor": {+ "untitled": "Sin título",+ "noteTitle": "Título de la nota",+ "stop": "Detener",+ "transcribe": "Transcribir",+ "processing": "Procesando...",+ "export": "Exportar",+ "asMarkdown": "Como Markdown",+ "asPlainText": "Como texto plano",+ "raw": "Sin procesar",+ "enhanced": "Mejorado",+ "saving": "Guardando",+ "wordsCount": "{{count}} palabras",+ "startWriting": "Comienza a escribir...",+ "staleIndicator": "El contenido ha cambiado desde la mejora"+ },+ "upload": {+ "title": "Subir audio",+ "using": "Usando {{model}}",+ "dropOrBrowse": "Arrastra un archivo de audio o haz clic para explorar",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Suelta para subir",+ "transcribe": "Transcribir",+ "cancel": "Cancelar",+ "transcribingCloud": "Transcribiendo en la nube...",+ "transcribingLocal": "Transcribiendo localmente...",+ "transcribingProvider": "Transcribiendo con {{provider}}...",+ "transcriptionComplete": "Transcripción completada",+ "openNote": "Abrir nota",+ "uploadAnother": "Subir otro",+ "retry": "Reintentar",+ "startOver": "Empezar de nuevo",+ "transcriptionSettings": "Configuración de transcripción",+ "newFolder": "Nueva carpeta",+ "folderName": "Nombre de la carpeta",+ "create": "Crear",+ "setupTitle": "Configurar transcripción",+ "setupDescription": "Elige cómo transcribir tu audio. Esto también se aplica al dictado en vivo.",+ "continue": "Continuar",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Personalizado",+ "selectFolder": "Seleccionar carpeta",+ "transcriptionFailed": "Error en la transcripción",+ "errorOccurred": "Se produjo un error",+ "noProviderTitle": "No se ha configurado un proveedor de transcripción",+ "noProviderDescription": "Agrega una clave API o descarga un modelo local para comenzar a transcribir.",+ "noProviderAction": "Abrir configuración de transcripción"+ },+ "meeting": {+ "title": "Notas de reunión",+ "description": "Identificación de hablantes y resúmenes estructurados",+ "comingSoon": "Próximamente"+ },+ "context": {+ "moveToFolder": "Mover a carpeta",+ "delete": "Eliminar",+ "rename": "Renombrar",+ "searchFolders": "Buscar carpetas...",+ "noResults": "No se encontraron carpetas",+ "newFolder": "Nueva carpeta"+ },+ "actions": {+ "manage": "Gestionar acciones...",+ "manageTitle": "Acciones personalizadas",+ "addAction": "Nueva acción",+ "editAction": "Editar acción",+ "namePlaceholder": "Nombre de la acción",+ "descriptionPlaceholder": "Descripción breve (opcional)",+ "promptPlaceholder": "¿Qué debe hacer la IA con el contenido de la nota?",+ "builtIn": "Integrada",+ "save": "Guardar",+ "update": "Actualizar",+ "cancel": "Cancelar",+ "noActions": "Aún no hay acciones personalizadas",+ "runAction": "Ejecutar {{name}}",+ "selectAction": "Seleccionar acción",+ "done": "Listo",+ "builtin": {+ "cleanupNotes": {+ "name": "Limpiar notas",+ "description": "Corregir gramática, estructura y formato"+ }+ }+ },+ "empty": {+ "title": "Todavía no hay notas aquí",+ "description": "Crea tu primera nota para empezar a escribir",+ "selectTitle": "Selecciona una nota",+ "selectDescription": "Elige una nota de la barra lateral",+ "createNote": "Crear nota",+ "emptyFolder": "No hay notas en esta carpeta"+ },+ "addToFolder": {+ "title": "Añadir notas",+ "searchPlaceholder": "Buscar notas para añadir...",+ "addExisting": "Añadir existentes",+ "addCount": "Añadir {{count}} notas",+ "noResults": "No hay notas coincidentes",+ "noNotesAvailable": "No hay otras notas disponibles",+ "today": "Hoy",+ "yesterday": "Ayer"+ },+ "onboarding": {+ "llm": {+ "title": "Configurar un modelo de IA",+ "description": "Las acciones usan IA para transformar tus notas. Configura un modelo de lenguaje para comenzar.",+ "configured": "Modelo de IA configurado"+ },+ "actions": {+ "title": "Acciones impulsadas por IA",+ "description": "Las acciones transforman tus notas: corrigen transcripciones, resumen reuniones y más. Usa acciones integradas o crea las tuyas.",+ "builtInLabel": "Integrada",+ "createTitle": "Crea tu propia acción",+ "createDescription": "Define una acción personalizada con tu propio prompt de IA. Puedes editar o agregar más después en los ajustes.",+ "created": "¡Creada!"+ },+ "getStarted": "Comenzar"+ },+ "realtimeBanner": {+ "message": "Transcripción en tiempo real disponible con Pro",+ "upgrade": "Mejorar"+ }+ },+ "dictionary": {+ "addWord": "Añadir palabra",+ "removeWord": "Eliminar {{word}}",+ "clearAll": "Borrar todo",+ "howItWorks": "Cómo funciona",+ "howItWorksDetail": "Las palabras que agregas se incluyen en el prompt de IA para que el modelo las reconozca y preserve durante la corrección de transcripción.",+ "autoManaged": "Nombre del agente (gestionado automáticamente)",+ "inputHint": "Pulsa Enter para agregar",+ "title": "Diccionario personalizado",+ "description": "Enseña a la IA tu vocabulario: nombres, jerga y términos que podría pasar por alto",+ "clearTitle": "¿Borrar el diccionario?",+ "clearDescription": "Esto eliminará todas las palabras de tu diccionario personalizado. Esta acción no se puede deshacer.",+ "addPlaceholder": "Añadir una palabra o frase..."+ },+ "sidebar": {+ "home": "Inicio",+ "notes": "Notas",+ "upload": "Subir",+ "dictionary": "Diccionario",+ "referral": "Obtener un mes gratis",+ "settings": "Configuración",+ "support": "Soporte",+ "limitReached": "Límite semanal alcanzado",+ "limitReachedDescription": "Mejora a Pro para transcripciones ilimitadas.",+ "upgradeToPro": "Mejorar a Pro",+ "upgradeTitle": "Mejorar a Pro",+ "upgradeDescription": "Transcripciones ilimitadas y más.",+ "learnMore": "Más información",+ "defaultUser": "Usuario",+ "notSignedIn": "Sin sesión iniciada"+ },+ "usage": {+ "approachingLimit": "Cerca del límite semanal",+ "approachingLimitDescription": "Has usado {{wordsUsed}} de {{limit}} palabras gratuitas esta semana.",+ "yourPlan": "Tu plan",+ "trial": "Prueba (queda {{days}} día)",+ "trial_other": "Prueba (quedan {{days}} días)",+ "pro": "Pro",+ "unlimitedTrial": "Transcripciones ilimitadas durante tu período de prueba",+ "unlimited": "Transcripciones ilimitadas",+ "manageSubscription": "Gestionar suscripción",+ "weeklyUsage": "Uso semanal",+ "limitReached": "Límite alcanzado",+ "free": "Gratis",+ "wordsRemaining": "{{remaining}} palabras restantes",+ "rollingLimit": "Límite semanal renovable",+ "upgradeToPro": "Actualizar a Pro",+ "useYourOwnKey": "Usar tu propia clave API",+ "upgradeUnlimited": "Actualizar a Pro — transcripciones ilimitadas"+ },+ "support": {+ "joinDiscord": "Unirse a Discord",+ "contactSupport": "Contactar soporte",+ "submitBug": "Reportar un error"+ },+ "apiKeyInput": {+ "placeholder": "Introduce tu clave API",+ "label": "Clave API",+ "save": "Guardar",+ "cancelEdit": "Cancelar edición",+ "edit": "Editar",+ "add": "Agregar",+ "editButton": "Editar",+ "addButton": "Agregar"}}diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex fe4a397d4..9a59eb10c 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Chargement d'OpenWhispr...",- "oauth": {- "redirectTitle": "Redirection vers OpenWhispr",- "closeTab": "Vous pouvez fermer cet onglet"- },- "buttons": {- "cancelRecording": "Annuler l'enregistrement",- "cancelProcessing": "Annuler le traitement"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] pour parler",- "recording": "Enregistrement...",- "processing": "Traitement...",- "clickToSpeak": "Cliquez pour parler"- },- "toasts": {- "hotkeyChanged": {- "title": "Raccourci modifié"- },- "hotkeyUnavailable": {- "title": "Raccourci indisponible",- "description": "Impossible d'enregistrer ce raccourci. Choisissez-en un autre dans les paramètres."- }- },- "commandMenu": {- "startListening": "Démarrer l'écoute",- "stopListening": "Arrêter l'écoute",- "hideForNow": "Masquer pour le moment"- }- },"settings": {"language": {"sectionTitle": "Langue",@@ -172,10 +140,10 @@"availableModels": "Modèles disponibles","fast": "Rapide","hold": "Maintenir",- "less": "Moins",- "more": "Plus","private": "Privé",- "tap": "Appui"+ "tap": "Appui",+ "close": "Fermer",+ "dismiss": "Ignorer"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "Mettre à jour le paiement"},"history": {- "title": "Transcriptions","couldNotLoadTitle": "Impossible de charger votre historique","couldNotLoadDescription": "Un problème est survenu lors du chargement des transcriptions. Fermez puis rouvrez l'application.","copiedTitle": "Copié !","copiedDescription": "Texte copié dans le presse-papiers","couldNotCopyTitle": "Impossible de copier","couldNotCopyDescription": "Un problème est survenu pendant la copie. Réessayez.",- "clearTitle": "Effacer l'historique",- "clearDescription": "Cela supprimera toutes vos transcriptions. Action irréversible.",- "clearedTitle": "Historique effacé",- "clearedDescription": "{{count}} transcription supprimée",- "clearedDescription_other": "{{count}} transcriptions supprimées",- "couldNotClearTitle": "Impossible d'effacer l'historique",- "couldNotClearDescription": "Une erreur est survenue. Veuillez réessayer.","deleteTitle": "Supprimer la transcription","deleteDescription": "Cette transcription sera supprimée définitivement.","couldNotDeleteTitle": "Impossible de supprimer","couldNotDeleteDescription": "Cette transcription a peut-être déjà été supprimée.","couldNotDeleteDescriptionGeneric": "Une erreur est survenue. Veuillez réessayer.",- "clear": "Effacer","empty": "Aucune transcription pour le moment","press": "Appuyez sur",- "toStart": "pour démarrer"+ "toStart": "pour démarrer",+ "dateGroups": {+ "today": "Aujourd'hui",+ "yesterday": "Hier"+ }},"cloudMigration": {"title": "Bienvenue sur OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "S'exécute sur votre appareil. Confidentialité totale et fonctionnement hors ligne.","cloudDescription": "Modèles avancés via API. Rapides et puissants, nécessitent internet."},- "enableTitle": "Activer l'amélioration de texte par IA",- "enableDescription": "Utiliser l'IA pour améliorer automatiquement la qualité de transcription","custom": {"endpointWithProtocol": "Saisissez une URL de base complète avec protocole (ex : https://server/v1).","httpsRequired": "HTTPS requis (HTTP autorisé seulement en réseau local).",@@ -536,7 +497,8 @@"continueWithGoogle": "Continuer avec Google"},"welcomeSubtitle": "Dictez n'importe où en utilisant votre voix",- "welcomeTitle": "Bienvenue sur OpenWhispr"+ "welcomeTitle": "Bienvenue sur OpenWhispr",+ "sessionExpired": "Session expirée. Veuillez relancer le processus d'inscription."},"cleanupPrompt": "Correction","developerSection": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Compte","app": "Application",- "intelligence": "Intelligence",- "profile": "Profil",- "speech": "Parole",+ "speechAi": "Parole & IA","system": "Système"},"sections": {"account": {- "description": "Connexion et utilisation",+ "description": "Profil & connexion","label": "Compte"},- "agentConfig": {- "description": "Configuration de l'agent vocal",- "label": "Agent"- },- "aiModels": {- "description": "Correction et amélioration du texte",- "label": "Modèles IA"- },- "developer": {- "description": "Journaux, diagnostics et données",- "label": "Développeur"- },- "dictionary": {- "description": "Mots et expressions personnalisés",- "label": "Dictionnaire"+ "plansBilling": {+ "description": "Forfaits, utilisation & facturation",+ "label": "Forfaits & facturation"},"general": {- "description": "Apparence, raccourci et démarrage",+ "description": "Apparence, sons & démarrage","label": "Préférences"},- "permissions": {- "description": "Microphone et accessibilité",- "label": "Permissions"- },- "privacy": {- "description": "Sauvegarde cloud et analyse",- "label": "Confidentialité"- },- "prompts": {- "description": "Studio de prompts système",- "label": "Prompts"+ "hotkeys": {+ "description": "Raccourci de dictée et activation",+ "label": "Raccourcis"},"transcription": {"description": "Moteur de reconnaissance vocale","label": "Transcription"+ },+ "intelligence": {+ "description": "Modèles IA, agent & prompts",+ "label": "Intelligence"+ },+ "privacyData": {+ "description": "Confidentialité, permissions & analytique",+ "label": "Confidentialité & données"+ },+ "system": {+ "description": "Mises à jour, stockage & outils de développement",+ "label": "Système"}},"title": "Paramètres"@@ -933,6 +886,55 @@"trial": "Essai"},"planTitle": "Plan",+ "pricing": {+ "title": "Forfaits",+ "monthly": "Mensuel",+ "annual": "Annuel",+ "annualBadge": "Économisez 17 %",+ "free": {+ "name": "Gratuit",+ "price": "$0",+ "period": "pour toujours",+ "trialNote": "Inclut 7 jours gratuits d'OpenWhispr Pro",+ "features": [+ "2 000 mots/semaine",+ "Modèles IA locaux",+ "Apportez vos propres clés",+ "Dictionnaire et extraits",+ "Prise en charge de plus de 100 langues",+ "Aucune rétention de données"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/mois",+ "annualPrice": "$80",+ "annualPeriod": "/an",+ "features": [+ "Tout ce qui est dans Gratuit",+ "Utilisation illimitée",+ "Transcription en temps réel",+ "Derniers modèles audio & IA",+ "iOS/Android (bientôt)",+ "Aucune rétention de données",+ "Support prioritaire"+ ],+ "cta": "Commencer",+ "switchToAnnual": "Passer à l'annuel"+ },+ "enterprise": {+ "name": "Entreprise",+ "price": "Sur devis",+ "features": [+ "Synchronisation cloud",+ "Fonctionnalités d'équipe (bientôt)",+ "SSO & conformité"+ ],+ "cta": "Nous contacter"+ },+ "currentPlan": "Plan actuel"+ },"rollingWeeklyLimit": "Limite hebdomadaire glissante","signOut": {"failedDescription": "Un problème est survenu lors de la déconnexion. Veuillez réessayer.",@@ -953,6 +955,9 @@"description": "Transcriptions illimitées, traitement prioritaire et plus encore.","title": "Essayez Pro gratuitement pendant 7 jours"},+ "signedOutPlans": {+ "button": "Créer un compte gratuit"+ },"user": "Utilisateur","wordsRemaining": "{{remaining}} restants"},@@ -1023,26 +1028,6 @@"resetAppData": "Réinitialiser les données de l'application","resetAppDataDescription": "Supprime définitivement tous les paramètres, transcriptions et données en cache"},- "dictionary": {- "add": "Ajouter",- "addWordOrPhrase": "Ajouter un mot ou une expression",- "agentNameAutoManaged": "Nom de l'agent (géré automatiquement)",- "clearAll": "Tout effacer",- "clearDictionaryDescription": "Cela supprimera tous les mots de votre dictionnaire personnalisé. Action irréversible.",- "clearDictionaryTitle": "Effacer le dictionnaire ?",- "description": "Ajoutez des mots, noms ou termes techniques pour améliorer la précision de la transcription",- "howItWorksDescription": "Les mots que vous ajoutez sont inclus dans le prompt IA pour que le modèle reconnaisse et préserve ces termes lors de la correction de la transcription.",- "howItWorksTitle": "Comment ça marche",- "noWords": "Aucun mot ajouté",- "placeholder": "ex. OpenWhispr, Kubernetes, Dr. Martinez...",- "pressEnterToAdd": "Appuyez sur Entrée pour ajouter",- "removeWord": "Supprimer le mot",- "tipDescription": "Ajoutez des noms propres, termes techniques ou tout mot susceptible d'être mal transcrit.",- "tipLabel": "Astuce",- "title": "Dictionnaire personnalisé",- "wordsAppearHere": "Les mots que vous ajoutez apparaîtront ici",- "yourWords": "Vos mots"- },"general": {"appearance": {"auto": "Auto",@@ -1062,6 +1047,7 @@"hotkey": {"activationMode": "Mode d'activation","description": "La combinaison de touches qui démarre et arrête la dictée vocale",+ "resetToDefault": "Réinitialiser à {{hotkey}}","title": "Raccourci de dictée"},"microphone": {@@ -1245,5 +1231,284 @@"openai_oss_gpt_oss_20b_mxfp4": "Modèle open-weight d'OpenAI pour matériel grand public"}}+ },+ "sidebar": {+ "home": "Accueil",+ "notes": "Notes",+ "upload": "Importer",+ "dictionary": "Dictionnaire",+ "referral": "Obtenir un mois gratuit",+ "settings": "Paramètres",+ "support": "Assistance",+ "limitReached": "Limite hebdomadaire atteinte",+ "limitReachedDescription": "Passez à Pro pour des transcriptions illimitées.",+ "upgradeToPro": "Passer à Pro",+ "upgradeTitle": "Passer à Pro",+ "upgradeDescription": "Transcriptions illimitées et fonctionnalités premium.",+ "learnMore": "En savoir plus",+ "defaultUser": "Utilisateur",+ "notSignedIn": "Non connecté"+ },+ "referral": {+ "title": "Parrainez et gagnez des récompenses",+ "modalTitle": "Parrainez et gagnez des récompenses",+ "subtitle": "Offrez un mois. Recevez un mois.",+ "tabs": {+ "refer": "Parrainer",+ "pastInvites": "Invitations passées"+ },+ "howItWorks": {+ "shareLink": "Partagez votre lien d'invitation",+ "theySignUp": "Ils s'inscrivent et obtiennent un ",+ "freeMonthOfPro": "mois gratuit de Pro",+ "youGet": "Vous recevez un ",+ "freeMonth": "mois gratuit",+ "whenTheyDictate": " lorsqu'ils dictent 2 000 mots"+ },+ "inviteLink": {+ "title": "Votre lien d'invitation",+ "copy": "Copier",+ "copied": "Copié"+ },+ "sendInvites": {+ "title": "Envoyer des invitations",+ "placeholder": "[email protected]",+ "send": "Envoyer",+ "sending": "Envoi en cours"+ },+ "stats": {+ "referred": "Parrainés",+ "converted": "Convertis",+ "monthsEarned": "Mois gagnés"+ },+ "status": {+ "converted": "Converti",+ "opened": "Ouvert",+ "failed": "Échoué",+ "sent": "Envoyé"+ },+ "friends": {+ "title": "Amis",+ "completed": "Complété",+ "sentInvites": "Invitations envoyées"+ },+ "empty": {+ "title": "Aucune invitation envoyée",+ "description": "Partagez votre lien ou envoyez une invitation pour commencer"+ },+ "toasts": {+ "copiedTitle": "Copié !",+ "copiedDescription": "Lien de parrainage copié dans le presse-papiers",+ "copyFailedTitle": "Échec de la copie",+ "copyFailedDescription": "Impossible de copier le lien dans le presse-papiers",+ "invalidEmailTitle": "E-mail invalide",+ "invalidEmailDescription": "Veuillez entrer une adresse e-mail valide",+ "inviteSentTitle": "Invitation envoyée !",+ "inviteSentDescription": "Invitation envoyée à {{email}}",+ "sendFailedTitle": "Échec de l'envoi",+ "sendFailedDescription": "Impossible d'envoyer l'invitation. Veuillez réessayer."+ },+ "errors": {+ "unableToLoad": "Impossible de charger les données de parrainage",+ "unableToLoadStats": "Impossible de charger les statistiques de parrainage. Veuillez réessayer plus tard."+ },+ "tryAgain": "Réessayer",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Votre signature audio",+ "stop": "Arrêter",+ "playSignal": "Lire le signal"+ }+ },+ "usage": {+ "approachingLimit": "Limite hebdomadaire bientôt atteinte",+ "approachingLimitDescription": "Vous avez utilisé {{wordsUsed}} de vos {{limit}} mots gratuits cette semaine.",+ "yourPlan": "Votre abonnement",+ "trial": "Essai ({{days}} jour restant)",+ "trial_other": "Essai ({{days}} jours restants)",+ "pro": "Pro",+ "unlimitedTrial": "Transcriptions illimitées pendant votre période d'essai",+ "unlimited": "Transcriptions illimitées",+ "manageSubscription": "Gérer l'abonnement",+ "weeklyUsage": "Utilisation hebdomadaire",+ "limitReached": "Limite atteinte",+ "free": "Gratuit",+ "wordsRemaining": "{{remaining}} mots restants",+ "rollingLimit": "Limite hebdomadaire glissante",+ "upgradeToPro": "Passer à Pro",+ "useYourOwnKey": "Utiliser votre propre clé API",+ "upgradeUnlimited": "Passer à Pro — transcriptions illimitées"+ },+ "notes": {+ "folders": {+ "title": "Dossiers",+ "soon": "Bientôt",+ "folderName": "Nom du dossier",+ "couldNotCreate": "Impossible de créer le dossier",+ "couldNotRename": "Impossible de renommer le dossier",+ "couldNotDelete": "Impossible de supprimer le dossier"+ },+ "list": {+ "title": "Notes",+ "newNote": "Nouvelle note",+ "untitled": "Sans titre",+ "untitledNote": "Note sans titre",+ "timeNow": "maintenant",+ "minutesAgo": "il y a {{count}}m",+ "hoursAgo": "il y a {{count}}h",+ "daysAgo": "il y a {{count}}j"+ },+ "editor": {+ "untitled": "Sans titre",+ "noteTitle": "Titre de la note",+ "stop": "Arrêter",+ "transcribe": "Transcrire",+ "processing": "Traitement...",+ "export": "Exporter",+ "asMarkdown": "En Markdown",+ "asPlainText": "En texte brut",+ "raw": "Brut",+ "enhanced": "Amélioré",+ "saving": "Enregistrement",+ "wordsCount": "{{count}} mots",+ "startWriting": "Commencez à écrire...",+ "staleIndicator": "Le contenu a changé depuis l'amélioration"+ },+ "upload": {+ "title": "Téléverser un fichier audio",+ "using": "Utilisation de {{model}}",+ "dropOrBrowse": "Déposez un fichier audio ou cliquez pour parcourir",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Déposez pour téléverser",+ "transcribe": "Transcrire",+ "cancel": "Annuler",+ "transcribingCloud": "Transcription via le cloud...",+ "transcribingLocal": "Transcription locale...",+ "transcribingProvider": "Transcription via {{provider}}...",+ "transcriptionComplete": "Transcription terminée",+ "openNote": "Ouvrir la note",+ "uploadAnother": "Téléverser un autre fichier",+ "retry": "Réessayer",+ "startOver": "Recommencer",+ "transcriptionSettings": "Paramètres de transcription",+ "newFolder": "Nouveau dossier",+ "folderName": "Nom du dossier",+ "create": "Créer",+ "setupTitle": "Configurer la transcription",+ "setupDescription": "Choisissez comment transcrire votre audio. Cela s'applique également à la dictée en direct.",+ "continue": "Continuer",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Personnalisé",+ "selectFolder": "Sélectionner un dossier",+ "transcriptionFailed": "Échec de la transcription",+ "errorOccurred": "Une erreur est survenue",+ "noProviderTitle": "Aucun fournisseur de transcription configuré",+ "noProviderDescription": "Ajoutez une clé API ou téléchargez un modèle local pour commencer à transcrire.",+ "noProviderAction": "Ouvrir les paramètres de transcription"+ },+ "meeting": {+ "title": "Notes de réunion",+ "description": "Identification des intervenants et résumés structurés",+ "comingSoon": "Bientôt disponible"+ },+ "empty": {+ "title": "Aucune note ici pour l'instant",+ "description": "Créez votre première note pour commencer à écrire",+ "selectTitle": "Sélectionner une note",+ "selectDescription": "Choisissez une note dans la barre latérale",+ "createNote": "Créer une note",+ "emptyFolder": "Aucune note dans ce dossier"+ },+ "addToFolder": {+ "title": "Ajouter des notes",+ "searchPlaceholder": "Rechercher des notes à ajouter...",+ "addExisting": "Ajouter des notes existantes",+ "addCount": "Ajouter {{count}} notes",+ "noResults": "Aucune note correspondante",+ "noNotesAvailable": "Aucune autre note disponible",+ "today": "Aujourd'hui",+ "yesterday": "Hier"+ },+ "context": {+ "moveToFolder": "Déplacer vers un dossier",+ "delete": "Supprimer",+ "rename": "Renommer",+ "searchFolders": "Rechercher des dossiers...",+ "noResults": "Aucun dossier trouvé",+ "newFolder": "Nouveau dossier"+ },+ "actions": {+ "done": "Terminé",+ "manage": "Gérer les actions...",+ "manageTitle": "Actions personnalisées",+ "addAction": "Nouvelle action",+ "editAction": "Modifier l'action",+ "namePlaceholder": "Nom de l'action",+ "descriptionPlaceholder": "Description brève (facultatif)",+ "promptPlaceholder": "Que doit faire l'IA avec le contenu de la note ?",+ "builtIn": "Intégrée",+ "save": "Enregistrer",+ "update": "Mettre à jour",+ "cancel": "Annuler",+ "noActions": "Aucune action personnalisée pour l'instant",+ "runAction": "Exécuter {{name}}",+ "selectAction": "Sélectionner l'action",+ "builtin": {+ "cleanupNotes": {+ "name": "Nettoyer les notes",+ "description": "Corriger la grammaire, la structure et la mise en forme"+ }+ }+ },+ "onboarding": {+ "llm": {+ "title": "Configurer un modèle IA",+ "description": "Les actions utilisent l'IA pour transformer vos notes. Configurez un modèle de langage pour commencer.",+ "configured": "Modèle IA configuré"+ },+ "actions": {+ "title": "Actions alimentées par l'IA",+ "description": "Les actions transforment vos notes : nettoyage des transcriptions, résumés de réunions et bien plus. Utilisez les actions intégrées ou créez les vôtres.",+ "builtInLabel": "Intégrée",+ "createTitle": "Créez votre propre action",+ "createDescription": "Définissez une action personnalisée avec votre propre prompt IA. Vous pourrez toujours la modifier ou en ajouter d'autres dans les paramètres.",+ "created": "Créée !"+ },+ "getStarted": "Commencer"+ },+ "realtimeBanner": {+ "message": "Transcription en temps réel disponible avec Pro",+ "upgrade": "Passer à Pro"+ }+ },+ "dictionary": {+ "title": "Dictionnaire personnalisé",+ "description": "Apprenez à l'IA votre vocabulaire — noms, jargon et termes qu'elle pourrait autrement manquer",+ "clearTitle": "Vider le dictionnaire ?",+ "clearDescription": "Cela supprimera tous les mots de votre dictionnaire personnalisé. Cette action est irréversible.",+ "addWord": "Ajouter un mot",+ "addPlaceholder": "Ajouter un mot ou une expression...",+ "removeWord": "Supprimer {{word}}",+ "clearAll": "Tout effacer",+ "howItWorks": "Comment ça marche",+ "howItWorksDetail": "Les mots sont transmis comme indices contextuels au modèle vocal, l'aidant à reconnaître les termes peu courants. Pour les mots difficiles, essayez d'ajouter du contexte comme « Le mot est Synty » en plus du mot lui-même.",+ "autoManaged": "Géré automatiquement — synchronisé depuis le nom de l'agent",+ "inputHint": "Séparez les mots par des virgules. Ajoutez des phrases de contexte comme « Le mot est Synty » pour une meilleure reconnaissance."+ },+ "support": {+ "joinDiscord": "Rejoindre Discord",+ "contactSupport": "Contacter le support",+ "submitBug": "Signaler un bug"+ },+ "apiKeyInput": {+ "placeholder": "Collez votre clé API",+ "label": "Clé API",+ "save": "Enregistrer la clé API",+ "cancelEdit": "Annuler la modification",+ "edit": "Modifier la clé API",+ "add": "Ajouter une clé API",+ "editButton": "modifier",+ "addButton": "ajouter"}}diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex b55951edd..c8590505b 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Caricamento di OpenWhispr...",- "oauth": {- "redirectTitle": "Reindirizzamento a OpenWhispr",- "closeTab": "Puoi chiudere questa scheda"- },- "buttons": {- "cancelRecording": "Annulla registrazione",- "cancelProcessing": "Annulla elaborazione"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] per parlare",- "recording": "Registrazione...",- "processing": "Elaborazione...",- "clickToSpeak": "Clicca per parlare"- },- "toasts": {- "hotkeyChanged": {- "title": "Scorciatoia modificata"- },- "hotkeyUnavailable": {- "title": "Scorciatoia non disponibile",- "description": "Impossibile registrare la scorciatoia. Impostane una diversa nelle Impostazioni."- }- },- "commandMenu": {- "startListening": "Avvia ascolto",- "stopListening": "Ferma ascolto",- "hideForNow": "Nascondi per ora"- }- },"settings": {"language": {"sectionTitle": "Lingua",@@ -172,10 +140,10 @@"availableModels": "Modelli disponibili","fast": "Veloce","hold": "Tieni premuto",- "less": "Meno",- "more": "Di più","private": "Privato",- "tap": "Tocca"+ "tap": "Tocca",+ "close": "Chiudi",+ "dismiss": "Ignora"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "Aggiorna pagamento"},"history": {- "title": "Trascrizioni","couldNotLoadTitle": "Impossibile caricare la cronologia","couldNotLoadDescription": "Si è verificato un errore nel caricamento delle trascrizioni. Chiudi e riapri l'app.","copiedTitle": "Copiato!","copiedDescription": "Testo copiato negli appunti","couldNotCopyTitle": "Impossibile copiare","couldNotCopyDescription": "Si è verificato un errore durante la copia. Riprova.",- "clearTitle": "Cancella cronologia",- "clearDescription": "Questo rimuoverà tutte le trascrizioni. L'azione non può essere annullata.",- "clearedTitle": "Cronologia cancellata",- "clearedDescription": "{{count}} trascrizione rimossa",- "clearedDescription_other": "{{count}} trascrizioni rimosse",- "couldNotClearTitle": "Impossibile cancellare la cronologia",- "couldNotClearDescription": "Qualcosa è andato storto. Riprova.","deleteTitle": "Elimina trascrizione","deleteDescription": "Questa trascrizione verrà rimossa definitivamente.","couldNotDeleteTitle": "Impossibile eliminare","couldNotDeleteDescription": "Questa trascrizione potrebbe essere già stata rimossa.","couldNotDeleteDescriptionGeneric": "Qualcosa è andato storto. Riprova.",- "clear": "Cancella","empty": "Nessuna trascrizione","press": "Premi",- "toStart": "per iniziare"+ "toStart": "per iniziare",+ "dateGroups": {+ "today": "Oggi",+ "yesterday": "Ieri"+ }},"cloudMigration": {"title": "Benvenuto in OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "Funziona sul tuo dispositivo. Privacy completa, funziona offline.","cloudDescription": "Modelli avanzati via API. Veloci e potenti, richiedono internet."},- "enableTitle": "Attiva miglioramento testo con IA",- "enableDescription": "Usa l'IA per migliorare automaticamente la qualità della trascrizione","custom": {"endpointWithProtocol": "Inserisci un URL base completo di protocollo (ad esempio, https://server/v1).","httpsRequired": "HTTPS richiesto (HTTP consentito solo in rete locale).",@@ -479,6 +440,7 @@}},"auth": {+ "sessionExpired": "Sessione scaduta","cloudNotConfigured": "Cloud non configurato","common": {"back": "Indietro",@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Account","app": "App",- "intelligence": "Intelligenza",- "profile": "Profilo",- "speech": "Voce",+ "speechAi": "Voce & IA","system": "Sistema"},"sections": {"account": {- "description": "Accesso e utilizzo",+ "description": "Profilo e accesso","label": "Account"},- "agentConfig": {- "description": "Configurazione agente vocale",- "label": "Agente"- },- "aiModels": {- "description": "Correzione e miglioramento testo",- "label": "Modelli IA"- },- "developer": {- "description": "Log, diagnostica e dati",- "label": "Sviluppatore"- },- "dictionary": {- "description": "Parole e frasi personalizzate",- "label": "Dizionario"+ "plansBilling": {+ "description": "Piani, utilizzo e fatturazione",+ "label": "Piani e fatturazione"},"general": {- "description": "Aspetto, scorciatoia e avvio",+ "description": "Aspetto, suoni e avvio","label": "Preferenze"},- "permissions": {- "description": "Microfono e accessibilità",- "label": "Permessi"- },- "privacy": {- "description": "Backup cloud e analisi",- "label": "Privacy"- },- "prompts": {- "description": "Studio del prompt di sistema",- "label": "Prompt"+ "hotkeys": {+ "description": "Scorciatoia di dettatura e attivazione",+ "label": "Scorciatoie"},"transcription": {"description": "Motore di riconoscimento vocale","label": "Trascrizione"+ },+ "intelligence": {+ "description": "Modelli IA, agente e prompt",+ "label": "Intelligenza"+ },+ "privacyData": {+ "description": "Privacy, permessi e analisi",+ "label": "Privacy e dati"+ },+ "system": {+ "description": "Aggiornamenti, archiviazione e strumenti di sviluppo",+ "label": "Sistema"}},"title": "Impostazioni"@@ -953,6 +906,58 @@"description": "Trascrizioni illimitate, elaborazione prioritaria e altro ancora.","title": "Prova Pro gratis per 7 giorni"},+ "pricing": {+ "title": "Piani",+ "monthly": "Mensile",+ "annual": "Annuale",+ "annualBadge": "Risparmi il 17%",+ "free": {+ "name": "Gratuito",+ "price": "$0",+ "period": "per sempre",+ "trialNote": "Include 7 giorni gratuiti di OpenWhispr Pro",+ "features": [+ "2.000 parole/settimana",+ "Modelli IA locali",+ "Usa le tue chiavi API",+ "Dizionario e snippet",+ "Supporto per oltre 100 lingue",+ "Nessuna conservazione dei dati"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/mese",+ "annualPrice": "$80",+ "annualPeriod": "/anno",+ "features": [+ "Tutto del piano Gratuito",+ "Uso illimitato",+ "Trascrizione in tempo reale",+ "Modelli audio e IA più recenti",+ "iOS/Android (in arrivo)",+ "Nessuna conservazione dei dati",+ "Supporto prioritario"+ ],+ "cta": "Inizia",+ "switchToAnnual": "Passa all'annuale"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "Personalizzato",+ "features": [+ "Sincronizzazione cloud",+ "Funzionalità team (in arrivo)",+ "SSO e conformità"+ ],+ "cta": "Contattaci"+ },+ "currentPlan": "Piano attuale"+ },+ "signedOutPlans": {+ "button": "Crea account gratuito"+ },"user": "Utente","wordsRemaining": "{{remaining}} rimanenti"},@@ -1023,26 +1028,6 @@"resetAppData": "Reimposta dati app","resetAppDataDescription": "Elimina definitivamente tutte le impostazioni, le trascrizioni e i dati in cache"},- "dictionary": {- "add": "Aggiungi",- "addWordOrPhrase": "Aggiungi una parola o una frase",- "agentNameAutoManaged": "Nome agente (gestito automaticamente)",- "clearAll": "Cancella tutto",- "clearDictionaryDescription": "Questa operazione rimuoverà tutte le parole dal dizionario personalizzato. L'azione non può essere annullata.",- "clearDictionaryTitle": "Cancellare il dizionario?",- "description": "Aggiungi parole, nomi o termini tecnici per migliorare la precisione della trascrizione",- "howItWorksDescription": "Le parole aggiunte vengono incluse nel prompt dell'IA, in modo che il modello sappia cercare e preservare questi termini durante la correzione della trascrizione.",- "howItWorksTitle": "Come funziona",- "noWords": "Nessuna parola aggiunta",- "placeholder": "es. OpenWhispr, Kubernetes, Dr. Martinez...",- "pressEnterToAdd": "Premi Invio per aggiungere",- "removeWord": "Rimuovi parola",- "tipDescription": "Aggiungi nomi propri, termini tecnici o qualsiasi parola che potrebbe essere trascritta in modo errato.",- "tipLabel": "Suggerimento",- "title": "Dizionario personalizzato",- "wordsAppearHere": "Le parole aggiunte appariranno qui",- "yourWords": "Le tue parole"- },"general": {"appearance": {"auto": "Automatico",@@ -1062,6 +1047,7 @@"hotkey": {"activationMode": "Modalità di attivazione","description": "La combinazione di tasti che avvia e ferma la dettatura vocale",+ "resetToDefault": "Ripristina a {{hotkey}}","title": "Scorciatoia di dettatura"},"microphone": {@@ -1245,5 +1231,284 @@"openai_oss_gpt_oss_20b_mxfp4": "Modello open-weight di OpenAI per hardware consumer"}}+ },+ "referral": {+ "modalTitle": "Invita un amico",+ "title": "Invita e ottieni ricompense",+ "subtitle": "Regala un mese. Ricevi un mese.",+ "tabs": {+ "refer": "Invita",+ "pastInvites": "Inviti passati"+ },+ "howItWorks": {+ "shareLink": "Condividi il tuo link di invito",+ "theySignUp": "Si iscrivono e ottengono un ",+ "freeMonthOfPro": "mese gratuito di Pro",+ "youGet": "Tu ottieni un ",+ "freeMonth": "mese gratuito",+ "whenTheyDictate": " quando dettano 2.000 parole"+ },+ "inviteLink": {+ "title": "Il tuo link di invito",+ "copy": "Copia",+ "copied": "Copiato"+ },+ "sendInvites": {+ "title": "Invia inviti",+ "placeholder": "[email protected]",+ "send": "Invia",+ "sending": "Invio in corso"+ },+ "stats": {+ "referred": "Invitati",+ "converted": "Convertiti",+ "monthsEarned": "Mesi guadagnati"+ },+ "status": {+ "converted": "Convertito",+ "opened": "Aperto",+ "failed": "Non riuscito",+ "sent": "Inviato"+ },+ "empty": {+ "title": "Nessun invito inviato",+ "description": "Condividi il tuo link o invia un invito per iniziare"+ },+ "toasts": {+ "copiedTitle": "Copiato!",+ "copiedDescription": "Link di invito copiato negli appunti",+ "copyFailedTitle": "Copia non riuscita",+ "copyFailedDescription": "Impossibile copiare il link negli appunti",+ "invalidEmailTitle": "Email non valida",+ "invalidEmailDescription": "Inserisci un indirizzo email valido",+ "inviteSentTitle": "Invito inviato!",+ "inviteSentDescription": "Invito inviato a {{email}}",+ "sendFailedTitle": "Invio non riuscito",+ "sendFailedDescription": "Impossibile inviare l'invito. Riprova."+ },+ "errors": {+ "unableToLoad": "Impossibile caricare i dati degli inviti",+ "unableToLoadStats": "Impossibile caricare le statistiche degli inviti. Riprova più tardi."+ },+ "tryAgain": "Riprova",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "La tua firma audio",+ "stop": "Ferma",+ "playSignal": "Riproduci segnale"+ },+ "friends": {+ "title": "Amici",+ "completed": "Completato",+ "sentInvites": "Inviti inviati"+ }+ },+ "notes": {+ "folders": {+ "title": "Cartelle",+ "soon": "Presto",+ "folderName": "Nome cartella",+ "couldNotCreate": "Impossibile creare la cartella",+ "couldNotRename": "Impossibile rinominare la cartella",+ "couldNotDelete": "Impossibile eliminare la cartella"+ },+ "list": {+ "title": "Note",+ "newNote": "Nuova nota",+ "untitled": "Senza titolo",+ "untitledNote": "Nota senza titolo",+ "timeNow": "Adesso",+ "minutesAgo": "{{count}}m",+ "hoursAgo": "{{count}}h",+ "daysAgo": "{{count}}g"+ },+ "editor": {+ "untitled": "Senza titolo",+ "noteTitle": "Titolo della nota",+ "stop": "Ferma",+ "transcribe": "Trascrivi",+ "processing": "Elaborazione...",+ "export": "Esporta",+ "asMarkdown": "Come Markdown",+ "asPlainText": "Come testo semplice",+ "raw": "Originale",+ "enhanced": "Migliorato",+ "saving": "Salvataggio",+ "wordsCount": "{{count}} parole",+ "startWriting": "Inizia a scrivere...",+ "staleIndicator": "Il contenuto è cambiato dall'ultimo miglioramento"+ },+ "upload": {+ "title": "Carica audio",+ "using": "Utilizzando {{model}}",+ "dropOrBrowse": "Trascina un file audio o clicca per sfogliare",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Rilascia per caricare",+ "transcribe": "Trascrivi",+ "cancel": "Annulla",+ "transcribingCloud": "Trascrizione nel cloud...",+ "transcribingLocal": "Trascrizione locale...",+ "transcribingProvider": "Trascrizione tramite {{provider}}...",+ "transcriptionComplete": "Trascrizione completata",+ "openNote": "Apri nota",+ "uploadAnother": "Carica un altro",+ "retry": "Riprova",+ "startOver": "Ricomincia",+ "transcriptionSettings": "Impostazioni di trascrizione",+ "newFolder": "Nuova cartella",+ "folderName": "Nome cartella",+ "create": "Crea",+ "setupTitle": "Configura la trascrizione",+ "setupDescription": "Scegli come trascrivere il tuo audio. Questo si applica anche alla dettatura dal vivo.",+ "continue": "Continua",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Personalizzato",+ "selectFolder": "Seleziona cartella",+ "transcriptionFailed": "Trascrizione non riuscita",+ "errorOccurred": "Si è verificato un errore",+ "noProviderTitle": "Nessun provider di trascrizione configurato",+ "noProviderDescription": "Aggiungi una chiave API o scarica un modello locale per iniziare a trascrivere.",+ "noProviderAction": "Apri impostazioni di trascrizione"+ },+ "meeting": {+ "title": "Note delle riunioni",+ "description": "Identificazione degli interlocutori e riassunti strutturati",+ "comingSoon": "Prossimamente"+ },+ "context": {+ "moveToFolder": "Sposta nella cartella",+ "delete": "Elimina",+ "rename": "Rinomina",+ "searchFolders": "Cerca cartelle...",+ "noResults": "Nessuna cartella trovata",+ "newFolder": "Nuova cartella"+ },+ "actions": {+ "manage": "Gestisci azioni...",+ "manageTitle": "Azioni personalizzate",+ "addAction": "Nuova azione",+ "editAction": "Modifica azione",+ "namePlaceholder": "Nome dell'azione",+ "descriptionPlaceholder": "Descrizione breve (facoltativo)",+ "promptPlaceholder": "Cosa deve fare l'IA con il contenuto della nota?",+ "builtIn": "Integrata",+ "save": "Salva",+ "update": "Aggiorna",+ "cancel": "Annulla",+ "noActions": "Nessuna azione personalizzata ancora",+ "runAction": "Esegui {{name}}",+ "selectAction": "Seleziona azione",+ "done": "Fatto",+ "builtin": {+ "cleanupNotes": {+ "name": "Pulisci note",+ "description": "Correggere grammatica, struttura e formattazione"+ }+ }+ },+ "empty": {+ "title": "Ancora nessuna nota qui",+ "description": "Crea la tua prima nota per iniziare a scrivere",+ "selectTitle": "Seleziona una nota",+ "selectDescription": "Scegli una nota dalla barra laterale",+ "createNote": "Crea nota",+ "emptyFolder": "Nessuna nota in questa cartella"+ },+ "addToFolder": {+ "title": "Aggiungi note",+ "searchPlaceholder": "Cerca note da aggiungere...",+ "addExisting": "Aggiungi esistenti",+ "addCount": "Aggiungi {{count}} note",+ "noResults": "Nessuna nota corrispondente",+ "noNotesAvailable": "Nessun'altra nota disponibile",+ "today": "Oggi",+ "yesterday": "Ieri"+ },+ "onboarding": {+ "llm": {+ "title": "Configura un modello IA",+ "description": "Le azioni usano l'IA per trasformare le tue note. Configura un modello linguistico per iniziare.",+ "configured": "Modello IA configurato"+ },+ "actions": {+ "title": "Azioni basate sull'IA",+ "description": "Le azioni trasformano le tue note: correggono le trascrizioni, riassumono le riunioni e altro ancora. Usa le azioni integrate o creane di tue.",+ "builtInLabel": "Integrata",+ "createTitle": "Crea la tua azione",+ "createDescription": "Definisci un'azione personalizzata con il tuo prompt IA. Puoi sempre modificarle o aggiungerne altre nelle impostazioni.",+ "created": "Creata!"+ },+ "getStarted": "Inizia"+ },+ "realtimeBanner": {+ "message": "Trascrizione in tempo reale disponibile con Pro",+ "upgrade": "Passa a Pro"+ }+ },+ "dictionary": {+ "addWord": "Aggiungi parola",+ "removeWord": "Rimuovi {{word}}",+ "clearAll": "Cancella tutto",+ "howItWorks": "Come funziona",+ "howItWorksDetail": "Le parole aggiunte vengono incluse nel prompt dell'IA, in modo che il modello sappia cercare e preservare questi termini durante la correzione della trascrizione.",+ "autoManaged": "Gestito automaticamente",+ "inputHint": "Premi Invio per aggiungere",+ "title": "Dizionario personalizzato",+ "description": "Insegna all'IA il tuo vocabolario — nomi, gergo e termini che potrebbe altrimenti non riconoscere",+ "clearTitle": "Svuotare il dizionario?",+ "clearDescription": "Verranno rimossi tutti i termini dal tuo dizionario personalizzato. Questa azione non può essere annullata.",+ "addPlaceholder": "Aggiungi una parola o una frase..."+ },+ "sidebar": {+ "home": "Home",+ "notes": "Note",+ "upload": "Carica",+ "dictionary": "Dizionario",+ "referral": "Ottieni un mese gratis",+ "settings": "Impostazioni",+ "support": "Assistenza",+ "limitReached": "Limite settimanale raggiunto",+ "limitReachedDescription": "Passa a Pro per trascrizioni illimitate.",+ "upgradeToPro": "Passa a Pro",+ "upgradeTitle": "Passa a Pro",+ "upgradeDescription": "Trascrizioni illimitate e funzionalità avanzate.",+ "learnMore": "Scopri di più",+ "defaultUser": "Utente",+ "notSignedIn": "Non hai effettuato l'accesso"+ },+ "usage": {+ "approachingLimit": "Limite settimanale quasi raggiunto",+ "approachingLimitDescription": "Hai usato {{wordsUsed}} di {{limit}} parole gratuite questa settimana.",+ "yourPlan": "Il tuo piano",+ "trial": "Prova ({{days}} giorno rimanente)",+ "trial_other": "Prova ({{days}} giorni rimanenti)",+ "pro": "Pro",+ "unlimitedTrial": "Trascrizioni illimitate durante il periodo di prova",+ "unlimited": "Trascrizioni illimitate",+ "manageSubscription": "Gestisci abbonamento",+ "weeklyUsage": "Utilizzo settimanale",+ "limitReached": "Limite raggiunto",+ "free": "Gratuito",+ "wordsRemaining": "{{remaining}} parole rimanenti",+ "rollingLimit": "Limite settimanale mobile",+ "upgradeToPro": "Passa a Pro",+ "useYourOwnKey": "Usa la tua chiave API",+ "upgradeUnlimited": "Passa a Pro — trascrizioni illimitate"+ },+ "support": {+ "joinDiscord": "Unisciti a Discord",+ "contactSupport": "Contatta il supporto",+ "submitBug": "Segnala un bug"+ },+ "apiKeyInput": {+ "placeholder": "Incolla la tua chiave API",+ "label": "Chiave API",+ "save": "Salva",+ "cancelEdit": "Annulla modifica",+ "edit": "Modifica",+ "add": "Aggiungi",+ "editButton": "Modifica",+ "addButton": "Aggiungi"}}diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex a3fe0e1e1..e6f792f91 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "OpenWhispr を読み込み中...",- "oauth": {- "redirectTitle": "OpenWhispr にリダイレクト中",- "closeTab": "このタブは閉じて構いません"- },- "buttons": {- "cancelRecording": "録音をキャンセル",- "cancelProcessing": "処理をキャンセル"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] で音声入力",- "recording": "録音中...",- "processing": "処理中...",- "clickToSpeak": "クリックして音声入力"- },- "toasts": {- "hotkeyChanged": {- "title": "ホットキーを変更しました"- },- "hotkeyUnavailable": {- "title": "ホットキーが使用できません",- "description": "ホットキーを登録できませんでした。設定から別のホットキーを設定してください。"- }- },- "commandMenu": {- "startListening": "音声入力を開始",- "stopListening": "音声入力を停止",- "hideForNow": "一時的に非表示にする"- }- },"settings": {"language": {"sectionTitle": "言語",@@ -172,10 +140,10 @@"availableModels": "利用可能なモデル","fast": "高速","hold": "ホールド",- "less": "少なく表示",- "more": "もっと見る","private": "プライベート",- "tap": "タップ"+ "tap": "タップ",+ "close": "閉じる",+ "dismiss": "閉じる"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "お支払い方法を更新"},"history": {- "title": "文字起こし履歴","couldNotLoadTitle": "履歴を読み込めませんでした","couldNotLoadDescription": "文字起こし履歴の読み込み中に問題が発生しました。アプリを閉じて再度開いてください。","copiedTitle": "コピーしました!","copiedDescription": "テキストをクリップボードにコピーしました","couldNotCopyTitle": "コピーできませんでした","couldNotCopyDescription": "クリップボードへのコピー中に問題が発生しました。もう一度お試しください。",- "clearTitle": "履歴を消去",- "clearDescription": "すべての文字起こし履歴を削除します。この操作は元に戻せません。",- "clearedTitle": "履歴を消去しました",- "clearedDescription": "{{count}} 件の文字起こしを削除しました",- "clearedDescription_other": "{{count}} 件の文字起こしを削除しました",- "couldNotClearTitle": "履歴を消去できませんでした",- "couldNotClearDescription": "問題が発生しました。もう一度お試しください。","deleteTitle": "文字起こしを削除","deleteDescription": "この文字起こしは完全に削除されます。","couldNotDeleteTitle": "削除できませんでした","couldNotDeleteDescription": "この文字起こしは既に削除されている可能性があります。","couldNotDeleteDescriptionGeneric": "問題が発生しました。もう一度お試しください。",- "clear": "消去","empty": "文字起こし履歴はまだありません","press": "押してください",- "toStart": "開始するには"+ "toStart": "開始するには",+ "dateGroups": {+ "today": "今日",+ "yesterday": "昨日"+ }},"cloudMigration": {"title": "OpenWhispr Pro へようこそ",@@ -292,8 +255,6 @@"localDescription": "デバイス上で動作。完全なプライバシー保護、オフライン対応。","cloudDescription": "API 経由の高度なモデル。高速・高機能、インターネット接続が必要。"},- "enableTitle": "AI テキスト補正を有効にする",- "enableDescription": "AI を使って文字起こしの品質を自動的に向上","custom": {"endpointWithProtocol": "プロトコルを含む完全なベース URL を入力してください(例: https://server/v1)。","httpsRequired": "HTTPS が必要です(ローカルネットワークのみ HTTP を許可)。",@@ -480,6 +441,7 @@},"auth": {"cloudNotConfigured": "クラウド未設定",+ "sessionExpired": "セッションの有効期限が切れました","common": {"back": "戻る","continue": "続ける",@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "アカウント","app": "アプリ",- "intelligence": "インテリジェンス",- "profile": "プロフィール",- "speech": "音声",+ "speechAi": "音声 & AI","system": "システム"},"sections": {"account": {- "description": "サインインと使用状況",+ "description": "プロフィールとサインイン","label": "アカウント"},- "agentConfig": {- "description": "音声エージェント設定",- "label": "エージェント"- },- "aiModels": {- "description": "テキスト補正と改善",- "label": "AI モデル"- },- "developer": {- "description": "ログ・診断・データ",- "label": "開発者"- },- "dictionary": {- "description": "カスタム語句",- "label": "辞書"+ "plansBilling": {+ "description": "プラン、使用状況、請求",+ "label": "プランと請求"},"general": {- "description": "外観・ホットキー・起動設定",+ "description": "外観、サウンド、起動設定","label": "環境設定"},- "permissions": {- "description": "マイクとアクセシビリティ",- "label": "権限"- },- "privacy": {- "description": "クラウドバックアップと分析",- "label": "プライバシー"- },- "prompts": {- "description": "システムプロンプトスタジオ",- "label": "プロンプト"+ "hotkeys": {+ "description": "ディクテーションホットキーと起動モード",+ "label": "ホットキー"},"transcription": {"description": "音声テキスト変換エンジン","label": "文字起こし"+ },+ "intelligence": {+ "description": "AIモデル、エージェント、プロンプト",+ "label": "インテリジェンス"+ },+ "privacyData": {+ "description": "プライバシー、権限、分析",+ "label": "プライバシーとデータ"+ },+ "system": {+ "description": "更新、ストレージ、開発者ツール",+ "label": "システム"}},"title": "設定"@@ -933,6 +886,51 @@"trial": "トライアル"},"planTitle": "プラン",+ "pricing": {+ "title": "プラン",+ "monthly": "月払い",+ "annual": "年払い",+ "annualBadge": "17% お得",+ "free": {+ "name": "無料",+ "price": "$0",+ "period": "永久",+ "trialNote": "OpenWhispr Pro の 7 日間無料トライアル付き",+ "features": [+ "週 2,000 ワード",+ "ローカル AI モデル",+ "自分の API キーを使用",+ "辞書とスニペット",+ "100 以上の言語に対応",+ "データ保持なし"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/月",+ "annualPrice": "$80",+ "annualPeriod": "/年",+ "features": [+ "無料プランのすべて",+ "無制限の使用",+ "リアルタイム文字起こし",+ "最新の音声 & AI モデル",+ "iOS/Android(近日公開)",+ "データ保持なし",+ "優先サポート"+ ],+ "cta": "始める",+ "switchToAnnual": "年払いに切り替え"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "カスタム",+ "features": ["クラウド同期", "チーム機能(近日公開)", "SSO & コンプライアンス"],+ "cta": "お問い合わせ"+ },+ "currentPlan": "現在のプラン"+ },"rollingWeeklyLimit": "週間利用上限(ローリング)","signOut": {"failedDescription": "サインアウト中に問題が発生しました。もう一度お試しください。",@@ -941,6 +939,9 @@"signingOut": "サインアウト中..."},"signedIn": "サインイン済み",+ "signedOutPlans": {+ "button": "無料アカウントを作成"+ },"title": "アカウント","toasts": {"approachingLimit": {@@ -1023,26 +1024,6 @@"resetAppData": "アプリデータをリセット","resetAppDataDescription": "すべての設定、文字起こし履歴、キャッシュデータを完全に削除"},- "dictionary": {- "add": "追加",- "addWordOrPhrase": "単語やフレーズを追加",- "agentNameAutoManaged": "エージェント名(自動管理)",- "clearAll": "すべて消去",- "clearDictionaryDescription": "カスタム辞書からすべての単語が削除されます。この操作は元に戻せません。",- "clearDictionaryTitle": "辞書を消去しますか?",- "description": "文字起こしの精度を向上させるために単語、名前、専門用語を追加",- "howItWorksDescription": "追加した単語は AI プロンプトに含まれ、文字起こしのクリーンアップ時にこれらの用語を正確に認識・保持します。",- "howItWorksTitle": "仕組み",- "noWords": "まだ単語が追加されていません",- "placeholder": "例: OpenWhispr、Kubernetes、田中先生...",- "pressEnterToAdd": "Enter で追加",- "removeWord": "単語を削除",- "tipDescription": "固有名詞、専門用語、誤って文字起こしされやすい単語を追加してください。",- "tipLabel": "ヒント",- "title": "カスタム辞書",- "wordsAppearHere": "追加した単語がここに表示されます",- "yourWords": "登録した単語"- },"general": {"appearance": {"auto": "自動",@@ -1062,6 +1043,7 @@"hotkey": {"activationMode": "起動モード","description": "音声ディクテーションの開始/停止に使用するキーの組み合わせ",+ "resetToDefault": "{{hotkey}}にリセット","title": "ディクテーションホットキー"},"microphone": {@@ -1245,5 +1227,284 @@"openai_oss_gpt_oss_20b_mxfp4": "一般消費者向けハードウェア用 OpenAI オープンウェイトモデル"}}+ },+ "notes": {+ "editor": {+ "transcribe": "文字起こし",+ "staleIndicator": "強化後にコンテンツが変更されました",+ "untitled": "無題",+ "noteTitle": "ノートのタイトル",+ "stop": "停止",+ "processing": "処理中...",+ "export": "エクスポート",+ "asMarkdown": "Markdown 形式",+ "asPlainText": "プレーンテキスト形式",+ "raw": "元のテキスト",+ "enhanced": "強化済み",+ "saving": "保存中",+ "wordsCount": "{{count}} 語",+ "startWriting": "書き始める..."+ },+ "context": {+ "moveToFolder": "フォルダに移動",+ "delete": "削除",+ "rename": "名前を変更",+ "searchFolders": "フォルダを検索...",+ "noResults": "フォルダが見つかりません",+ "newFolder": "新しいフォルダ"+ },+ "actions": {+ "manage": "アクションを管理...",+ "manageTitle": "カスタムアクション",+ "addAction": "新しいアクション",+ "editAction": "アクションを編集",+ "namePlaceholder": "アクション名",+ "descriptionPlaceholder": "簡単な説明(任意)",+ "promptPlaceholder": "AIにノートの内容をどう処理させますか?",+ "builtIn": "組み込み",+ "save": "保存",+ "update": "更新",+ "cancel": "キャンセル",+ "noActions": "カスタムアクションはまだありません",+ "runAction": "{{name}} を実行",+ "selectAction": "アクションを選択",+ "done": "完了",+ "builtin": {+ "cleanupNotes": {+ "name": "ノートを整理",+ "description": "文法、構成、書式を修正する"+ }+ }+ },+ "empty": {+ "title": "まだノートがありません",+ "description": "最初のノートを作成して書き始めましょう",+ "selectTitle": "ノートを選択",+ "selectDescription": "サイドバーからノートを選んでください",+ "createNote": "ノートを作成",+ "emptyFolder": "このフォルダにノートはありません"+ },+ "addToFolder": {+ "title": "ノートを追加",+ "searchPlaceholder": "追加するノートを検索...",+ "addExisting": "既存を追加",+ "addCount": "{{count}}件のノートを追加",+ "noResults": "一致するノートがありません",+ "noNotesAvailable": "他のノートはありません",+ "today": "今日",+ "yesterday": "昨日"+ },+ "folders": {+ "title": "フォルダ",+ "soon": "近日公開",+ "folderName": "フォルダ名",+ "couldNotCreate": "フォルダを作成できませんでした",+ "couldNotRename": "フォルダの名前を変更できませんでした",+ "couldNotDelete": "フォルダを削除できませんでした"+ },+ "list": {+ "title": "ノート",+ "newNote": "新規ノート",+ "untitled": "無題",+ "untitledNote": "無題のノート",+ "timeNow": "たった今",+ "minutesAgo": "{{count}}分前",+ "hoursAgo": "{{count}}時間前",+ "daysAgo": "{{count}}日前"+ },+ "upload": {+ "title": "音声をアップロード",+ "using": "{{model}} を使用中",+ "dropOrBrowse": "音声ファイルをドロップまたはクリックして選択",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "ドロップしてアップロード",+ "transcribe": "文字起こし",+ "cancel": "キャンセル",+ "transcribingCloud": "クラウドで文字起こし中...",+ "transcribingLocal": "ローカルで文字起こし中...",+ "transcribingProvider": "{{provider}} で文字起こし中...",+ "transcriptionComplete": "文字起こし完了",+ "openNote": "ノートを開く",+ "uploadAnother": "別のファイルをアップロード",+ "retry": "再試行",+ "startOver": "やり直す",+ "transcriptionSettings": "文字起こし設定",+ "newFolder": "新しいフォルダ",+ "folderName": "フォルダ名",+ "create": "作成",+ "setupTitle": "文字起こしを設定",+ "setupDescription": "音声の文字起こし方法を選択してください。ライブディクテーションにも適用されます。",+ "continue": "続ける",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "カスタム",+ "selectFolder": "フォルダを選択",+ "transcriptionFailed": "文字起こしに失敗しました",+ "errorOccurred": "エラーが発生しました",+ "noProviderTitle": "文字起こしプロバイダーが設定されていません",+ "noProviderDescription": "API キーを追加するか、ローカルモデルをダウンロードして文字起こしを開始してください。",+ "noProviderAction": "文字起こし設定を開く"+ },+ "meeting": {+ "title": "議事録",+ "description": "話者識別と構造化されたサマリー",+ "comingSoon": "近日公開"+ },+ "onboarding": {+ "llm": {+ "title": "AI モデルを設定",+ "description": "アクションは AI を使ってノートを変換します。言語モデルを設定して始めましょう。",+ "configured": "AI モデルが設定されました"+ },+ "actions": {+ "title": "AI アクション",+ "description": "アクションでノートを変換できます — 文字起こしの整理、議事録の要約など。組み込みアクションを使うか、独自のアクションを作成できます。",+ "builtInLabel": "組み込み",+ "createTitle": "独自のアクションを作成",+ "createDescription": "独自の AI プロンプトでカスタムアクションを定義できます。設定からいつでも編集・追加できます。",+ "created": "作成しました!"+ },+ "getStarted": "始める"+ },+ "realtimeBanner": {+ "message": "Pro でリアルタイム文字起こしが利用可能",+ "upgrade": "アップグレード"+ }+ },+ "dictionary": {+ "addWord": "単語を追加",+ "removeWord": "{{word}} を削除",+ "clearAll": "すべてクリア",+ "howItWorks": "仕組み",+ "howItWorksDetail": "追加した単語は AI プロンプトに含まれ、文字起こし時にこれらの用語を正確に認識・保持します。",+ "autoManaged": "自動管理",+ "inputHint": "Enter で追加",+ "title": "カスタム辞書",+ "description": "AIに語彙を学習させましょう — 名前、専門用語、見落とされがちな表現など",+ "clearTitle": "辞書をクリアしますか?",+ "clearDescription": "カスタム辞書のすべての単語が削除されます。この操作は元に戻せません。",+ "addPlaceholder": "単語やフレーズを追加..."+ },+ "referral": {+ "title": "紹介して特典をゲット",+ "subtitle": "1か月あげて、1か月もらおう。",+ "modalTitle": "友達を紹介",+ "tabs": {+ "refer": "紹介する",+ "pastInvites": "過去の招待"+ },+ "howItWorks": {+ "shareLink": "招待リンクを共有",+ "theySignUp": "相手が登録すると",+ "freeMonthOfPro": "Pro の無料 1 か月",+ "youGet": "あなたも",+ "freeMonth": "無料 1 か月",+ "whenTheyDictate": "を獲得(相手が 2,000 語ディクテーションした時点で)"+ },+ "inviteLink": {+ "title": "招待リンク",+ "copy": "コピー",+ "copied": "コピーしました"+ },+ "sendInvites": {+ "title": "招待を送信",+ "placeholder": "[email protected]",+ "send": "送信",+ "sending": "送信中"+ },+ "stats": {+ "referred": "紹介済み",+ "converted": "登録済み",+ "monthsEarned": "獲得した月数"+ },+ "status": {+ "converted": "登録済み",+ "opened": "開封済み",+ "failed": "失敗",+ "sent": "送信済み"+ },+ "friends": {+ "title": "フレンド",+ "completed": "完了",+ "sentInvites": "送信済みの招待"+ },+ "empty": {+ "title": "まだ招待を送信していません",+ "description": "リンクを共有するか招待を送信して始めましょう"+ },+ "toasts": {+ "copiedTitle": "コピーしました!",+ "copiedDescription": "紹介リンクをクリップボードにコピーしました",+ "copyFailedTitle": "コピーに失敗しました",+ "copyFailedDescription": "リンクをクリップボードにコピーできませんでした",+ "invalidEmailTitle": "無効なメールアドレス",+ "invalidEmailDescription": "有効なメールアドレスを入力してください",+ "inviteSentTitle": "招待を送信しました!",+ "inviteSentDescription": "{{email}} に招待を送信しました",+ "sendFailedTitle": "送信に失敗しました",+ "sendFailedDescription": "招待の送信に失敗しました。もう一度お試しください。"+ },+ "errors": {+ "unableToLoad": "紹介データを読み込めませんでした",+ "unableToLoadStats": "紹介統計を読み込めませんでした。後でもう一度お試しください。"+ },+ "tryAgain": "再試行",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "あなたの音声シグネチャー",+ "stop": "停止",+ "playSignal": "シグナルを再生"+ }+ },+ "sidebar": {+ "home": "ホーム",+ "notes": "ノート",+ "upload": "アップロード",+ "dictionary": "辞書",+ "referral": "1か月無料を取得",+ "settings": "設定",+ "support": "サポート",+ "limitReached": "週間の利用上限に達しました",+ "limitReachedDescription": "Pro にアップグレードして無制限の文字起こしをご利用ください。",+ "upgradeToPro": "Pro にアップグレード",+ "upgradeTitle": "Pro にアップグレード",+ "upgradeDescription": "無制限の文字起こしと最新の AI モデルをご利用いただけます。",+ "learnMore": "詳しく見る",+ "defaultUser": "ユーザー",+ "notSignedIn": "未サインイン"+ },+ "usage": {+ "approachingLimit": "週間制限に近づいています",+ "approachingLimitDescription": "今週の無料枠 {{limit}} 語のうち {{wordsUsed}} 語を使用しました。",+ "yourPlan": "現在のプラン",+ "trial": "トライアル(残り{{days}}日)",+ "trial_other": "トライアル(残り{{days}}日)",+ "pro": "Pro",+ "unlimitedTrial": "トライアル期間中は無制限で文字起こし可能",+ "unlimited": "無制限の文字起こし",+ "manageSubscription": "サブスクリプションを管理",+ "weeklyUsage": "週間使用量",+ "limitReached": "制限に達しました",+ "free": "無料",+ "wordsRemaining": "残り{{remaining}}語",+ "rollingLimit": "週間制限(ローリング方式)",+ "upgradeToPro": "Proにアップグレード",+ "useYourOwnKey": "自分のAPIキーを使用",+ "upgradeUnlimited": "Proにアップグレード — 無制限の文字起こし"+ },+ "support": {+ "joinDiscord": "Discord に参加",+ "contactSupport": "サポートに問い合わせ",+ "submitBug": "バグを報告"+ },+ "apiKeyInput": {+ "placeholder": "API キーを入力",+ "label": "API キー",+ "save": "保存",+ "cancelEdit": "編集をキャンセル",+ "edit": "編集",+ "add": "追加",+ "editButton": "編集",+ "addButton": "追加"}}diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex c8ecc111f..9b4c575f6 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Carregando OpenWhispr...",- "oauth": {- "redirectTitle": "Redirecionando para OpenWhispr",- "closeTab": "Você pode fechar esta aba"- },- "buttons": {- "cancelRecording": "Cancelar gravação",- "cancelProcessing": "Cancelar processamento"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] para falar",- "recording": "Gravando...",- "processing": "Processando...",- "clickToSpeak": "Clique para falar"- },- "toasts": {- "hotkeyChanged": {- "title": "Atalho alterado"- },- "hotkeyUnavailable": {- "title": "Atalho indisponível",- "description": "Não foi possível registrar o atalho. Defina outro em Configurações."- }- },- "commandMenu": {- "startListening": "Iniciar escuta",- "stopListening": "Parar escuta",- "hideForNow": "Ocultar por enquanto"- }- },"settings": {"language": {"sectionTitle": "Idioma",@@ -144,10 +112,10 @@"availableModels": "Modelos disponíveis","fast": "Rápido","hold": "Segurar",- "less": "Menos",- "more": "Mais","private": "Privado",- "tap": "Toque"+ "tap": "Toque",+ "close": "Fechar",+ "dismiss": "Dispensar"},"onboarding": {"steps": {@@ -221,29 +189,24 @@"updatePayment": "Atualizar pagamento"},"history": {- "title": "Transcrições","couldNotLoadTitle": "Não foi possível carregar seu histórico","couldNotLoadDescription": "Ocorreu um erro ao carregar as transcrições. Feche e abra o app novamente.","copiedTitle": "Copiado!","copiedDescription": "Texto copiado para a área de transferência","couldNotCopyTitle": "Não foi possível copiar","couldNotCopyDescription": "Ocorreu um erro ao copiar para a área de transferência. Tente novamente.",- "clearTitle": "Limpar histórico",- "clearDescription": "Isso removerá todas as transcrições. Não é possível desfazer.",- "clearedTitle": "Histórico limpo",- "clearedDescription": "{{count}} transcrição removida",- "clearedDescription_other": "{{count}} transcrições removidas",- "couldNotClearTitle": "Não foi possível limpar o histórico",- "couldNotClearDescription": "Algo deu errado. Tente novamente.","deleteTitle": "Excluir transcrição","deleteDescription": "Esta transcrição será removida permanentemente.","couldNotDeleteTitle": "Não foi possível excluir","couldNotDeleteDescription": "Esta transcrição pode já ter sido removida.","couldNotDeleteDescriptionGeneric": "Algo deu errado. Tente novamente.",- "clear": "Limpar","empty": "Ainda sem transcrições","press": "Pressione",- "toStart": "para iniciar"+ "toStart": "para iniciar",+ "dateGroups": {+ "today": "Hoje",+ "yesterday": "Ontem"+ }},"cloudMigration": {"title": "Boas-vindas ao OpenWhispr Pro",@@ -264,8 +227,6 @@"localDescription": "Roda no seu dispositivo. Privacidade total, funciona offline.","cloudDescription": "Modelos avançados via API. Rápido e potente, requer internet."},- "enableTitle": "Ativar melhoria de texto com IA",- "enableDescription": "Use IA para melhorar automaticamente a qualidade da transcrição","custom": {"endpointWithProtocol": "Informe uma URL base completa com protocolo (por exemplo, https://server/v1).","httpsRequired": "HTTPS obrigatório (HTTP permitido apenas em rede local).",@@ -451,6 +412,7 @@}},"auth": {+ "sessionExpired": "Sessão expirada","cloudNotConfigured": "Nuvem não configurada","common": {"back": "Voltar",@@ -809,52 +771,43 @@},"settingsModal": {"groups": {+ "account": "Conta","app": "Aplicativo",- "intelligence": "Inteligência",- "profile": "Perfil",- "speech": "Fala",+ "speechAi": "Fala & IA","system": "Sistema"},"sections": {"account": {- "description": "Login e uso",+ "description": "Perfil e login","label": "Conta"},- "agentConfig": {- "description": "Configuração do agente de voz",- "label": "Agente"- },- "aiModels": {- "description": "Limpeza e melhoria de texto",- "label": "Modelos de IA"- },- "developer": {- "description": "Logs, diagnósticos e dados",- "label": "Desenvolvedor"- },- "dictionary": {- "description": "Palavras e frases personalizadas",- "label": "Dicionário"+ "plansBilling": {+ "description": "Planos, uso e cobrança",+ "label": "Planos e cobrança"},"general": {- "description": "Aparência, atalho e inicialização",+ "description": "Aparência, sons e inicialização","label": "Preferências"},- "permissions": {- "description": "Microfone e acessibilidade",- "label": "Permissões"- },- "privacy": {- "description": "Backup na nuvem e análises",- "label": "Privacidade"- },- "prompts": {- "description": "Estúdio de prompt do sistema",- "label": "Prompts"+ "hotkeys": {+ "description": "Atalho de ditado e ativação",+ "label": "Atalhos"},"transcription": {"description": "Motor de fala para texto","label": "Transcrição"+ },+ "intelligence": {+ "description": "Modelos de IA, agente e prompts",+ "label": "Inteligência"+ },+ "privacyData": {+ "description": "Privacidade, permissões e análise",+ "label": "Privacidade e dados"+ },+ "system": {+ "description": "Atualizações, armazenamento e ferramentas de desenvolvimento",+ "label": "Sistema"}},"title": "Configurações"@@ -925,6 +878,58 @@"description": "Transcrições ilimitadas, processamento prioritário e muito mais.","title": "Experimente o Pro grátis por 7 dias"},+ "pricing": {+ "title": "Planos",+ "monthly": "Mensal",+ "annual": "Anual",+ "annualBadge": "Economize 17%",+ "free": {+ "name": "Grátis",+ "price": "$0",+ "period": "para sempre",+ "trialNote": "Inclui 7 dias grátis de OpenWhispr Pro",+ "features": [+ "2.000 palavras/semana",+ "Modelos de IA locais",+ "Traga suas próprias chaves",+ "Dicionário e snippets",+ "Suporte para mais de 100 idiomas",+ "Sem retenção de dados"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/mês",+ "annualPrice": "$80",+ "annualPeriod": "/ano",+ "features": [+ "Tudo do plano Grátis",+ "Uso ilimitado",+ "Transcrição em tempo real",+ "Modelos de áudio e IA mais recentes",+ "iOS/Android (em breve)",+ "Sem retenção de dados",+ "Suporte prioritário"+ ],+ "cta": "Começar",+ "switchToAnnual": "Mudar para anual"+ },+ "enterprise": {+ "name": "Enterprise",+ "price": "Personalizado",+ "features": [+ "Sincronização na nuvem",+ "Recursos de equipe (em breve)",+ "SSO e conformidade"+ ],+ "cta": "Fale conosco"+ },+ "currentPlan": "Plano atual"+ },+ "signedOutPlans": {+ "button": "Criar conta gratuita"+ },"user": "Usuário","wordsRemaining": "{{remaining}} restantes"},@@ -995,26 +1000,6 @@"resetAppData": "Redefinir dados do app","resetAppDataDescription": "Excluir permanentemente todas as configurações, transcrições e dados em cache"},- "dictionary": {- "add": "Adicionar",- "addWordOrPhrase": "Adicionar palavra ou frase",- "agentNameAutoManaged": "Nome do agente (gerenciado automaticamente)",- "clearAll": "Limpar tudo",- "clearDictionaryDescription": "Isso removerá todas as palavras do seu dicionário personalizado. Esta ação não pode ser desfeita.",- "clearDictionaryTitle": "Limpar dicionário?",- "description": "Adicione palavras, nomes ou termos técnicos para melhorar a precisão da transcrição",- "howItWorksDescription": "As palavras adicionadas são incluídas no prompt de IA para que o modelo saiba procurar e preservar esses termos durante a limpeza da transcrição.",- "howItWorksTitle": "Como funciona",- "noWords": "Nenhuma palavra adicionada ainda",- "placeholder": "ex.: OpenWhispr, Kubernetes, Dr. Martinez...",- "pressEnterToAdd": "Pressione Enter para adicionar",- "removeWord": "Remover palavra",- "tipDescription": "Adicione nomes próprios, termos técnicos ou qualquer palavra que possa ser transcrita incorretamente.",- "tipLabel": "Dica",- "title": "Dicionário personalizado",- "wordsAppearHere": "As palavras adicionadas aparecerão aqui",- "yourWords": "Suas palavras"- },"general": {"appearance": {"auto": "Auto",@@ -1034,6 +1019,7 @@"hotkey": {"activationMode": "Modo de ativação","description": "A combinação de teclas que inicia e para o ditado por voz",+ "resetToDefault": "Redefinir para {{hotkey}}","title": "Atalho de ditado"},"microphone": {@@ -1245,5 +1231,284 @@"maximize": "Maximizar","restore": "Restaurar","close": "Fechar"+ },+ "referral": {+ "modalTitle": "Indicar um amigo",+ "title": "Indique e ganhe recompensas",+ "subtitle": "Dê um mês. Ganhe um mês.",+ "tabs": {+ "refer": "Indicar",+ "pastInvites": "Convites anteriores"+ },+ "howItWorks": {+ "shareLink": "Compartilhe seu link de convite",+ "theySignUp": "A pessoa se cadastra e ganha um ",+ "freeMonthOfPro": "mês grátis de Pro",+ "youGet": "Você ganha um ",+ "freeMonth": "mês grátis",+ "whenTheyDictate": " quando ela ditar 2.000 palavras"+ },+ "inviteLink": {+ "title": "Seu link de convite",+ "copy": "Copiar",+ "copied": "Copiado"+ },+ "sendInvites": {+ "title": "Enviar convites",+ "placeholder": "[email protected]",+ "send": "Enviar",+ "sending": "Enviando"+ },+ "stats": {+ "referred": "Indicados",+ "converted": "Convertidos",+ "monthsEarned": "Meses ganhos"+ },+ "status": {+ "converted": "Convertido",+ "opened": "Aberto",+ "failed": "Falhou",+ "sent": "Enviado"+ },+ "empty": {+ "title": "Nenhum convite enviado ainda",+ "description": "Compartilhe seu link ou envie um convite para começar"+ },+ "toasts": {+ "copiedTitle": "Copiado!",+ "copiedDescription": "Link de indicação copiado para a área de transferência",+ "copyFailedTitle": "Falha ao copiar",+ "copyFailedDescription": "Não foi possível copiar o link para a área de transferência",+ "invalidEmailTitle": "E-mail inválido",+ "invalidEmailDescription": "Por favor, insira um endereço de e-mail válido",+ "inviteSentTitle": "Convite enviado!",+ "inviteSentDescription": "Convite enviado para {{email}}",+ "sendFailedTitle": "Falha ao enviar",+ "sendFailedDescription": "Não foi possível enviar o convite. Por favor, tente novamente."+ },+ "errors": {+ "unableToLoad": "Não foi possível carregar os dados de indicação",+ "unableToLoadStats": "Não foi possível carregar as estatísticas de indicação. Por favor, tente novamente mais tarde."+ },+ "tryAgain": "Tentar novamente",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Sua assinatura de áudio",+ "stop": "Parar",+ "playSignal": "Reproduzir sinal"+ },+ "friends": {+ "title": "Amigos",+ "completed": "Concluído",+ "sentInvites": "Convites enviados"+ }+ },+ "notes": {+ "folders": {+ "title": "Pastas",+ "soon": "Em breve",+ "folderName": "Nome da pasta",+ "couldNotCreate": "Não foi possível criar a pasta",+ "couldNotRename": "Não foi possível renomear a pasta",+ "couldNotDelete": "Não foi possível excluir a pasta"+ },+ "list": {+ "title": "Notas",+ "newNote": "Nova nota",+ "untitled": "Sem título",+ "untitledNote": "Nota sem título",+ "timeNow": "Agora",+ "minutesAgo": "{{count}}m",+ "hoursAgo": "{{count}}h",+ "daysAgo": "{{count}}d"+ },+ "editor": {+ "untitled": "Sem título",+ "noteTitle": "Título da nota",+ "stop": "Parar",+ "transcribe": "Transcrever",+ "processing": "Processando...",+ "export": "Exportar",+ "asMarkdown": "Como Markdown",+ "asPlainText": "Como texto simples",+ "raw": "Original",+ "enhanced": "Aprimorado",+ "saving": "Salvando",+ "wordsCount": "{{count}} palavras",+ "startWriting": "Comece a escrever...",+ "staleIndicator": "O conteúdo mudou desde o aprimoramento"+ },+ "upload": {+ "title": "Enviar áudio",+ "using": "Usando {{model}}",+ "dropOrBrowse": "Arraste um arquivo de áudio ou clique para procurar",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Solte para enviar",+ "transcribe": "Transcrever",+ "cancel": "Cancelar",+ "transcribingCloud": "Transcrevendo pela nuvem...",+ "transcribingLocal": "Transcrevendo localmente...",+ "transcribingProvider": "Transcrevendo via {{provider}}...",+ "transcriptionComplete": "Transcrição concluída",+ "openNote": "Abrir nota",+ "uploadAnother": "Enviar outro",+ "retry": "Tentar novamente",+ "startOver": "Recomeçar",+ "transcriptionSettings": "Configurações de transcrição",+ "newFolder": "Nova pasta",+ "folderName": "Nome da pasta",+ "create": "Criar",+ "setupTitle": "Configurar transcrição",+ "setupDescription": "Escolha como transcrever seu áudio. Isso também se aplica à ditação ao vivo.",+ "continue": "Continuar",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Personalizado",+ "selectFolder": "Selecionar pasta",+ "transcriptionFailed": "Falha na transcrição",+ "errorOccurred": "Ocorreu um erro",+ "noProviderTitle": "Nenhum provedor de transcrição configurado",+ "noProviderDescription": "Adicione uma chave API ou baixe um modelo local para começar a transcrever.",+ "noProviderAction": "Abrir configurações de transcrição"+ },+ "meeting": {+ "title": "Notas de reunião",+ "description": "Identificação de falantes e resumos estruturados",+ "comingSoon": "Em breve"+ },+ "context": {+ "moveToFolder": "Mover para pasta",+ "delete": "Excluir",+ "rename": "Renomear",+ "searchFolders": "Pesquisar pastas...",+ "noResults": "Nenhuma pasta encontrada",+ "newFolder": "Nova pasta"+ },+ "actions": {+ "manage": "Gerenciar ações...",+ "manageTitle": "Ações personalizadas",+ "addAction": "Nova ação",+ "editAction": "Editar ação",+ "namePlaceholder": "Nome da ação",+ "descriptionPlaceholder": "Descrição breve (opcional)",+ "promptPlaceholder": "O que a IA deve fazer com o conteúdo da nota?",+ "builtIn": "Integrada",+ "save": "Salvar",+ "update": "Atualizar",+ "cancel": "Cancelar",+ "noActions": "Nenhuma ação personalizada ainda",+ "runAction": "Executar {{name}}",+ "selectAction": "Selecionar ação",+ "done": "Concluído",+ "builtin": {+ "cleanupNotes": {+ "name": "Limpar notas",+ "description": "Corrigir gramática, estrutura e formatação"+ }+ }+ },+ "empty": {+ "title": "Ainda não há notas aqui",+ "description": "Crie sua primeira nota para começar a escrever",+ "selectTitle": "Selecione uma nota",+ "selectDescription": "Escolha uma nota na barra lateral",+ "createNote": "Criar nota",+ "emptyFolder": "Nenhuma nota nesta pasta"+ },+ "addToFolder": {+ "title": "Adicionar notas",+ "searchPlaceholder": "Pesquisar notas para adicionar...",+ "addExisting": "Adicionar existentes",+ "addCount": "Adicionar {{count}} notas",+ "noResults": "Nenhuma nota encontrada",+ "noNotesAvailable": "Nenhuma outra nota disponível",+ "today": "Hoje",+ "yesterday": "Ontem"+ },+ "onboarding": {+ "llm": {+ "title": "Configure um modelo de IA",+ "description": "As ações usam IA para transformar suas notas. Configure um modelo de linguagem para começar.",+ "configured": "Modelo de IA configurado"+ },+ "actions": {+ "title": "Ações com IA",+ "description": "As ações transformam suas notas — limpam transcrições, resumem reuniões e muito mais. Use ações integradas ou crie as suas.",+ "builtInLabel": "Integrada",+ "createTitle": "Crie sua própria ação",+ "createDescription": "Defina uma ação personalizada com seu próprio prompt de IA. Você sempre pode editar ou adicionar mais nas configurações.",+ "created": "Criada!"+ },+ "getStarted": "Começar"+ },+ "realtimeBanner": {+ "message": "Transcrição em tempo real disponível no Pro",+ "upgrade": "Fazer upgrade"+ }+ },+ "dictionary": {+ "addWord": "Adicionar palavra",+ "removeWord": "Remover {{word}}",+ "clearAll": "Limpar tudo",+ "howItWorks": "Como funciona",+ "howItWorksDetail": "As palavras adicionadas são incluídas no prompt de IA para que o modelo saiba procurar e preservar esses termos durante a limpeza da transcrição.",+ "autoManaged": "Gerenciado automaticamente",+ "inputHint": "Pressione Enter para adicionar",+ "title": "Dicionário personalizado",+ "description": "Ensine a IA o seu vocabulário — nomes, jargões e termos que ela poderia não reconhecer",+ "clearTitle": "Limpar o dicionário?",+ "clearDescription": "Isso removerá todas as palavras do seu dicionário personalizado. Esta ação não pode ser desfeita.",+ "addPlaceholder": "Adicionar uma palavra ou frase..."+ },+ "sidebar": {+ "home": "Início",+ "notes": "Notas",+ "upload": "Enviar",+ "dictionary": "Dicionário",+ "referral": "Ganhe um mês grátis",+ "settings": "Configurações",+ "support": "Suporte",+ "limitReached": "Limite semanal atingido",+ "limitReachedDescription": "Faça upgrade para Pro para transcrições ilimitadas.",+ "upgradeToPro": "Fazer upgrade para Pro",+ "upgradeTitle": "Fazer upgrade para Pro",+ "upgradeDescription": "Transcrições ilimitadas e recursos avançados.",+ "learnMore": "Saiba mais",+ "defaultUser": "Usuário",+ "notSignedIn": "Não conectado"+ },+ "usage": {+ "approachingLimit": "Próximo do limite semanal",+ "approachingLimitDescription": "Você usou {{wordsUsed}} de {{limit}} palavras gratuitas esta semana.",+ "yourPlan": "Seu plano",+ "trial": "Teste ({{days}} dia restante)",+ "trial_other": "Teste ({{days}} dias restantes)",+ "pro": "Pro",+ "unlimitedTrial": "Transcrições ilimitadas durante o seu período de teste",+ "unlimited": "Transcrições ilimitadas",+ "manageSubscription": "Gerenciar assinatura",+ "weeklyUsage": "Uso semanal",+ "limitReached": "Limite atingido",+ "free": "Grátis",+ "wordsRemaining": "{{remaining}} palavras restantes",+ "rollingLimit": "Limite semanal contínuo",+ "upgradeToPro": "Fazer upgrade para Pro",+ "useYourOwnKey": "Usar sua própria chave API",+ "upgradeUnlimited": "Fazer upgrade para Pro — transcrições ilimitadas"+ },+ "support": {+ "joinDiscord": "Entrar no Discord",+ "contactSupport": "Contatar suporte",+ "submitBug": "Reportar um bug"+ },+ "apiKeyInput": {+ "placeholder": "Cole sua chave API",+ "label": "Chave API",+ "save": "Salvar",+ "cancelEdit": "Cancelar edição",+ "edit": "Editar",+ "add": "Adicionar",+ "editButton": "Editar",+ "addButton": "Adicionar"}}diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex a5924099b..f973dab46 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "Загрузка OpenWhispr...",- "oauth": {- "redirectTitle": "Перенаправление в OpenWhispr",- "closeTab": "Можете закрыть эту вкладку"- },- "buttons": {- "cancelRecording": "Отменить запись",- "cancelProcessing": "Отменить обработку"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] для диктовки",- "recording": "Запись...",- "processing": "Обработка...",- "clickToSpeak": "Нажмите для диктовки"- },- "toasts": {- "hotkeyChanged": {- "title": "Горячая клавиша изменена"- },- "hotkeyUnavailable": {- "title": "Горячая клавиша недоступна",- "description": "Не удалось зарегистрировать горячую клавишу. Выберите другую в настройках."- }- },- "commandMenu": {- "startListening": "Начать прослушивание",- "stopListening": "Остановить прослушивание",- "hideForNow": "Скрыть"- }- },"settings": {"language": {"sectionTitle": "Язык",@@ -172,10 +140,10 @@"availableModels": "Доступные модели","fast": "Быстрый","hold": "Удержание",- "less": "Меньше",- "more": "Больше","private": "Приватный",- "tap": "Нажатие"+ "tap": "Нажатие",+ "close": "Закрыть",+ "dismiss": "Скрыть"},"onboarding": {"steps": {@@ -249,30 +217,24 @@"updatePayment": "Обновить платёж"},"history": {- "title": "Транскрипции","couldNotLoadTitle": "Не удалось загрузить историю","couldNotLoadDescription": "Произошла ошибка при загрузке транскрипций. Попробуйте закрыть и снова открыть приложение.","copiedTitle": "Скопировано!","copiedDescription": "Текст скопирован в буфер обмена","couldNotCopyTitle": "Не удалось скопировать","couldNotCopyDescription": "Произошла ошибка при копировании в буфер обмена. Попробуйте снова.",- "clearTitle": "Очистить историю",- "clearDescription": "Все ваши транскрипции будут удалены. Это действие нельзя отменить.",- "clearedTitle": "История очищена",- "clearedDescription_one": "{{count}} транскрипция удалена",- "clearedDescription_few": "{{count}} транскрипции удалены",- "clearedDescription_many": "{{count}} транскрипций удалено",- "couldNotClearTitle": "Не удалось очистить историю",- "couldNotClearDescription": "Что-то пошло не так. Попробуйте снова.","deleteTitle": "Удалить транскрипцию","deleteDescription": "Эта транскрипция будет удалена безвозвратно.","couldNotDeleteTitle": "Не удалось удалить","couldNotDeleteDescription": "Эта транскрипция, возможно, уже была удалена.","couldNotDeleteDescriptionGeneric": "Что-то пошло не так. Попробуйте снова.",- "clear": "Очистить","empty": "Транскрипций пока нет","press": "Нажмите",- "toStart": "чтобы начать"+ "toStart": "чтобы начать",+ "dateGroups": {+ "today": "Сегодня",+ "yesterday": "Вчера"+ }},"cloudMigration": {"title": "Добро пожаловать в OpenWhispr Pro",@@ -293,8 +255,6 @@"localDescription": "Работает на вашем устройстве. Полная приватность, работает офлайн.","cloudDescription": "Продвинутые модели через API. Быстро и мощно, требуется интернет."},- "enableTitle": "Включить ИИ-улучшение текста",- "enableDescription": "Используйте ИИ для автоматического повышения качества транскрипций","custom": {"endpointWithProtocol": "Введите полный базовый URL, включая протокол (например, https://server/v1).","httpsRequired": "Требуется HTTPS (HTTP допускается только для локальной сети).",@@ -537,7 +497,8 @@"continueWithGoogle": "Продолжить с Google"},"welcomeSubtitle": "Диктуйте где угодно голосом",- "welcomeTitle": "Добро пожаловать в OpenWhispr"+ "welcomeTitle": "Добро пожаловать в OpenWhispr",+ "sessionExpired": "Сессия истекла. Пожалуйста, войдите снова."},"cleanupPrompt": "Очистка","developerSection": {@@ -838,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "Аккаунт","app": "Приложение",- "intelligence": "Интеллект",- "profile": "Профиль",- "speech": "Речь",+ "speechAi": "Речь и ИИ","system": "Система"},"sections": {"account": {- "description": "Вход и использование",+ "description": "Профиль и вход","label": "Аккаунт"},- "agentConfig": {- "description": "Настройка голосового агента",- "label": "Агент"- },- "aiModels": {- "description": "Очистка и улучшение текста",- "label": "ИИ-модели"- },- "developer": {- "description": "Логи, диагностика и данные",- "label": "Разработчик"- },- "dictionary": {- "description": "Пользовательские слова и фразы",- "label": "Словарь"+ "plansBilling": {+ "description": "Тарифы, использование и оплата",+ "label": "Тарифы и оплата"},"general": {- "description": "Внешний вид, горячая клавиша и автозапуск",+ "description": "Внешний вид, звуки и автозапуск","label": "Настройки"},- "permissions": {- "description": "Микрофон и универсальный доступ",- "label": "Разрешения"- },- "privacy": {- "description": "Облачное резервное копирование и аналитика",- "label": "Конфиденциальность"- },- "prompts": {- "description": "Студия системных промптов",- "label": "Промпты"+ "hotkeys": {+ "description": "Горячая клавиша диктовки и активация",+ "label": "Горячие клавиши"},"transcription": {"description": "Движок распознавания речи","label": "Транскрипция"+ },+ "intelligence": {+ "description": "ИИ-модели, агент и промпты",+ "label": "Интеллект"+ },+ "privacyData": {+ "description": "Конфиденциальность, разрешения и аналитика",+ "label": "Конфиденциальность и данные"+ },+ "system": {+ "description": "Обновления, хранилище и инструменты разработчика",+ "label": "Система"}},"title": "Настройки"@@ -954,6 +906,58 @@"description": "Безлимитные транскрипции, приоритетная обработка и многое другое.","title": "Попробуйте Pro бесплатно на 7 дней"},+ "pricing": {+ "title": "Тарифы",+ "monthly": "Ежемесячно",+ "annual": "Ежегодно",+ "annualBadge": "Скидка 17%",+ "free": {+ "name": "Бесплатный",+ "price": "$0",+ "period": "навсегда",+ "trialNote": "Включает 7 дней бесплатного Pro",+ "features": [+ "2 000 слов/неделя",+ "Локальные модели ИИ",+ "Свои API-ключи",+ "Словарь и сниппеты",+ "Поддержка 100+ языков",+ "Без хранения данных"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/мес.",+ "annualPrice": "$80",+ "annualPeriod": "/год",+ "features": [+ "Всё из Бесплатного",+ "Безлимитное использование",+ "Транскрипция в реальном времени",+ "Новейшие аудио- и ИИ-модели",+ "iOS/Android (скоро)",+ "Без хранения данных",+ "Приоритетная поддержка"+ ],+ "cta": "Начать",+ "switchToAnnual": "Перейти на годовой"+ },+ "enterprise": {+ "name": "Корпоративный",+ "price": "Индивидуально",+ "features": [+ "Облачная синхронизация",+ "Командные функции (скоро)",+ "SSO и соответствие требованиям"+ ],+ "cta": "Связаться с нами"+ },+ "currentPlan": "Текущий тариф"+ },+ "signedOutPlans": {+ "button": "Создать бесплатный аккаунт"+ },"user": "Пользователь","wordsRemaining": "Осталось {{remaining}}"},@@ -1024,26 +1028,6 @@"resetAppData": "Сбросить данные приложения","resetAppDataDescription": "Безвозвратно удалить все настройки, транскрипции и кешированные данные"},- "dictionary": {- "add": "Добавить",- "addWordOrPhrase": "Добавить слово или фразу",- "agentNameAutoManaged": "Имя агента (управляется автоматически)",- "clearAll": "Очистить всё",- "clearDictionaryDescription": "Все слова из пользовательского словаря будут удалены. Это действие нельзя отменить.",- "clearDictionaryTitle": "Очистить словарь?",- "description": "Добавляйте слова, имена или технические термины для повышения точности транскрипции",- "howItWorksDescription": "Добавленные слова включаются в промпт ИИ, чтобы модель распознавала и сохраняла эти термины при очистке транскрипции.",- "howItWorksTitle": "Как это работает",- "noWords": "Слова ещё не добавлены",- "placeholder": "например, OpenWhispr, Kubernetes, Др. Мартинез...",- "pressEnterToAdd": "Нажмите Enter для добавления",- "removeWord": "Удалить слово",- "tipDescription": "Добавляйте имена собственные, технические термины или любые слова, которые могут быть распознаны неправильно.",- "tipLabel": "Совет",- "title": "Пользовательский словарь",- "wordsAppearHere": "Добавленные слова появятся здесь",- "yourWords": "Ваши слова"- },"general": {"appearance": {"auto": "Авто",@@ -1063,6 +1047,7 @@"hotkey": {"activationMode": "Режим активации","description": "Комбинация клавиш для запуска и остановки голосовой диктовки",+ "resetToDefault": "Сбросить на {{hotkey}}","title": "Горячая клавиша диктовки"},"microphone": {@@ -1246,5 +1231,284 @@"openai_oss_gpt_oss_20b_mxfp4": "Открытая модель OpenAI для потребительского оборудования"}}+ },+ "referral": {+ "modalTitle": "Реферальная программа",+ "title": "Приглашайте и получайте награды",+ "subtitle": "Подарите месяц. Получите месяц.",+ "tabs": {+ "refer": "Пригласить",+ "pastInvites": "Отправленные приглашения"+ },+ "howItWorks": {+ "shareLink": "Поделитесь ссылкой-приглашением",+ "theySignUp": "Они регистрируются и получают ",+ "freeMonthOfPro": "бесплатный месяц Pro",+ "youGet": "Вы получаете ",+ "freeMonth": "бесплатный месяц",+ "whenTheyDictate": ", когда они надиктуют 2 000 слов"+ },+ "inviteLink": {+ "title": "Ваша ссылка-приглашение",+ "copy": "Копировать",+ "copied": "Скопировано"+ },+ "sendInvites": {+ "title": "Отправить приглашения",+ "placeholder": "[email protected]",+ "send": "Отправить",+ "sending": "Отправка"+ },+ "stats": {+ "referred": "Приглашено",+ "converted": "Активировано",+ "monthsEarned": "Месяцев заработано"+ },+ "status": {+ "converted": "Активировано",+ "opened": "Открыто",+ "failed": "Не удалось",+ "sent": "Отправлено"+ },+ "empty": {+ "title": "Приглашения ещё не отправлены",+ "description": "Поделитесь ссылкой или отправьте приглашение, чтобы начать"+ },+ "toasts": {+ "copiedTitle": "Скопировано!",+ "copiedDescription": "Реферальная ссылка скопирована в буфер обмена",+ "copyFailedTitle": "Ошибка копирования",+ "copyFailedDescription": "Не удалось скопировать ссылку в буфер обмена",+ "invalidEmailTitle": "Неверный адрес электронной почты",+ "invalidEmailDescription": "Пожалуйста, введите корректный адрес электронной почты",+ "inviteSentTitle": "Приглашение отправлено!",+ "inviteSentDescription": "Приглашение отправлено на {{email}}",+ "sendFailedTitle": "Ошибка отправки",+ "sendFailedDescription": "Не удалось отправить приглашение. Пожалуйста, попробуйте ещё раз."+ },+ "errors": {+ "unableToLoad": "Не удалось загрузить данные реферальной программы",+ "unableToLoadStats": "Не удалось загрузить статистику рефералов. Пожалуйста, попробуйте позже."+ },+ "tryAgain": "Попробовать снова",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "Ваша аудиоподпись",+ "stop": "Стоп",+ "playSignal": "Воспроизвести сигнал"+ },+ "friends": {+ "title": "Друзья",+ "completed": "Завершено",+ "sentInvites": "Отправленные приглашения"+ }+ },+ "notes": {+ "folders": {+ "title": "Папки",+ "soon": "Скоро",+ "folderName": "Название папки",+ "couldNotCreate": "Не удалось создать папку",+ "couldNotRename": "Не удалось переименовать папку",+ "couldNotDelete": "Не удалось удалить папку"+ },+ "list": {+ "title": "Заметки",+ "newNote": "Новая заметка",+ "untitled": "Без названия",+ "untitledNote": "Заметка без названия",+ "timeNow": "Только что",+ "minutesAgo": "{{count}} мин. назад",+ "hoursAgo": "{{count}} ч. назад",+ "daysAgo": "{{count}} дн. назад"+ },+ "editor": {+ "untitled": "Без названия",+ "noteTitle": "Название заметки",+ "stop": "Стоп",+ "transcribe": "Транскрибировать",+ "processing": "Обработка...",+ "export": "Экспорт",+ "asMarkdown": "Как Markdown",+ "asPlainText": "Как обычный текст",+ "raw": "Исходный",+ "enhanced": "Улучшенный",+ "saving": "Сохранение",+ "wordsCount": "{{count}} слов",+ "startWriting": "Начните писать...",+ "staleIndicator": "Содержимое изменилось после улучшения"+ },+ "upload": {+ "title": "Загрузить аудио",+ "using": "Используется {{model}}",+ "dropOrBrowse": "Перетащите аудиофайл или нажмите для выбора",+ "supportedFormats": "MP3, WAV, M4A, WebM, OGG, FLAC, AAC",+ "dropToUpload": "Отпустите для загрузки",+ "transcribe": "Транскрибировать",+ "cancel": "Отмена",+ "transcribingCloud": "Транскрибирование через облако...",+ "transcribingLocal": "Локальное транскрибирование...",+ "transcribingProvider": "Транскрибирование через {{provider}}...",+ "transcriptionComplete": "Транскрибирование завершено",+ "openNote": "Открыть заметку",+ "uploadAnother": "Загрузить ещё",+ "retry": "Повторить",+ "startOver": "Начать сначала",+ "transcriptionSettings": "Настройки транскрибирования",+ "newFolder": "Новая папка",+ "folderName": "Название папки",+ "create": "Создать",+ "setupTitle": "Настройте транскрибирование",+ "setupDescription": "Выберите способ транскрибирования аудио. Это также применяется к живой диктовке.",+ "continue": "Продолжить",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "Другой",+ "selectFolder": "Выбрать папку",+ "transcriptionFailed": "Ошибка транскрибирования",+ "errorOccurred": "Произошла ошибка",+ "noProviderTitle": "Провайдер транскрипции не настроен",+ "noProviderDescription": "Добавьте API-ключ или скачайте локальную модель, чтобы начать транскрипцию.",+ "noProviderAction": "Открыть настройки транскрипции"+ },+ "meeting": {+ "title": "Заметки со встреч",+ "description": "Определение говорящих и структурированные резюме",+ "comingSoon": "Скоро"+ },+ "context": {+ "moveToFolder": "Переместить в папку",+ "delete": "Удалить",+ "rename": "Переименовать",+ "searchFolders": "Поиск папок...",+ "noResults": "Папки не найдены",+ "newFolder": "Новая папка"+ },+ "actions": {+ "manage": "Управление действиями...",+ "manageTitle": "Пользовательские действия",+ "addAction": "Новое действие",+ "editAction": "Редактировать действие",+ "namePlaceholder": "Название действия",+ "descriptionPlaceholder": "Краткое описание (необязательно)",+ "promptPlaceholder": "Что ИИ должен сделать с содержимым заметки?",+ "builtIn": "Встроенное",+ "save": "Сохранить",+ "update": "Обновить",+ "cancel": "Отмена",+ "noActions": "Пользовательских действий пока нет",+ "runAction": "Запустить {{name}}",+ "selectAction": "Выбрать действие",+ "done": "Готово",+ "builtin": {+ "cleanupNotes": {+ "name": "Очистить заметки",+ "description": "Исправить грамматику, структуру и форматирование"+ }+ }+ },+ "empty": {+ "title": "Нет заметок",+ "description": "Создайте первую заметку",+ "selectTitle": "Выберите заметку",+ "selectDescription": "Выберите заметку на боковой панели",+ "createNote": "Создать заметку",+ "emptyFolder": "Папка пуста"+ },+ "addToFolder": {+ "title": "Добавить заметки",+ "searchPlaceholder": "Поиск заметок...",+ "addExisting": "Добавить существующие",+ "addCount": "Добавить: {{count}}",+ "noResults": "Не найдено",+ "noNotesAvailable": "Нет доступных заметок",+ "today": "Сегодня",+ "yesterday": "Вчера"+ },+ "onboarding": {+ "llm": {+ "title": "Настройте модель ИИ",+ "description": "Действия используют ИИ для обработки ваших заметок. Настройте языковую модель, чтобы начать.",+ "configured": "Модель ИИ настроена"+ },+ "actions": {+ "title": "Действия на основе ИИ",+ "description": "Действия преобразуют ваши заметки — очищают транскрипции, создают резюме встреч и многое другое. Используйте встроенные действия или создавайте свои.",+ "builtInLabel": "Встроенное",+ "createTitle": "Создайте своё действие",+ "createDescription": "Определите пользовательское действие с собственным промптом для ИИ. Вы всегда сможете изменить или добавить новые в настройках.",+ "created": "Создано!"+ },+ "getStarted": "Начать"+ },+ "realtimeBanner": {+ "message": "Транскрипция в реальном времени доступна в Pro",+ "upgrade": "Перейти"+ }+ },+ "dictionary": {+ "addWord": "Добавить слово",+ "removeWord": "Удалить {{word}}",+ "clearAll": "Очистить все",+ "howItWorks": "Как это работает",+ "howItWorksDetail": "Добавленные слова включаются в промпт ИИ, чтобы модель распознавала и сохраняла эти термины при очистке транскрипции.",+ "autoManaged": "Имя агента (управляется автоматически)",+ "inputHint": "Нажмите Enter для добавления",+ "addPlaceholder": "Добавить слово или фразу...",+ "title": "Словарь",+ "description": "Добавьте слова для улучшения транскрипции",+ "clearTitle": "Очистить словарь?",+ "clearDescription": "Все слова будут удалены без возможности восстановления."+ },+ "sidebar": {+ "home": "Главная",+ "notes": "Заметки",+ "upload": "Загрузить",+ "dictionary": "Словарь",+ "referral": "Получить бесплатный месяц",+ "settings": "Настройки",+ "support": "Поддержка",+ "limitReached": "Недельный лимит достигнут",+ "limitReachedDescription": "Перейдите на Pro для безлимитных транскрипций.",+ "upgradeToPro": "Перейти на Pro",+ "upgradeTitle": "Перейдите на Pro",+ "upgradeDescription": "Безлимитные транскрипции, транскрипция в реальном времени и многое другое.",+ "learnMore": "Узнать больше",+ "defaultUser": "Пользователь",+ "notSignedIn": "Не авторизован"+ },+ "usage": {+ "approachingLimit": "Приближается недельный лимит",+ "approachingLimitDescription": "На этой неделе использовано {{wordsUsed}} / {{limit}} слов.",+ "yourPlan": "Ваш тариф",+ "trial": "Пробный период ({{days}} дн.)",+ "trial_other": "Пробный период ({{days}} дн.)",+ "pro": "Pro",+ "unlimitedTrial": "Без ограничений в пробный период",+ "unlimited": "Без ограничений",+ "manageSubscription": "Управление подпиской",+ "weeklyUsage": "За неделю",+ "limitReached": "Лимит достигнут",+ "free": "Бесплатно",+ "wordsRemaining": "Осталось {{remaining}} слов",+ "rollingLimit": "Скользящий недельный лимит",+ "upgradeToPro": "Перейти на Pro",+ "useYourOwnKey": "Свой API-ключ",+ "upgradeUnlimited": "Pro — без ограничений"+ },+ "support": {+ "joinDiscord": "Присоединиться к Discord",+ "contactSupport": "Связаться с поддержкой",+ "submitBug": "Сообщить об ошибке"+ },+ "apiKeyInput": {+ "placeholder": "Введите ваш API-ключ",+ "label": "API-ключ",+ "save": "Сохранить",+ "cancelEdit": "Отменить редактирование",+ "edit": "Изменить",+ "add": "Добавить",+ "editButton": "Изменить ключ",+ "addButton": "Добавить ключ"}}diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex d8b71f671..34b835211 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "正在加载 OpenWhispr...",- "oauth": {- "redirectTitle": "正在跳转到 OpenWhispr",- "closeTab": "你可以关闭此标签页"- },- "buttons": {- "cancelRecording": "取消录音",- "cancelProcessing": "取消处理"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] 开始说话",- "recording": "录音中...",- "processing": "处理中...",- "clickToSpeak": "点击开始说话"- },- "toasts": {- "hotkeyChanged": {- "title": "快捷键已更改"- },- "hotkeyUnavailable": {- "title": "快捷键不可用",- "description": "无法注册快捷键,请在设置中选择其他快捷键。"- }- },- "commandMenu": {- "startListening": "开始听写",- "stopListening": "停止听写",- "hideForNow": "暂时隐藏"- }- },"settings": {"language": {"sectionTitle": "语言",@@ -172,10 +140,10 @@"availableModels": "可用模型","fast": "快速","hold": "按住",- "less": "收起",- "more": "展开","private": "隐私",- "tap": "点按"+ "tap": "点按",+ "close": "关闭",+ "dismiss": "忽略"},"onboarding": {"steps": {@@ -225,7 +193,7 @@"controlPanel": {"update": {"readyTitle": "更新已准备就绪",- "readyDescription": "点击\u201c安装更新\u201d以重启并安装最新版本。",+ "readyDescription": "点击“安装更新”以重启并安装最新版本。","problemTitle": "更新遇到问题","problemDescription": "无法完成更新,请稍后再试。","installTitle": "安装更新",@@ -249,29 +217,24 @@"updatePayment": "更新支付方式"},"history": {- "title": "转录记录","couldNotLoadTitle": "无法加载历史记录","couldNotLoadDescription": "加载转录记录时出错,请尝试关闭并重新打开应用。","copiedTitle": "已复制!","copiedDescription": "文本已复制到剪贴板","couldNotCopyTitle": "无法复制","couldNotCopyDescription": "复制到剪贴板时出错,请重试。",- "clearTitle": "清除历史记录",- "clearDescription": "这将删除你的所有转录记录,此操作无法撤销。",- "clearedTitle": "历史记录已清除",- "clearedDescription": "已删除 {{count}} 条转录记录",- "clearedDescription_other": "已删除 {{count}} 条转录记录",- "couldNotClearTitle": "无法清除历史记录",- "couldNotClearDescription": "出了点问题,请重试。","deleteTitle": "删除转录记录","deleteDescription": "此转录记录将被永久删除。","couldNotDeleteTitle": "无法删除","couldNotDeleteDescription": "此转录记录可能已被删除。","couldNotDeleteDescriptionGeneric": "出了点问题,请重试。",- "clear": "清除","empty": "暂无转录记录","press": "按下",- "toStart": "开始"+ "toStart": "开始",+ "dateGroups": {+ "today": "今天",+ "yesterday": "昨天"+ }},"cloudMigration": {"title": "欢迎使用 OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "在你的设备上运行,完全隐私,离线可用。","cloudDescription": "通过 API 使用高级模型,快速且强大,需要联网。"},- "enableTitle": "启用 AI 文本增强",- "enableDescription": "使用 AI 自动提升转录质量","custom": {"endpointWithProtocol": "请输入包含协议的完整 URL(例如 https://server/v1)。","httpsRequired": "需要 HTTPS(仅本地网络允许 HTTP)。",@@ -307,7 +268,7 @@"applyAndRefresh": "应用并刷新","queryPrefix": "我们将查询","querySuffix": "获取可用模型。",- "modelsReloadHint": "当你离开 URL 输入框或点击\u201c应用并刷新\u201d时,模型列表将重新加载。",+ "modelsReloadHint": "当你离开 URL 输入框或点击“应用并刷新”时,模型列表将重新加载。","enterEndpoint": "请在上方输入端点 URL 以加载模型。","fetchingModels": "正在从端点获取模型列表...","noModels": "未返回任何模型,请检查端点 URL。",@@ -499,7 +460,7 @@"failedUserCheck": "检查用户账户失败","generic": "出了点问题,请重试。","invalidCredentials": "邮箱或密码无效",- "plusAliasUnsupported": "不支持包含\u201c+\u201d的邮箱别名"+ "plusAliasUnsupported": "不支持包含“+”的邮箱别名"},"getStarted": "开始使用","legal": {@@ -536,7 +497,8 @@"continueWithGoogle": "使用 Google 继续"},"welcomeSubtitle": "随时随地用语音输入",- "welcomeTitle": "欢迎使用 OpenWhispr"+ "welcomeTitle": "欢迎使用 OpenWhispr",+ "sessionExpired": "会话已过期,请重新登录。"},"cleanupPrompt": "文本整理","developerSection": {@@ -556,7 +518,7 @@"footer": "日志不包含 API Key 或敏感数据","steps": {"0": "在启用 Debug 模式的情况下重现问题",- "1": "点击上方的\u201c打开日志文件夹\u201d",+ "1": "点击上方的“打开日志文件夹”","2": "将最新的日志文件附加到你的 Bug 报告中"},"title": "为技术支持分享日志"@@ -778,7 +740,7 @@"view": "查看"},"test": {- "addressHint": "试试说\u201c{{agentName}}\u201d来测试指令模式",+ "addressHint": "试试说“{{agentName}}”来测试指令模式","aiModels": "AI 模型","baseUrlMissing": "{{provider}} 的 URL 缺失,请在 AI 模型设置中添加。","cleanup": "文本整理",@@ -803,7 +765,7 @@"defaultPrompt": "默认提示词","modes": {"agent": {- "description": "通过\u201c{{agentName}}\u201d触发——执行命令、回答问题、撰写内容",+ "description": "通过“{{agentName}}”触发——执行命令、回答问题、撰写内容","label": "语音助手"},"cleanup": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "账户","app": "应用",- "intelligence": "智能",- "profile": "个人资料",- "speech": "语音",+ "speechAi": "语音与 AI","system": "系统"},"sections": {"account": {- "description": "登录与用量",+ "description": "个人资料与登录","label": "账户"},- "agentConfig": {- "description": "语音助手设置",- "label": "语音助手"- },- "aiModels": {- "description": "文本整理与增强",- "label": "AI 模型"- },- "developer": {- "description": "日志、诊断与数据",- "label": "开发者"- },- "dictionary": {- "description": "自定义词汇和短语",- "label": "词典"+ "plansBilling": {+ "description": "套餐、用量与账单",+ "label": "套餐与账单"},"general": {- "description": "外观、快捷键与启动",+ "description": "外观、声音与启动","label": "偏好设置"},- "permissions": {- "description": "麦克风与辅助功能",- "label": "权限"- },- "privacy": {- "description": "云端备份与分析",- "label": "隐私"- },- "prompts": {- "description": "系统提示词工作室",- "label": "提示词"+ "hotkeys": {+ "description": "听写快捷键与激活模式",+ "label": "快捷键"},"transcription": {"description": "语音转文字引擎","label": "转录"+ },+ "intelligence": {+ "description": "AI 模型、助手与提示词",+ "label": "智能"+ },+ "privacyData": {+ "description": "隐私、权限与数据分析",+ "label": "隐私与数据"+ },+ "system": {+ "description": "更新、存储与开发者工具",+ "label": "系统"}},"title": "设置"@@ -953,6 +906,54 @@"description": "无限转录、优先处理等更多功能。","title": "免费试用 Pro 版 7 天"},+ "pricing": {+ "title": "套餐",+ "monthly": "按月",+ "annual": "按年",+ "annualBadge": "省 17%",+ "free": {+ "name": "免费版",+ "price": "$0",+ "period": "永久",+ "trialNote": "含 7 天免费 Pro 试用",+ "features": [+ "每周 2,000 字",+ "本地 AI 模型",+ "自带 API Key",+ "词典和片段",+ "支持 100+ 种语言",+ "零数据留存"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/月",+ "annualPrice": "$80",+ "annualPeriod": "/年",+ "features": [+ "包含免费版所有功能",+ "无限使用",+ "实时转录",+ "最新音频和 AI 模型",+ "iOS/Android(即将推出)",+ "零数据留存",+ "优先支持"+ ],+ "cta": "开始使用",+ "switchToAnnual": "切换为年付"+ },+ "enterprise": {+ "name": "企业版",+ "price": "自定义",+ "features": ["云端同步", "团队功能(即将推出)", "SSO 与合规"],+ "cta": "联系我们"+ },+ "currentPlan": "当前套餐"+ },+ "signedOutPlans": {+ "button": "免费创建账户"+ },"user": "用户","wordsRemaining": "剩余 {{remaining}} 个词"},@@ -962,12 +963,12 @@"cleanupMode": "整理模式","description": "为你的 AI 助手取个名字,这样你就能在听写时直接呼唤它","dialogs": {- "updatedDescription": "你的助手已命名为\u201c{{name}}\u201d。说\u201cHey {{name}}\u201d然后说出指令即可使用。",+ "updatedDescription": "你的助手已命名为“{{name}}”。说“Hey {{name}}”然后说出指令即可使用。","updatedTitle": "助手名称已更新"},"examplesTitle": "示例","helper": "选一个简短、说起来自然的名字",- "howItWorksDescription": "当你说\u201cHey {{agentName}}\u201d并跟上指令时,AI 会从整理模式切换到指令模式。没有触发短语时,它只会整理你的听写内容。",+ "howItWorksDescription": "当你说“Hey {{agentName}}”并跟上指令时,AI 会从整理模式切换到指令模式。没有触发短语时,它只会整理你的听写内容。","howItWorksTitle": "工作原理","instructionMode": "指令","placeholder": "例如 Jarvis、Nova、Atlas...",@@ -1023,26 +1024,6 @@"resetAppData": "重置应用数据","resetAppDataDescription": "永久删除所有设置、转录记录和缓存数据"},- "dictionary": {- "add": "添加",- "addWordOrPhrase": "添加词汇或短语",- "agentNameAutoManaged": "助手名称(自动管理)",- "clearAll": "全部清除",- "clearDictionaryDescription": "这将删除自定义词典中的所有词汇,此操作无法撤销。",- "clearDictionaryTitle": "清除词典?",- "description": "添加词汇、姓名或专业术语以提高转录准确率",- "howItWorksDescription": "你添加的词汇会被包含在 AI 提示词中,以便模型在转录整理时能够识别并保留这些词汇。",- "howItWorksTitle": "工作原理",- "noWords": "尚未添加任何词汇",- "placeholder": "例如 OpenWhispr、Kubernetes、张医生...",- "pressEnterToAdd": "按回车键添加",- "removeWord": "删除词汇",- "tipDescription": "添加专有名词、专业术语或任何可能被错误转录的词汇。",- "tipLabel": "提示",- "title": "自定义词典",- "wordsAppearHere": "你添加的词汇将显示在这里",- "yourWords": "你的词汇"- },"general": {"appearance": {"auto": "自动",@@ -1062,6 +1043,7 @@"hotkey": {"activationMode": "激活模式","description": "用于开始和停止语音听写的组合键",+ "resetToDefault": "重置为 {{hotkey}}","title": "听写快捷键"},"microphone": {@@ -1245,5 +1227,284 @@"openai_oss_gpt_oss_20b_mxfp4": "OpenAI 开源模型,适用于消费级硬件"}}+ },+ "referral": {+ "modalTitle": "推荐计划",+ "title": "推荐赚取奖励",+ "subtitle": "送一个月,得一个月。",+ "tabs": {+ "refer": "推荐",+ "pastInvites": "历史邀请"+ },+ "howItWorks": {+ "shareLink": "分享你的邀请链接",+ "theySignUp": "对方注册即可获得",+ "freeMonthOfPro": "一个月免费 Pro",+ "youGet": "你将获得",+ "freeMonth": "一个月免费",+ "whenTheyDictate": "当对方听写满 2,000 个词时"+ },+ "inviteLink": {+ "title": "你的邀请链接",+ "copy": "复制",+ "copied": "已复制"+ },+ "sendInvites": {+ "title": "发送邀请",+ "placeholder": "[email protected]",+ "send": "发送",+ "sending": "发送中"+ },+ "stats": {+ "referred": "已推荐",+ "converted": "已转化",+ "monthsEarned": "已获得月数"+ },+ "status": {+ "converted": "已转化",+ "opened": "已打开",+ "failed": "失败",+ "sent": "已发送"+ },+ "empty": {+ "title": "尚未发送任何邀请",+ "description": "分享你的链接或发送邀请以开始使用"+ },+ "toasts": {+ "copiedTitle": "已复制!",+ "copiedDescription": "推荐链接已复制到剪贴板",+ "copyFailedTitle": "复制失败",+ "copyFailedDescription": "无法将链接复制到剪贴板",+ "invalidEmailTitle": "邮箱地址无效",+ "invalidEmailDescription": "请输入有效的邮箱地址",+ "inviteSentTitle": "邀请已发送!",+ "inviteSentDescription": "邀请已发送至 {{email}}",+ "sendFailedTitle": "发送失败",+ "sendFailedDescription": "邀请发送失败,请重试。"+ },+ "errors": {+ "unableToLoad": "无法加载推荐数据",+ "unableToLoadStats": "无法加载推荐统计数据,请稍后重试。"+ },+ "tryAgain": "重试",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "你的声纹签名",+ "stop": "停止",+ "playSignal": "播放信号"+ },+ "friends": {+ "title": "好友",+ "completed": "已完成",+ "sentInvites": "已发出的邀请"+ }+ },+ "notes": {+ "folders": {+ "title": "文件夹",+ "soon": "即将推出",+ "folderName": "文件夹名称",+ "couldNotCreate": "无法创建文件夹",+ "couldNotRename": "无法重命名文件夹",+ "couldNotDelete": "无法删除文件夹"+ },+ "list": {+ "title": "笔记",+ "newNote": "新建笔记",+ "untitled": "无标题",+ "untitledNote": "无标题笔记",+ "timeNow": "刚刚",+ "minutesAgo": "{{count}} 分钟前",+ "hoursAgo": "{{count}} 小时前",+ "daysAgo": "{{count}} 天前"+ },+ "editor": {+ "untitled": "无标题",+ "noteTitle": "笔记标题",+ "stop": "停止",+ "transcribe": "转录",+ "processing": "处理中...",+ "export": "导出",+ "asMarkdown": "导出为 Markdown",+ "asPlainText": "导出为纯文本",+ "raw": "原始内容",+ "enhanced": "增强内容",+ "saving": "保存中",+ "wordsCount": "{{count}} 个词",+ "startWriting": "开始书写...",+ "staleIndicator": "内容在增强后已更改"+ },+ "upload": {+ "title": "上传音频",+ "using": "使用 {{model}}",+ "dropOrBrowse": "拖放音频文件或点击浏览",+ "supportedFormats": "MP3、WAV、M4A、WebM、OGG、FLAC、AAC",+ "dropToUpload": "拖放以上传",+ "transcribe": "转录",+ "cancel": "取消",+ "transcribingCloud": "正在通过云端转录...",+ "transcribingLocal": "正在本地转录...",+ "transcribingProvider": "正在通过 {{provider}} 转录...",+ "transcriptionComplete": "转录完成",+ "openNote": "打开笔记",+ "uploadAnother": "上传另一个",+ "retry": "重试",+ "startOver": "重新开始",+ "transcriptionSettings": "转录设置",+ "newFolder": "新建文件夹",+ "folderName": "文件夹名称",+ "create": "创建",+ "setupTitle": "设置转录",+ "setupDescription": "选择转录音频的方式。此设置也适用于实时听写。",+ "continue": "继续",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "自定义",+ "selectFolder": "选择文件夹",+ "transcriptionFailed": "转录失败",+ "errorOccurred": "发生错误",+ "noProviderTitle": "尚未设置转录服务商",+ "noProviderDescription": "添加 API Key 或下载本地模型以开始转录。",+ "noProviderAction": "打开转录设置"+ },+ "meeting": {+ "title": "会议笔记",+ "description": "说话人识别与结构化摘要",+ "comingSoon": "即将推出"+ },+ "context": {+ "moveToFolder": "移动到文件夹",+ "delete": "删除",+ "rename": "重命名",+ "searchFolders": "搜索文件夹...",+ "noResults": "未找到文件夹",+ "newFolder": "新建文件夹"+ },+ "actions": {+ "manage": "管理操作...",+ "manageTitle": "自定义操作",+ "addAction": "新建操作",+ "editAction": "编辑操作",+ "namePlaceholder": "操作名称",+ "descriptionPlaceholder": "简要描述(可选)",+ "promptPlaceholder": "AI 应如何处理笔记内容?",+ "builtIn": "内置",+ "save": "保存",+ "update": "更新",+ "cancel": "取消",+ "noActions": "暂无自定义操作",+ "runAction": "运行 {{name}}",+ "selectAction": "选择操作",+ "done": "完成",+ "builtin": {+ "cleanupNotes": {+ "name": "整理笔记",+ "description": "修正语法、结构和格式"+ }+ }+ },+ "empty": {+ "title": "这里还没有笔记",+ "description": "创建你的第一条笔记,开始书写",+ "selectTitle": "选择笔记",+ "selectDescription": "从侧边栏选择一条笔记",+ "createNote": "创建笔记",+ "emptyFolder": "此文件夹中没有笔记"+ },+ "addToFolder": {+ "title": "添加笔记",+ "searchPlaceholder": "搜索要添加的笔记...",+ "addExisting": "添加已有笔记",+ "addCount": "添加 {{count}} 条笔记",+ "noResults": "没有匹配的笔记",+ "noNotesAvailable": "没有其他可用笔记",+ "today": "今天",+ "yesterday": "昨天"+ },+ "onboarding": {+ "llm": {+ "title": "配置 AI 模型",+ "description": "操作使用 AI 来处理你的笔记。设置一个语言模型以开始使用。",+ "configured": "AI 模型已配置"+ },+ "actions": {+ "title": "AI 驱动的操作",+ "description": "操作可以处理你的笔记——整理转录、总结会议等。使用内置操作或创建你自己的。",+ "builtInLabel": "内置",+ "createTitle": "创建你的操作",+ "createDescription": "使用你自己的 AI 提示词定义自定义操作。你可以随时在设置中编辑或添加更多。",+ "created": "已创建!"+ },+ "getStarted": "开始使用"+ },+ "realtimeBanner": {+ "message": "Pro 版可使用实时转录",+ "upgrade": "升级"+ }+ },+ "dictionary": {+ "addWord": "添加词语",+ "removeWord": "移除 {{word}}",+ "clearAll": "全部清除",+ "howItWorks": "工作原理",+ "howItWorksDetail": "你添加的词汇会被包含在 AI 提示词中,以便模型在转录整理时能够识别并保留这些词汇。",+ "autoManaged": "助手名称(自动管理)",+ "inputHint": "按回车键添加",+ "title": "自定义词典",+ "description": "教 AI 学习你的词汇 — 名字、行话和它可能遗漏的术语",+ "clearTitle": "清空词典?",+ "clearDescription": "这将删除自定义词典中的所有词汇,此操作无法撤销。",+ "addPlaceholder": "添加词语或短语..."+ },+ "sidebar": {+ "home": "首页",+ "notes": "笔记",+ "upload": "上传",+ "dictionary": "词典",+ "referral": "获取免费一个月",+ "settings": "设置",+ "support": "支持",+ "limitReached": "已达每周上限",+ "limitReachedDescription": "升级到 Pro 即可无限转录。",+ "upgradeToPro": "升级到 Pro",+ "upgradeTitle": "升级到 Pro",+ "upgradeDescription": "无限转录、实时转录等更多功能。",+ "learnMore": "了解更多",+ "defaultUser": "用户",+ "notSignedIn": "未登录"+ },+ "usage": {+ "approachingLimit": "即将达到周限额",+ "approachingLimitDescription": "你本周已使用 {{wordsUsed}} / {{limit}} 个免费词数。",+ "yourPlan": "你的套餐",+ "trial": "试用期(剩余 {{days}} 天)",+ "trial_other": "试用期(剩余 {{days}} 天)",+ "pro": "Pro",+ "unlimitedTrial": "试用期间无限转录",+ "unlimited": "无限转录",+ "manageSubscription": "管理订阅",+ "weeklyUsage": "每周用量",+ "limitReached": "已达上限",+ "free": "免费版",+ "wordsRemaining": "剩余 {{remaining}} 个词",+ "rollingLimit": "滚动周限额",+ "upgradeToPro": "升级到 Pro",+ "useYourOwnKey": "使用自己的 API Key",+ "upgradeUnlimited": "升级到 Pro — 无限转录"+ },+ "support": {+ "joinDiscord": "加入 Discord",+ "contactSupport": "联系支持",+ "submitBug": "提交 Bug"+ },+ "apiKeyInput": {+ "placeholder": "输入你的 API Key",+ "label": "API Key",+ "save": "保存",+ "cancelEdit": "取消编辑",+ "edit": "编辑",+ "add": "添加",+ "editButton": "编辑密钥",+ "addButton": "添加密钥"}}diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 2ad733981..1d9af3a60 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -1,36 +1,4 @@{- "app": {- "name": "OpenWhispr",- "loading": "正在載入 OpenWhispr...",- "oauth": {- "redirectTitle": "正在導向 OpenWhispr",- "closeTab": "你可以關閉此分頁"- },- "buttons": {- "cancelRecording": "取消錄音",- "cancelProcessing": "取消處理"- },- "mic": {- "hotkeyToSpeak": "[{{hotkey}}] 開始說話",- "recording": "錄音中...",- "processing": "處理中...",- "clickToSpeak": "點擊開始說話"- },- "toasts": {- "hotkeyChanged": {- "title": "快捷鍵已變更"- },- "hotkeyUnavailable": {- "title": "快捷鍵無法使用",- "description": "無法註冊快捷鍵。請在設定中選擇其他快捷鍵。"- }- },- "commandMenu": {- "startListening": "開始聆聽",- "stopListening": "停止聆聽",- "hideForNow": "暫時隱藏"- }- },"settings": {"language": {"sectionTitle": "語言",@@ -172,10 +140,10 @@"availableModels": "可用模型","fast": "快速","hold": "按住",- "less": "更少",- "more": "更多","private": "私密",- "tap": "點按"+ "tap": "點按",+ "close": "關閉",+ "dismiss": "忽略"},"onboarding": {"steps": {@@ -249,29 +217,24 @@"updatePayment": "更新付款"},"history": {- "title": "轉錄記錄","couldNotLoadTitle": "無法載入歷史記錄","couldNotLoadDescription": "載入轉錄記錄時發生錯誤。請嘗試關閉並重新開啟應用程式。","copiedTitle": "已複製!","copiedDescription": "文字已複製到剪貼簿","couldNotCopyTitle": "無法複製","couldNotCopyDescription": "複製到剪貼簿時發生錯誤。請再試一次。",- "clearTitle": "清除歷史記錄",- "clearDescription": "這將移除你的所有轉錄記錄。此操作無法復原。",- "clearedTitle": "歷史記錄已清除",- "clearedDescription": "已移除 {{count}} 筆轉錄記錄",- "clearedDescription_other": "已移除 {{count}} 筆轉錄記錄",- "couldNotClearTitle": "無法清除歷史記錄",- "couldNotClearDescription": "發生錯誤,請再試一次。","deleteTitle": "刪除轉錄記錄","deleteDescription": "這筆轉錄記錄將被永久移除。","couldNotDeleteTitle": "無法刪除","couldNotDeleteDescription": "這筆轉錄記錄可能已被移除。","couldNotDeleteDescriptionGeneric": "發生錯誤,請再試一次。",- "clear": "清除","empty": "目前沒有轉錄記錄","press": "按下",- "toStart": "開始"+ "toStart": "開始",+ "dateGroups": {+ "today": "今天",+ "yesterday": "昨天"+ }},"cloudMigration": {"title": "歡迎使用 OpenWhispr Pro",@@ -292,8 +255,6 @@"localDescription": "在你的裝置上執行。完全私密,可離線使用。","cloudDescription": "透過 API 使用進階模型。快速且強大,需要網路。"},- "enableTitle": "啟用 AI 文字增強",- "enableDescription": "使用 AI 自動提升轉錄品質","custom": {"endpointWithProtocol": "請輸入包含通訊協定的完整 URL(例如 https://server/v1)。","httpsRequired": "需使用 HTTPS(僅限本機網路可使用 HTTP)。",@@ -536,7 +497,8 @@"continueWithGoogle": "使用 Google 繼續"},"welcomeSubtitle": "隨時隨地用語音輸入文字",- "welcomeTitle": "歡迎使用 OpenWhispr"+ "welcomeTitle": "歡迎使用 OpenWhispr",+ "sessionExpired": "工作階段已過期,請重新登入。"},"cleanupPrompt": "文字整理","developerSection": {@@ -837,52 +799,43 @@},"settingsModal": {"groups": {+ "account": "帳戶","app": "應用程式",- "intelligence": "智慧功能",- "profile": "個人檔案",- "speech": "語音",+ "speechAi": "語音與 AI","system": "系統"},"sections": {"account": {- "description": "登入與用量",+ "description": "個人資料與登入","label": "帳號"},- "agentConfig": {- "description": "語音助理設定",- "label": "助理"- },- "aiModels": {- "description": "文字整理與增強",- "label": "AI 模型"- },- "developer": {- "description": "記錄、診斷與資料",- "label": "開發者"- },- "dictionary": {- "description": "自訂詞彙和片語",- "label": "字典"+ "plansBilling": {+ "description": "方案、用量與帳單",+ "label": "方案與帳單"},"general": {- "description": "外觀、快捷鍵與啟動",+ "description": "外觀、音效與啟動","label": "偏好設定"},- "permissions": {- "description": "麥克風與輔助使用",- "label": "權限"- },- "privacy": {- "description": "雲端備份與分析",- "label": "隱私權"- },- "prompts": {- "description": "系統提示詞工作室",- "label": "提示詞"+ "hotkeys": {+ "description": "聽寫快捷鍵與啟用模式",+ "label": "快捷鍵"},"transcription": {"description": "語音轉文字引擎","label": "轉錄"+ },+ "intelligence": {+ "description": "AI 模型、助理與提示詞",+ "label": "智慧功能"+ },+ "privacyData": {+ "description": "隱私、權限與資料分析",+ "label": "隱私與資料"+ },+ "system": {+ "description": "更新、儲存與開發者工具",+ "label": "系統"}},"title": "設定"@@ -953,6 +906,54 @@"description": "無限轉錄、優先處理等更多功能。","title": "免費試用 Pro 7 天"},+ "pricing": {+ "title": "方案",+ "monthly": "月付",+ "annual": "年付",+ "annualBadge": "省 17%",+ "free": {+ "name": "免費",+ "price": "$0",+ "period": "永久",+ "trialNote": "含 7 天免費 Pro 試用",+ "features": [+ "每週 2,000 字",+ "本機 AI 模型",+ "自備 API Key",+ "字典與片段",+ "支援 100+ 種語言",+ "零資料留存"+ ]+ },+ "pro": {+ "name": "Pro",+ "monthlyPrice": "$8",+ "monthlyPeriod": "/月",+ "annualPrice": "$80",+ "annualPeriod": "/年",+ "features": [+ "包含免費版所有功能",+ "無限使用",+ "即時轉錄",+ "最新音訊與 AI 模型",+ "iOS/Android(即將推出)",+ "零資料留存",+ "優先支援"+ ],+ "cta": "開始使用",+ "switchToAnnual": "切換為年付"+ },+ "enterprise": {+ "name": "企業版",+ "price": "自訂",+ "features": ["雲端同步", "團隊功能(即將推出)", "SSO 與合規"],+ "cta": "聯絡我們"+ },+ "currentPlan": "目前方案"+ },+ "signedOutPlans": {+ "button": "建立免費帳號"+ },"user": "使用者","wordsRemaining": "剩餘 {{remaining}} 字"},@@ -1023,26 +1024,6 @@"resetAppData": "重設應用程式資料","resetAppDataDescription": "永久刪除所有設定、轉錄記錄和快取資料"},- "dictionary": {- "add": "新增",- "addWordOrPhrase": "新增詞彙或片語",- "agentNameAutoManaged": "助理名稱(自動管理)",- "clearAll": "清除全部",- "clearDictionaryDescription": "這將移除自訂字典中的所有詞彙。此操作無法復原。",- "clearDictionaryTitle": "確定要清除字典?",- "description": "新增詞彙、姓名或專業術語以提高轉錄準確度",- "howItWorksDescription": "你新增的詞彙會包含在 AI 提示詞中,讓模型在轉錄整理時能辨識並保留這些詞彙。",- "howItWorksTitle": "運作方式",- "noWords": "尚未新增任何詞彙",- "placeholder": "例如 OpenWhispr、Kubernetes、Dr. Martinez...",- "pressEnterToAdd": "按 Enter 新增",- "removeWord": "移除詞彙",- "tipDescription": "新增專有名詞、專業術語,或任何可能被轉錄錯誤的詞彙。",- "tipLabel": "小提示",- "title": "自訂字典",- "wordsAppearHere": "你新增的詞彙會顯示在這裡",- "yourWords": "你的詞彙"- },"general": {"appearance": {"auto": "自動",@@ -1062,6 +1043,7 @@"hotkey": {"activationMode": "啟用模式","description": "用來開始和停止語音輸入的組合鍵",+ "resetToDefault": "重置為 {{hotkey}}","title": "語音輸入快捷鍵"},"microphone": {@@ -1245,5 +1227,284 @@"openai_oss_gpt_oss_20b_mxfp4": "OpenAI 開放權重模型,適用於消費級硬體"}}+ },+ "referral": {+ "modalTitle": "推薦計畫",+ "title": "推薦好友賺取獎勵",+ "subtitle": "送一個月,得一個月。",+ "tabs": {+ "refer": "推薦",+ "pastInvites": "過去的邀請"+ },+ "howItWorks": {+ "shareLink": "分享您的邀請連結",+ "theySignUp": "對方註冊即可獲得",+ "freeMonthOfPro": "一個月免費 Pro",+ "youGet": "您可獲得",+ "freeMonth": "一個月免費",+ "whenTheyDictate": "當對方聽寫滿 2,000 字時"+ },+ "inviteLink": {+ "title": "您的邀請連結",+ "copy": "複製",+ "copied": "已複製"+ },+ "sendInvites": {+ "title": "發送邀請",+ "placeholder": "[email protected]",+ "send": "發送",+ "sending": "發送中"+ },+ "stats": {+ "referred": "已推薦",+ "converted": "已轉換",+ "monthsEarned": "已獲得月數"+ },+ "status": {+ "converted": "已轉換",+ "opened": "已開啟",+ "failed": "失敗",+ "sent": "已發送"+ },+ "empty": {+ "title": "尚未發送任何邀請",+ "description": "分享您的連結或發送邀請以開始使用"+ },+ "toasts": {+ "copiedTitle": "已複製!",+ "copiedDescription": "推薦連結已複製到剪貼簿",+ "copyFailedTitle": "複製失敗",+ "copyFailedDescription": "無法將連結複製到剪貼簿",+ "invalidEmailTitle": "無效的電子郵件",+ "invalidEmailDescription": "請輸入有效的電子郵件地址",+ "inviteSentTitle": "邀請已發送!",+ "inviteSentDescription": "邀請已發送至 {{email}}",+ "sendFailedTitle": "發送失敗",+ "sendFailedDescription": "無法發送邀請,請重試。"+ },+ "errors": {+ "unableToLoad": "無法載入推薦資料",+ "unableToLoadStats": "無法載入推薦統計資料,請稍後再試。"+ },+ "tryAgain": "重試",+ "card": {+ "brand": "OpenWhispr",+ "signalId": "Signal ID",+ "audioSignature": "您的音訊簽名",+ "stop": "停止",+ "playSignal": "播放信號"+ },+ "friends": {+ "title": "好友",+ "completed": "已完成",+ "sentInvites": "已發送的邀請"+ }+ },+ "notes": {+ "folders": {+ "title": "資料夾",+ "soon": "即將推出",+ "folderName": "資料夾名稱",+ "couldNotCreate": "無法建立資料夾",+ "couldNotRename": "無法重新命名資料夾",+ "couldNotDelete": "無法刪除資料夾"+ },+ "list": {+ "title": "筆記",+ "newNote": "新增筆記",+ "untitled": "未命名",+ "untitledNote": "未命名筆記",+ "timeNow": "剛剛",+ "minutesAgo": "{{count}} 分鐘前",+ "hoursAgo": "{{count}} 小時前",+ "daysAgo": "{{count}} 天前"+ },+ "editor": {+ "untitled": "未命名",+ "noteTitle": "筆記標題",+ "stop": "停止",+ "transcribe": "轉錄",+ "processing": "處理中...",+ "export": "匯出",+ "asMarkdown": "匯出為 Markdown",+ "asPlainText": "匯出為純文字",+ "raw": "原始",+ "enhanced": "已增強",+ "saving": "儲存中",+ "wordsCount": "{{count}} 個字",+ "startWriting": "開始撰寫...",+ "staleIndicator": "內容在增強後已變更"+ },+ "upload": {+ "title": "上傳音訊",+ "using": "使用 {{model}}",+ "dropOrBrowse": "拖放音訊檔案或點擊瀏覽",+ "supportedFormats": "MP3、WAV、M4A、WebM、OGG、FLAC、AAC",+ "dropToUpload": "拖放以上傳",+ "transcribe": "轉錄",+ "cancel": "取消",+ "transcribingCloud": "透過雲端轉錄中...",+ "transcribingLocal": "本機轉錄中...",+ "transcribingProvider": "透過 {{provider}} 轉錄中...",+ "transcriptionComplete": "轉錄完成",+ "openNote": "開啟筆記",+ "uploadAnother": "上傳另一個",+ "retry": "重試",+ "startOver": "重新開始",+ "transcriptionSettings": "轉錄設定",+ "newFolder": "新增資料夾",+ "folderName": "資料夾名稱",+ "create": "建立",+ "setupTitle": "設定轉錄",+ "setupDescription": "選擇音訊轉錄方式。此設定同樣適用於即時聽寫。",+ "continue": "繼續",+ "openwhisprCloud": "OpenWhispr Cloud",+ "custom": "自訂",+ "selectFolder": "選擇資料夾",+ "transcriptionFailed": "轉錄失敗",+ "errorOccurred": "發生錯誤",+ "noProviderTitle": "尚未設定轉錄服務供應商",+ "noProviderDescription": "新增 API Key 或下載本機模型以開始轉錄。",+ "noProviderAction": "開啟轉錄設定"+ },+ "meeting": {+ "title": "會議筆記",+ "description": "說話者辨識與結構化摘要",+ "comingSoon": "即將推出"+ },+ "context": {+ "moveToFolder": "移動到資料夾",+ "delete": "刪除",+ "rename": "重新命名",+ "searchFolders": "搜尋資料夾...",+ "noResults": "找不到資料夾",+ "newFolder": "新增資料夾"+ },+ "actions": {+ "manage": "管理動作...",+ "manageTitle": "自訂動作",+ "addAction": "新增動作",+ "editAction": "編輯動作",+ "namePlaceholder": "動作名稱",+ "descriptionPlaceholder": "簡要描述(選填)",+ "promptPlaceholder": "AI 應如何處理筆記內容?",+ "builtIn": "內建",+ "save": "儲存",+ "update": "更新",+ "cancel": "取消",+ "noActions": "尚無自訂動作",+ "runAction": "執行 {{name}}",+ "selectAction": "選擇動作",+ "done": "完成",+ "builtin": {+ "cleanupNotes": {+ "name": "整理筆記",+ "description": "修正文法、結構和格式"+ }+ }+ },+ "empty": {+ "title": "這裡還沒有筆記",+ "description": "建立你的第一則筆記,開始書寫",+ "selectTitle": "選擇筆記",+ "selectDescription": "從側邊欄選擇一則筆記",+ "createNote": "建立筆記",+ "emptyFolder": "此資料夾中沒有筆記"+ },+ "addToFolder": {+ "title": "新增筆記",+ "searchPlaceholder": "搜尋要新增的筆記...",+ "addExisting": "新增現有筆記",+ "addCount": "新增 {{count}} 則筆記",+ "noResults": "沒有符合的筆記",+ "noNotesAvailable": "沒有其他可用的筆記",+ "today": "今天",+ "yesterday": "昨天"+ },+ "onboarding": {+ "llm": {+ "title": "設定 AI 模型",+ "description": "動作使用 AI 來處理你的筆記。設定語言模型以開始使用。",+ "configured": "AI 模型已設定"+ },+ "actions": {+ "title": "AI 驅動的動作",+ "description": "動作可以處理你的筆記——整理轉錄、摘要會議等。使用內建動作或建立你自己的。",+ "builtInLabel": "內建",+ "createTitle": "建立你的動作",+ "createDescription": "使用你自己的 AI 提示詞定義自訂動作。你隨時可以在設定中編輯或新增更多。",+ "created": "已建立!"+ },+ "getStarted": "開始使用"+ },+ "realtimeBanner": {+ "message": "Pro 方案可使用即時轉錄",+ "upgrade": "升級"+ }+ },+ "dictionary": {+ "addWord": "新增詞語",+ "removeWord": "移除 {{word}}",+ "clearAll": "全部清除",+ "howItWorks": "運作方式",+ "howItWorksDetail": "你新增的詞彙會包含在 AI 提示詞中,讓模型在轉錄整理時能辨識並保留這些詞彙。",+ "autoManaged": "助理名稱(自動管理)",+ "inputHint": "按 Enter 新增",+ "title": "自訂字典",+ "description": "教 AI 學習你的詞彙 — 名字、專業術語和它可能遺漏的表達",+ "clearTitle": "清空字典?",+ "clearDescription": "這將移除自訂字典中的所有詞彙。此操作無法復原。",+ "addPlaceholder": "新增詞語或片語..."+ },+ "sidebar": {+ "home": "首頁",+ "notes": "筆記",+ "upload": "上傳",+ "dictionary": "字典",+ "referral": "獲得一個月免費",+ "settings": "設定",+ "support": "支援",+ "limitReached": "已達每週上限",+ "limitReachedDescription": "升級至 Pro 即可無限轉錄。",+ "upgradeToPro": "升級至 Pro",+ "upgradeTitle": "升級至 Pro",+ "upgradeDescription": "無限轉錄、即時轉錄等更多功能。",+ "learnMore": "瞭解更多",+ "defaultUser": "使用者",+ "notSignedIn": "尚未登入"+ },+ "usage": {+ "approachingLimit": "即將達到每週上限",+ "approachingLimitDescription": "你本週已使用 {{wordsUsed}} / {{limit}} 個免費字數。",+ "yourPlan": "你的方案",+ "trial": "試用(剩餘 {{days}} 天)",+ "trial_other": "試用(剩餘 {{days}} 天)",+ "pro": "Pro",+ "unlimitedTrial": "試用期間無限轉錄",+ "unlimited": "無限轉錄",+ "manageSubscription": "管理訂閱",+ "weeklyUsage": "每週用量",+ "limitReached": "已達上限",+ "free": "免費",+ "wordsRemaining": "剩餘 {{remaining}} 字",+ "rollingLimit": "滾動式每週額度",+ "upgradeToPro": "升級至 Pro",+ "useYourOwnKey": "使用自己的 API Key",+ "upgradeUnlimited": "升級至 Pro — 無限轉錄"+ },+ "support": {+ "joinDiscord": "加入 Discord",+ "contactSupport": "聯絡支援",+ "submitBug": "提交 Bug"+ },+ "apiKeyInput": {+ "placeholder": "輸入你的 API Key",+ "label": "API Key",+ "save": "儲存",+ "cancelEdit": "取消編輯",+ "edit": "編輯",+ "add": "新增",+ "editButton": "編輯金鑰",+ "addButton": "新增金鑰"}}diff --git a/src/main.jsx b/src/main.jsxindex ccafb474a..83309f2f3 100644--- a/src/main.jsx+++ b/src/main.jsx@@ -3,8 +3,7 @@ import ReactDOM from "react-dom/client";import { I18nextProvider, useTranslation } from "react-i18next";import App from "./App.jsx";import AuthenticationStep from "./components/AuthenticationStep.tsx";-import TitleBar from "./components/TitleBar.tsx";-import SupportDropdown from "./components/ui/SupportDropdown.tsx";+import WindowControls from "./components/WindowControls.tsx";import { Card, CardContent } from "./components/ui/card.tsx";import ErrorBoundary from "./components/ErrorBoundary.tsx";import { ToastProvider } from "./components/ui/Toast.tsx";@@ -350,14 +349,17 @@ function AppRouter() {className="h-screen flex flex-col bg-background"style={{ paddingTop: "env(safe-area-inset-top, 0px)" }}>- <div className="shrink-0 z-10">- <TitleBar- showTitle={true}- className="bg-background backdrop-blur-xl border-b border-border shadow-sm"- actions={<SupportDropdown />}- />+ <div+ className="flex items-center justify-end w-full h-10 shrink-0"+ style={{ WebkitAppRegion: "drag" }}+ >+ {window.electronAPI?.getPlatform?.() !== "darwin" && (+ <div className="pr-1" style={{ WebkitAppRegion: "no-drag" }}>+ <WindowControls />+ </div>+ )}</div>- <div className="flex-1 px-6 md:px-12 overflow-y-auto flex items-center">+ <div className="flex-1 px-6 overflow-y-auto flex items-center"><div className="w-full max-w-sm mx-auto"><Card className="bg-card/90 backdrop-blur-2xl border border-border/50 dark:border-white/5 shadow-lg rounded-xl overflow-hidden"><CardContent className="p-6">diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.tsindex 9b955b689..967d78269 100644--- a/src/models/ModelRegistry.ts+++ b/src/models/ModelRegistry.ts@@ -1,4 +1,5 @@import modelDataRaw from "./modelRegistryData.json";+import { isCloudReasoningMode } from "../stores/settingsStore";export interface ModelDefinition {id: string;@@ -251,13 +252,8 @@ export function getReasoningModelLabel(modelId: string): string {}export function getModelProvider(modelId: string): string {- // When in OpenWhispr cloud mode, route reasoning through the cloud API- if (typeof localStorage !== "undefined") {- const cloudMode = localStorage.getItem("cloudReasoningMode");- const isSignedIn = localStorage.getItem("isSignedIn") === "true";- if (cloudMode === "openwhispr" && isSignedIn) {- return "openwhispr";- }+ if (isCloudReasoningMode()) {+ return "openwhispr";}const model = getAllReasoningModels().find((m) => m.value === modelId);diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex 02db47c2b..67c794005 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -1,34 +1,26 @@import { getSystemPrompt } from "../config/prompts";+import { getSettings } from "../stores/settingsStore";export interface ReasoningConfig {maxTokens?: number;temperature?: number;contextSize?: number;+ systemPrompt?: string;}export abstract class BaseReasoningService {protected isProcessing = false;protected getCustomDictionary(): string[] {- if (typeof window === "undefined" || !window.localStorage) return [];- try {- const raw = window.localStorage.getItem("customDictionary");- if (!raw) return [];- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }+ return getSettings().customDictionary;}protected getPreferredLanguage(): string {- if (typeof window === "undefined" || !window.localStorage) return "auto";- return window.localStorage.getItem("preferredLanguage") || "auto";+ return getSettings().preferredLanguage || "auto";}protected getUiLanguage(): string {- if (typeof window === "undefined" || !window.localStorage) return "en";- return window.localStorage.getItem("uiLanguage") || "en";+ return getSettings().uiLanguage || "en";}protected getSystemPrompt(agentName: string | null, transcript?: string): string {diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex a234d5049..da311fe5e 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -6,6 +6,7 @@ import { API_ENDPOINTS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../cimport logger from "../utils/logger";import { isSecureEndpoint } from "../utils/urlUtils";import { withSessionRefresh } from "../lib/neonAuth";+import { getSettings, isCloudReasoningMode } from "../stores/settingsStore";class ReasoningService extends BaseReasoningService {private apiKeyCache: SecureCache<string>;@@ -24,12 +25,13 @@ class ReasoningService extends BaseReasoningService {}private getConfiguredOpenAIBase(): string {- if (typeof window === "undefined" || !window.localStorage) {+ if (typeof window === "undefined") {return API_ENDPOINTS.OPENAI_BASE;}try {- const provider = window.localStorage.getItem("reasoningProvider") || "";+ const settings = getSettings();+ const provider = settings.reasoningProvider || "";const isCustomProvider = provider === "custom";if (!isCustomProvider) {@@ -42,7 +44,7 @@ class ReasoningService extends BaseReasoningService {return API_ENDPOINTS.OPENAI_BASE;}- const stored = window.localStorage.getItem("cloudReasoningBaseUrl") || "";+ const stored = settings.cloudReasoningBaseUrl || "";const trimmed = stored.trim();if (!trimmed) {@@ -187,7 +189,7 @@ class ReasoningService extends BaseReasoningService {logger.logReasoning("CUSTOM_KEY_IPC_FALLBACK", { error: (err as Error)?.message });}if (!customKey || !customKey.trim()) {- customKey = window.localStorage?.getItem("customReasoningApiKey") || "";+ customKey = getSettings().customReasoningApiKey || "";}const trimmedKey = customKey.trim();@@ -195,7 +197,6 @@ class ReasoningService extends BaseReasoningService {provider,hasKey: !!trimmedKey,keyLength: trimmedKey.length,- keyPreview: trimmedKey ? `${trimmedKey.substring(0, 8)}...` : "none",});return trimmedKey;@@ -223,7 +224,6 @@ class ReasoningService extends BaseReasoningService {provider,hasKey: !!apiKey,keyLength: apiKey?.length || 0,- keyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : "none",});if (apiKey) {@@ -259,7 +259,7 @@ class ReasoningService extends BaseReasoningService {config: ReasoningConfig,providerName: string): Promise<string> {- const systemPrompt = this.getSystemPrompt(agentName, text);+ const systemPrompt = config.systemPrompt || this.getSystemPrompt(agentName, text);const userPrompt = text;const messages = [@@ -397,11 +397,12 @@ class ReasoningService extends BaseReasoningService {agentName: string | null = null,config: ReasoningConfig = {}): Promise<string> {- const trimmedModel = model?.trim?.() || "";- if (!trimmedModel) {+ let trimmedModel = model?.trim?.() || "";+ const provider = getModelProvider(trimmedModel);++ if (!trimmedModel && provider !== "openwhispr") {throw new Error("No reasoning model selected");}- const provider = getModelProvider(trimmedModel);logger.logReasoning("PROVIDER_SELECTION", {model: trimmedModel,@@ -472,7 +473,7 @@ class ReasoningService extends BaseReasoningService {agentName: string | null = null,config: ReasoningConfig = {}): Promise<string> {- const reasoningProvider = window.localStorage?.getItem("reasoningProvider") || "";+ const reasoningProvider = getSettings().reasoningProvider || "";const isCustomProvider = reasoningProvider === "custom";logger.logReasoning("OPENAI_START", {@@ -496,7 +497,7 @@ class ReasoningService extends BaseReasoningService {this.isProcessing = true;try {- const systemPrompt = this.getSystemPrompt(agentName, text);+ const systemPrompt = config.systemPrompt || this.getSystemPrompt(agentName, text);const userPrompt = text;const messages = [@@ -712,7 +713,7 @@ class ReasoningService extends BaseReasoningService {textLength: text.length,});- const systemPrompt = this.getSystemPrompt(agentName, text);+ const systemPrompt = config.systemPrompt || this.getSystemPrompt(agentName, text);const result = await window.electronAPI.processAnthropicReasoning(text, model, agentName, {...config,systemPrompt,@@ -763,7 +764,7 @@ class ReasoningService extends BaseReasoningService {textLength: text.length,});- const systemPrompt = this.getSystemPrompt(agentName, text);+ const systemPrompt = config.systemPrompt || this.getSystemPrompt(agentName, text);const result = await window.electronAPI.processLocalReasoning(text, model, agentName, {...config,systemPrompt,@@ -820,7 +821,7 @@ class ReasoningService extends BaseReasoningService {this.isProcessing = true;try {- const systemPrompt = this.getSystemPrompt(agentName, text);+ const systemPrompt = config.systemPrompt || this.getSystemPrompt(agentName, text);const userPrompt = text;const requestBody = {@@ -1040,6 +1041,7 @@ class ReasoningService extends BaseReasoningService {agentName,customDictionary,customPrompt: this.getCustomPrompt(),+ systemPrompt: config.systemPrompt,language,locale,});@@ -1071,17 +1073,6 @@ class ReasoningService extends BaseReasoningService {}}- protected getCustomDictionary(): string[] {- try {- const raw = localStorage.getItem("customDictionary");- if (!raw) return [];- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }- }-private getCustomPrompt(): string | undefined {try {const raw = localStorage.getItem("customUnifiedPrompt");diff --git a/src/stores/actionStore.ts b/src/stores/actionStore.tsnew file mode 100644index 000000000..fd82950cb--- /dev/null+++ b/src/stores/actionStore.ts@@ -0,0 +1,94 @@+import { create } from "zustand";+import { TFunction } from "i18next";+import type { ActionItem } from "../types/electron";++interface ActionState {+ actions: ActionItem[];+}++const useActionStore = create<ActionState>()(() => ({+ actions: [],+}));++let hasBoundIpcListeners = false;++function ensureIpcListeners() {+ if (hasBoundIpcListeners || typeof window === "undefined") return;++ const disposers: Array<() => void> = [];++ if (window.electronAPI?.onActionCreated) {+ const dispose = window.electronAPI.onActionCreated((action) => {+ if (action) addActionToStore(action);+ });+ if (typeof dispose === "function") disposers.push(dispose);+ }++ if (window.electronAPI?.onActionUpdated) {+ const dispose = window.electronAPI.onActionUpdated((action) => {+ if (action) updateActionInStore(action);+ });+ if (typeof dispose === "function") disposers.push(dispose);+ }++ if (window.electronAPI?.onActionDeleted) {+ const dispose = window.electronAPI.onActionDeleted(({ id }) => {+ removeActionFromStore(id);+ });+ if (typeof dispose === "function") disposers.push(dispose);+ }++ hasBoundIpcListeners = true;+ window.addEventListener("beforeunload", () => {+ disposers.forEach((dispose) => dispose());+ });+}++export async function initializeActions(): Promise<ActionItem[]> {+ ensureIpcListeners();+ const items = (await window.electronAPI?.getActions()) ?? [];+ useActionStore.setState({ actions: items });+ return items;+}++function addActionToStore(action: ActionItem): void {+ const { actions } = useActionStore.getState();+ const withoutDuplicate = actions.filter((a) => a.id !== action.id);+ useActionStore.setState({+ actions: [...withoutDuplicate, action].sort((a, b) => a.sort_order - b.sort_order),+ });+}++function updateActionInStore(action: ActionItem): void {+ const { actions } = useActionStore.getState();+ useActionStore.setState({ actions: actions.map((a) => (a.id === action.id ? action : a)) });+}++function removeActionFromStore(id: number): void {+ const { actions } = useActionStore.getState();+ const next = actions.filter((a) => a.id !== id);+ if (next.length === actions.length) return;+ useActionStore.setState({ actions: next });+}++export function useActions(): ActionItem[] {+ return useActionStore((state) => state.actions);+}++export function getActionName(+ action: { name: string; translation_key?: string },+ t: TFunction+): string {+ return action.translation_key+ ? t(`${action.translation_key}.name`, { defaultValue: action.name })+ : action.name;+}++export function getActionDescription(+ action: { description: string; translation_key?: string },+ t: TFunction+): string {+ return action.translation_key+ ? t(`${action.translation_key}.description`, { defaultValue: action.description })+ : action.description;+}diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsnew file mode 100644index 000000000..773748d83--- /dev/null+++ b/src/stores/noteStore.ts@@ -0,0 +1,129 @@+import { create } from "zustand";+import type { NoteItem } from "../types/electron";++interface NoteState {+ notes: NoteItem[];+ activeNoteId: number | null;+ activeFolderId: number | null;+}++const useNoteStore = create<NoteState>()(() => ({+ notes: [],+ activeNoteId: null,+ activeFolderId: null,+}));++let hasBoundIpcListeners = false;+const DEFAULT_LIMIT = 50;+let currentLimit = DEFAULT_LIMIT;++function ensureIpcListeners() {+ if (hasBoundIpcListeners || typeof window === "undefined") {+ return;+ }++ const disposers: Array<() => void> = [];++ if (window.electronAPI?.onNoteAdded) {+ const dispose = window.electronAPI.onNoteAdded((note) => {+ if (note) {+ addNote(note);+ }+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ if (window.electronAPI?.onNoteUpdated) {+ const dispose = window.electronAPI.onNoteUpdated((note) => {+ if (note) {+ updateNoteInStore(note);+ }+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ if (window.electronAPI?.onNoteDeleted) {+ const dispose = window.electronAPI.onNoteDeleted(({ id }) => {+ removeNote(id);+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ hasBoundIpcListeners = true;++ window.addEventListener("beforeunload", () => {+ disposers.forEach((dispose) => dispose());+ });+}++export async function initializeNotes(+ noteType?: string | null,+ limit = DEFAULT_LIMIT,+ folderId?: number | null+): Promise<NoteItem[]> {+ currentLimit = limit;+ ensureIpcListeners();+ const items = (await window.electronAPI?.getNotes(noteType, limit, folderId)) ?? [];+ useNoteStore.setState({ notes: items });+ return items;+}++export function addNote(note: NoteItem): void {+ if (!note) return;+ const { notes, activeFolderId } = useNoteStore.getState();+ if (activeFolderId && note.folder_id !== activeFolderId) return;+ const withoutDuplicate = notes.filter((existing) => existing.id !== note.id);+ useNoteStore.setState({ notes: [note, ...withoutDuplicate].slice(0, currentLimit) });+}++export function updateNoteInStore(note: NoteItem): void {+ if (!note) return;+ const { notes } = useNoteStore.getState();+ useNoteStore.setState({+ notes: notes.map((existing) => (existing.id === note.id ? note : existing)),+ });+}++export function removeNote(id: number): void {+ if (id == null) return;+ const { notes } = useNoteStore.getState();+ const next = notes.filter((item) => item.id !== id);+ if (next.length === notes.length) return;+ useNoteStore.setState({ notes: next });+}++export function setActiveNoteId(id: number | null): void {+ if (useNoteStore.getState().activeNoteId === id) return;+ useNoteStore.setState({ activeNoteId: id });+}++export function setActiveFolderId(id: number | null): void {+ if (useNoteStore.getState().activeFolderId === id) return;+ useNoteStore.setState({ activeFolderId: id });+}++export function getActiveNoteIdValue(): number | null {+ return useNoteStore.getState().activeNoteId;+}++export function getActiveFolderIdValue(): number | null {+ return useNoteStore.getState().activeFolderId;+}++export function useNotes(): NoteItem[] {+ return useNoteStore((state) => state.notes);+}++export function useActiveNoteId(): number | null {+ return useNoteStore((state) => state.activeNoteId);+}++export function useActiveFolderId(): number | null {+ return useNoteStore((state) => state.activeFolderId);+}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsnew file mode 100644index 000000000..1a2d79eb7--- /dev/null+++ b/src/stores/settingsStore.ts@@ -0,0 +1,602 @@+import { create } from "zustand";+import { API_ENDPOINTS } from "../config/constants";+import i18n, { normalizeUiLanguage } from "../i18n";+import { hasStoredByokKey } from "../utils/byokDetection";+import { ensureAgentNameInDictionary } from "../utils/agentName";+import logger from "../utils/logger";+import type { LocalTranscriptionProvider } from "../types/electron";+import type {+ TranscriptionSettings,+ ReasoningSettings,+ HotkeySettings,+ MicrophoneSettings,+ ApiKeySettings,+ PrivacySettings,+ ThemeSettings,+} from "../hooks/useSettings";++let _ReasoningService: typeof import("../services/ReasoningService").default | null = null;+function getReasoningService() {+ if (!_ReasoningService) {+ _ReasoningService = require("../services/ReasoningService").default;+ }+ return _ReasoningService!;+}++const isBrowser = typeof window !== "undefined";++function readString(key: string, fallback: string): string {+ if (!isBrowser) return fallback;+ return localStorage.getItem(key) ?? fallback;+}++function readBoolean(key: string, fallback: boolean): boolean {+ if (!isBrowser) return fallback;+ const stored = localStorage.getItem(key);+ if (stored === null) return fallback;+ if (fallback === true) return stored !== "false";+ return stored === "true";+}++function readStringArray(key: string, fallback: string[]): string[] {+ if (!isBrowser) return fallback;+ const stored = localStorage.getItem(key);+ if (stored === null) return fallback;+ try {+ const parsed = JSON.parse(stored);+ return Array.isArray(parsed) ? parsed : fallback;+ } catch {+ return fallback;+ }+}++const BOOLEAN_SETTINGS = new Set([+ "useLocalWhisper",+ "allowOpenAIFallback",+ "allowLocalFallback",+ "assemblyAiStreaming",+ "useReasoningModel",+ "preferBuiltInMic",+ "cloudBackupEnabled",+ "telemetryEnabled",+ "audioCuesEnabled",+ "floatingIconAutoHide",+ "isSignedIn",+]);++const ARRAY_SETTINGS = new Set(["customDictionary"]);++const LANGUAGE_MIGRATIONS: Record<string, string> = { zh: "zh-CN" };++function migratePreferredLanguage() {+ if (!isBrowser) return;+ const stored = localStorage.getItem("preferredLanguage");+ if (stored && LANGUAGE_MIGRATIONS[stored]) {+ localStorage.setItem("preferredLanguage", LANGUAGE_MIGRATIONS[stored]);+ }+}++migratePreferredLanguage();++export interface SettingsState+ extends+ TranscriptionSettings,+ ReasoningSettings,+ HotkeySettings,+ MicrophoneSettings,+ ApiKeySettings,+ PrivacySettings,+ ThemeSettings {+ isSignedIn: boolean;+ audioCuesEnabled: boolean;+ floatingIconAutoHide: boolean;++ setUseLocalWhisper: (value: boolean) => void;+ setWhisperModel: (value: string) => void;+ setLocalTranscriptionProvider: (value: LocalTranscriptionProvider) => void;+ setParakeetModel: (value: string) => void;+ setAllowOpenAIFallback: (value: boolean) => void;+ setAllowLocalFallback: (value: boolean) => void;+ setFallbackWhisperModel: (value: string) => void;+ setPreferredLanguage: (value: string) => void;+ setCloudTranscriptionProvider: (value: string) => void;+ setCloudTranscriptionModel: (value: string) => void;+ setCloudTranscriptionBaseUrl: (value: string) => void;+ setCloudTranscriptionMode: (value: string) => void;+ setCloudReasoningMode: (value: string) => void;+ setCloudReasoningBaseUrl: (value: string) => void;+ setCustomDictionary: (words: string[]) => void;+ setAssemblyAiStreaming: (value: boolean) => void;+ setUseReasoningModel: (value: boolean) => void;+ setReasoningModel: (value: string) => void;+ setReasoningProvider: (value: string) => void;+ setUiLanguage: (language: string) => void;++ setOpenaiApiKey: (key: string) => void;+ setAnthropicApiKey: (key: string) => void;+ setGeminiApiKey: (key: string) => void;+ setGroqApiKey: (key: string) => void;+ setMistralApiKey: (key: string) => void;+ setCustomTranscriptionApiKey: (key: string) => void;+ setCustomReasoningApiKey: (key: string) => void;++ setDictationKey: (key: string) => void;+ setActivationMode: (mode: "tap" | "push") => void;++ setPreferBuiltInMic: (value: boolean) => void;+ setSelectedMicDeviceId: (value: string) => void;++ setTheme: (value: "light" | "dark" | "auto") => void;+ setCloudBackupEnabled: (value: boolean) => void;+ setTelemetryEnabled: (value: boolean) => void;+ setAudioCuesEnabled: (value: boolean) => void;+ setFloatingIconAutoHide: (enabled: boolean) => void;+ setIsSignedIn: (value: boolean) => void;++ updateTranscriptionSettings: (settings: Partial<TranscriptionSettings>) => void;+ updateReasoningSettings: (settings: Partial<ReasoningSettings>) => void;+ updateApiKeys: (keys: Partial<ApiKeySettings>) => void;+}++function createStringSetter(key: string) {+ return (value: string) => {+ if (isBrowser) localStorage.setItem(key, value);+ useSettingsStore.setState({ [key]: value });+ };+}++function createBooleanSetter(key: string) {+ return (value: boolean) => {+ if (isBrowser) localStorage.setItem(key, String(value));+ useSettingsStore.setState({ [key]: value });+ };+}++let envPersistTimer: ReturnType<typeof setTimeout> | null = null;+function debouncedPersistToEnv() {+ if (!isBrowser) return;+ if (envPersistTimer) clearTimeout(envPersistTimer);+ envPersistTimer = setTimeout(() => {+ window.electronAPI?.saveAllKeysToEnv?.().catch((err) => {+ logger.warn(+ "Failed to persist API keys to .env",+ { error: (err as Error).message },+ "settings"+ );+ });+ }, 1000);+}++function invalidateApiKeyCaches(+ provider?: "openai" | "anthropic" | "gemini" | "groq" | "mistral" | "custom"+) {+ if (provider) {+ getReasoningService().clearApiKeyCache(provider);+ }+ if (isBrowser) window.dispatchEvent(new Event("api-key-changed"));+ debouncedPersistToEnv();+}++export const useSettingsStore = create<SettingsState>()((set) => ({+ uiLanguage: normalizeUiLanguage(isBrowser ? localStorage.getItem("uiLanguage") : null),+ useLocalWhisper: readBoolean("useLocalWhisper", false),+ whisperModel: readString("whisperModel", "base"),+ localTranscriptionProvider: (readString("localTranscriptionProvider", "whisper") === "nvidia"+ ? "nvidia"+ : "whisper") as LocalTranscriptionProvider,+ parakeetModel: readString("parakeetModel", ""),+ allowOpenAIFallback: readBoolean("allowOpenAIFallback", false),+ allowLocalFallback: readBoolean("allowLocalFallback", false),+ fallbackWhisperModel: readString("fallbackWhisperModel", "base"),+ preferredLanguage: readString("preferredLanguage", "auto"),+ cloudTranscriptionProvider: readString("cloudTranscriptionProvider", "openai"),+ cloudTranscriptionModel: readString("cloudTranscriptionModel", "gpt-4o-mini-transcribe"),+ cloudTranscriptionBaseUrl: readString(+ "cloudTranscriptionBaseUrl",+ API_ENDPOINTS.TRANSCRIPTION_BASE+ ),+ cloudTranscriptionMode: readString(+ "cloudTranscriptionMode",+ hasStoredByokKey() ? "byok" : "openwhispr"+ ),+ cloudReasoningMode: readString("cloudReasoningMode", "openwhispr"),+ cloudReasoningBaseUrl: readString("cloudReasoningBaseUrl", API_ENDPOINTS.OPENAI_BASE),+ customDictionary: readStringArray("customDictionary", []),+ assemblyAiStreaming: readBoolean("assemblyAiStreaming", true),++ useReasoningModel: readBoolean("useReasoningModel", true),+ reasoningModel: readString("reasoningModel", ""),+ reasoningProvider: readString("reasoningProvider", "openai"),++ openaiApiKey: readString("openaiApiKey", ""),+ anthropicApiKey: readString("anthropicApiKey", ""),+ geminiApiKey: readString("geminiApiKey", ""),+ groqApiKey: readString("groqApiKey", ""),+ mistralApiKey: readString("mistralApiKey", ""),+ customTranscriptionApiKey: readString("customTranscriptionApiKey", ""),+ customReasoningApiKey: readString("customReasoningApiKey", ""),++ dictationKey: readString("dictationKey", ""),+ activationMode: (readString("activationMode", "tap") === "push" ? "push" : "tap") as+ | "tap"+ | "push",++ preferBuiltInMic: readBoolean("preferBuiltInMic", true),+ selectedMicDeviceId: readString("selectedMicDeviceId", ""),++ theme: (() => {+ const v = readString("theme", "auto");+ if (v === "light" || v === "dark" || v === "auto") return v;+ return "auto" as const;+ })(),+ cloudBackupEnabled: readBoolean("cloudBackupEnabled", false),+ telemetryEnabled: readBoolean("telemetryEnabled", false),+ audioCuesEnabled: readBoolean("audioCuesEnabled", true),+ floatingIconAutoHide: readBoolean("floatingIconAutoHide", false),+ isSignedIn: readBoolean("isSignedIn", false),++ setUseLocalWhisper: createBooleanSetter("useLocalWhisper"),+ setWhisperModel: createStringSetter("whisperModel"),+ setLocalTranscriptionProvider: (value: LocalTranscriptionProvider) => {+ if (isBrowser) localStorage.setItem("localTranscriptionProvider", value);+ set({ localTranscriptionProvider: value });+ },+ setParakeetModel: createStringSetter("parakeetModel"),+ setAllowOpenAIFallback: createBooleanSetter("allowOpenAIFallback"),+ setAllowLocalFallback: createBooleanSetter("allowLocalFallback"),+ setFallbackWhisperModel: createStringSetter("fallbackWhisperModel"),+ setPreferredLanguage: createStringSetter("preferredLanguage"),+ setCloudTranscriptionProvider: createStringSetter("cloudTranscriptionProvider"),+ setCloudTranscriptionModel: createStringSetter("cloudTranscriptionModel"),+ setCloudTranscriptionBaseUrl: createStringSetter("cloudTranscriptionBaseUrl"),+ setCloudTranscriptionMode: createStringSetter("cloudTranscriptionMode"),+ setCloudReasoningMode: createStringSetter("cloudReasoningMode"),+ setCloudReasoningBaseUrl: createStringSetter("cloudReasoningBaseUrl"),+ setAssemblyAiStreaming: createBooleanSetter("assemblyAiStreaming"),+ setUseReasoningModel: createBooleanSetter("useReasoningModel"),+ setReasoningModel: createStringSetter("reasoningModel"),+ setReasoningProvider: createStringSetter("reasoningProvider"),++ setCustomDictionary: (words: string[]) => {+ if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(words));+ set({ customDictionary: words });+ window.electronAPI?.setDictionary(words).catch((err) => {+ logger.warn(+ "Failed to sync dictionary to SQLite",+ { error: (err as Error).message },+ "settings"+ );+ });+ },++ setUiLanguage: (language: string) => {+ const normalized = normalizeUiLanguage(language);+ if (isBrowser) localStorage.setItem("uiLanguage", normalized);+ set({ uiLanguage: normalized });+ void i18n.changeLanguage(normalized);+ if (isBrowser && window.electronAPI?.setUiLanguage) {+ window.electronAPI.setUiLanguage(normalized).catch((err) => {+ logger.warn(+ "Failed to sync UI language to main process",+ { error: (err as Error).message },+ "settings"+ );+ });+ }+ },++ setOpenaiApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("openaiApiKey", key);+ set({ openaiApiKey: key });+ window.electronAPI?.saveOpenAIKey?.(key);+ invalidateApiKeyCaches("openai");+ },+ setAnthropicApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("anthropicApiKey", key);+ set({ anthropicApiKey: key });+ window.electronAPI?.saveAnthropicKey?.(key);+ invalidateApiKeyCaches("anthropic");+ },+ setGeminiApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("geminiApiKey", key);+ set({ geminiApiKey: key });+ window.electronAPI?.saveGeminiKey?.(key);+ invalidateApiKeyCaches("gemini");+ },+ setGroqApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("groqApiKey", key);+ set({ groqApiKey: key });+ window.electronAPI?.saveGroqKey?.(key);+ invalidateApiKeyCaches("groq");+ },+ setMistralApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("mistralApiKey", key);+ set({ mistralApiKey: key });+ window.electronAPI?.saveMistralKey?.(key);+ invalidateApiKeyCaches("mistral");+ },+ setCustomTranscriptionApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("customTranscriptionApiKey", key);+ set({ customTranscriptionApiKey: key });+ window.electronAPI?.saveCustomTranscriptionKey?.(key);+ invalidateApiKeyCaches();+ },+ setCustomReasoningApiKey: (key: string) => {+ if (isBrowser) localStorage.setItem("customReasoningApiKey", key);+ set({ customReasoningApiKey: key });+ window.electronAPI?.saveCustomReasoningKey?.(key);+ invalidateApiKeyCaches("custom");+ },++ setDictationKey: (key: string) => {+ if (isBrowser) localStorage.setItem("dictationKey", key);+ set({ dictationKey: key });+ if (isBrowser) {+ window.electronAPI?.notifyHotkeyChanged?.(key);+ window.electronAPI?.saveDictationKey?.(key);+ }+ },++ setActivationMode: (mode: "tap" | "push") => {+ if (isBrowser) localStorage.setItem("activationMode", mode);+ set({ activationMode: mode });+ if (isBrowser) {+ window.electronAPI?.notifyActivationModeChanged?.(mode);+ }+ },++ setPreferBuiltInMic: createBooleanSetter("preferBuiltInMic"),+ setSelectedMicDeviceId: createStringSetter("selectedMicDeviceId"),++ setTheme: (value: "light" | "dark" | "auto") => {+ if (isBrowser) localStorage.setItem("theme", value);+ set({ theme: value });+ },++ setCloudBackupEnabled: createBooleanSetter("cloudBackupEnabled"),+ setTelemetryEnabled: createBooleanSetter("telemetryEnabled"),+ setAudioCuesEnabled: createBooleanSetter("audioCuesEnabled"),++ setFloatingIconAutoHide: (enabled: boolean) => {+ if (isBrowser) localStorage.setItem("floatingIconAutoHide", String(enabled));+ set({ floatingIconAutoHide: enabled });+ if (isBrowser) {+ window.electronAPI?.notifyFloatingIconAutoHideChanged?.(enabled);+ }+ },++ setIsSignedIn: (value: boolean) => {+ if (isBrowser) localStorage.setItem("isSignedIn", String(value));+ set({ isSignedIn: value });+ },++ updateTranscriptionSettings: (settings: Partial<TranscriptionSettings>) => {+ const s = useSettingsStore.getState();+ if (settings.useLocalWhisper !== undefined) s.setUseLocalWhisper(settings.useLocalWhisper);+ if (settings.uiLanguage !== undefined) s.setUiLanguage(settings.uiLanguage);+ if (settings.whisperModel !== undefined) s.setWhisperModel(settings.whisperModel);+ if (settings.localTranscriptionProvider !== undefined)+ s.setLocalTranscriptionProvider(settings.localTranscriptionProvider);+ if (settings.parakeetModel !== undefined) s.setParakeetModel(settings.parakeetModel);+ if (settings.allowOpenAIFallback !== undefined)+ s.setAllowOpenAIFallback(settings.allowOpenAIFallback);+ if (settings.allowLocalFallback !== undefined)+ s.setAllowLocalFallback(settings.allowLocalFallback);+ if (settings.fallbackWhisperModel !== undefined)+ s.setFallbackWhisperModel(settings.fallbackWhisperModel);+ if (settings.preferredLanguage !== undefined)+ s.setPreferredLanguage(settings.preferredLanguage);+ if (settings.cloudTranscriptionProvider !== undefined)+ s.setCloudTranscriptionProvider(settings.cloudTranscriptionProvider);+ if (settings.cloudTranscriptionModel !== undefined)+ s.setCloudTranscriptionModel(settings.cloudTranscriptionModel);+ if (settings.cloudTranscriptionBaseUrl !== undefined)+ s.setCloudTranscriptionBaseUrl(settings.cloudTranscriptionBaseUrl);+ if (settings.cloudTranscriptionMode !== undefined)+ s.setCloudTranscriptionMode(settings.cloudTranscriptionMode);+ if (settings.customDictionary !== undefined) s.setCustomDictionary(settings.customDictionary);+ if (settings.assemblyAiStreaming !== undefined)+ s.setAssemblyAiStreaming(settings.assemblyAiStreaming);+ },++ updateReasoningSettings: (settings: Partial<ReasoningSettings>) => {+ const s = useSettingsStore.getState();+ if (settings.useReasoningModel !== undefined)+ s.setUseReasoningModel(settings.useReasoningModel);+ if (settings.reasoningModel !== undefined) s.setReasoningModel(settings.reasoningModel);+ if (settings.reasoningProvider !== undefined)+ s.setReasoningProvider(settings.reasoningProvider);+ if (settings.cloudReasoningBaseUrl !== undefined)+ s.setCloudReasoningBaseUrl(settings.cloudReasoningBaseUrl);+ if (settings.cloudReasoningMode !== undefined)+ s.setCloudReasoningMode(settings.cloudReasoningMode);+ },++ updateApiKeys: (keys: Partial<ApiKeySettings>) => {+ const s = useSettingsStore.getState();+ if (keys.openaiApiKey !== undefined) s.setOpenaiApiKey(keys.openaiApiKey);+ if (keys.anthropicApiKey !== undefined) s.setAnthropicApiKey(keys.anthropicApiKey);+ if (keys.geminiApiKey !== undefined) s.setGeminiApiKey(keys.geminiApiKey);+ if (keys.groqApiKey !== undefined) s.setGroqApiKey(keys.groqApiKey);+ if (keys.mistralApiKey !== undefined) s.setMistralApiKey(keys.mistralApiKey);+ if (keys.customTranscriptionApiKey !== undefined)+ s.setCustomTranscriptionApiKey(keys.customTranscriptionApiKey);+ if (keys.customReasoningApiKey !== undefined)+ s.setCustomReasoningApiKey(keys.customReasoningApiKey);+ },+}));++// --- Selectors (derived state, not stored) ---++export const selectIsCloudReasoningMode = (state: SettingsState) =>+ state.isSignedIn && state.cloudReasoningMode === "openwhispr";++export const selectEffectiveReasoningModel = (state: SettingsState) => state.reasoningModel;++export const selectEffectiveReasoningProvider = (state: SettingsState) =>+ selectIsCloudReasoningMode(state) ? "openwhispr" : state.reasoningProvider;++// --- Convenience getters for non-React code ---++export function getSettings() {+ return useSettingsStore.getState();+}++export function getEffectiveReasoningModel() {+ return selectEffectiveReasoningModel(useSettingsStore.getState());+}++export function isCloudReasoningMode() {+ return selectIsCloudReasoningMode(useSettingsStore.getState());+}++// --- Initialization ---++let hasInitialized = false;++export async function initializeSettings(): Promise<void> {+ if (hasInitialized) return;+ hasInitialized = true;++ if (!isBrowser) return;++ const state = useSettingsStore.getState();++ // Sync API keys from main process (if localStorage is empty, read from .env via IPC)+ if (window.electronAPI) {+ try {+ if (!state.openaiApiKey) {+ const envKey = await window.electronAPI.getOpenAIKey?.();+ if (envKey) createStringSetter("openaiApiKey")(envKey);+ }+ if (!state.anthropicApiKey) {+ const envKey = await window.electronAPI.getAnthropicKey?.();+ if (envKey) createStringSetter("anthropicApiKey")(envKey);+ }+ if (!state.geminiApiKey) {+ const envKey = await window.electronAPI.getGeminiKey?.();+ if (envKey) createStringSetter("geminiApiKey")(envKey);+ }+ if (!state.groqApiKey) {+ const envKey = await window.electronAPI.getGroqKey?.();+ if (envKey) createStringSetter("groqApiKey")(envKey);+ }+ if (!state.mistralApiKey) {+ const envKey = await window.electronAPI.getMistralKey?.();+ if (envKey) createStringSetter("mistralApiKey")(envKey);+ }+ if (!state.customTranscriptionApiKey) {+ const envKey = await window.electronAPI.getCustomTranscriptionKey?.();+ if (envKey) createStringSetter("customTranscriptionApiKey")(envKey);+ }+ if (!state.customReasoningApiKey) {+ const envKey = await window.electronAPI.getCustomReasoningKey?.();+ if (envKey) createStringSetter("customReasoningApiKey")(envKey);+ }+ } catch (err) {+ logger.warn(+ "Failed to sync API keys on startup",+ { error: (err as Error).message },+ "settings"+ );+ }++ // Sync dictation key from main process+ try {+ const envKey = await window.electronAPI.getDictationKey?.();+ if (envKey && envKey !== state.dictationKey) {+ createStringSetter("dictationKey")(envKey);+ }+ } catch {+ // ignore+ }++ // Sync activation mode from main process+ try {+ const envMode = await window.electronAPI.getActivationMode?.();+ if (envMode && envMode !== state.activationMode) {+ if (isBrowser) localStorage.setItem("activationMode", envMode);+ useSettingsStore.setState({ activationMode: envMode });+ }+ } catch {+ // ignore+ }++ // Sync UI language from main process+ try {+ const envLanguage = await window.electronAPI.getUiLanguage?.();+ const resolved = normalizeUiLanguage(envLanguage || state.uiLanguage);+ if (resolved !== state.uiLanguage) {+ if (isBrowser) localStorage.setItem("uiLanguage", resolved);+ useSettingsStore.setState({ uiLanguage: resolved });+ }+ await i18n.changeLanguage(resolved);+ } catch (err) {+ logger.warn(+ "Failed to sync UI language on startup",+ { error: (err as Error).message },+ "settings"+ );+ void i18n.changeLanguage(normalizeUiLanguage(state.uiLanguage));+ }++ // Migrate preferred language+ migratePreferredLanguage();+ const migratedLang = isBrowser ? localStorage.getItem("preferredLanguage") : null;+ if (migratedLang && migratedLang !== state.preferredLanguage) {+ useSettingsStore.setState({ preferredLanguage: migratedLang });+ }++ // Sync dictionary from SQLite <-> localStorage+ try {+ if (window.electronAPI.getDictionary) {+ const currentDictionary = useSettingsStore.getState().customDictionary;+ const dbWords = await window.electronAPI.getDictionary();+ if (dbWords.length === 0 && currentDictionary.length > 0) {+ await window.electronAPI.setDictionary(currentDictionary);+ } else if (dbWords.length > 0 && currentDictionary.length === 0) {+ if (isBrowser) localStorage.setItem("customDictionary", JSON.stringify(dbWords));+ useSettingsStore.setState({ customDictionary: dbWords });+ }+ }+ } catch (err) {+ logger.warn(+ "Failed to sync dictionary on startup",+ { error: (err as Error).message },+ "settings"+ );+ }++ ensureAgentNameInDictionary();+ }++ // Sync Zustand store when another window writes to localStorage+ window.addEventListener("storage", (event) => {+ if (!event.key || event.storageArea !== localStorage || event.newValue === null) return;++ const { key, newValue } = event;+ const state = useSettingsStore.getState();+ if (!(key in state) || typeof (state as unknown as Record<string, unknown>)[key] === "function")+ return;++ let value: unknown;+ if (BOOLEAN_SETTINGS.has(key)) {+ value = newValue === "true";+ } else if (ARRAY_SETTINGS.has(key)) {+ try {+ const parsed = JSON.parse(newValue);+ value = Array.isArray(parsed) ? parsed : [];+ } catch {+ value = [];+ }+ } else {+ value = newValue;+ }++ useSettingsStore.setState({ [key]: value });++ if (key === "uiLanguage" && typeof value === "string") {+ void i18n.changeLanguage(value);+ }+ });+}diff --git a/src/stores/transcriptionStore.ts b/src/stores/transcriptionStore.tsindex c7d6b262a..5412afb33 100644--- a/src/stores/transcriptionStore.ts+++ b/src/stores/transcriptionStore.ts@@ -1,25 +1,18 @@-import { useSyncExternalStore } from "react";+import { create } from "zustand";import type { TranscriptionItem } from "../types/electron";-type Listener = () => void;+interface TranscriptionState {+ transcriptions: TranscriptionItem[];+}++const useTranscriptionStore = create<TranscriptionState>()(() => ({+ transcriptions: [],+}));-const listeners = new Set<Listener>();-let transcriptions: TranscriptionItem[] = [];let hasBoundIpcListeners = false;const DEFAULT_LIMIT = 50;let currentLimit = DEFAULT_LIMIT;-const emit = () => {- listeners.forEach((listener) => listener());-};--const subscribe = (listener: Listener) => {- listeners.add(listener);- return () => listeners.delete(listener);-};--const getSnapshot = () => transcriptions;-function ensureIpcListeners() {if (hasBoundIpcListeners || typeof window === "undefined") {return;@@ -67,32 +60,32 @@ export async function initializeTranscriptions(limit = DEFAULT_LIMIT) {currentLimit = limit;ensureIpcListeners();const items = await window.electronAPI.getTranscriptions(limit);- transcriptions = items;- emit();+ useTranscriptionStore.setState({ transcriptions: items });return items;}export function addTranscription(item: TranscriptionItem) {if (!item) return;+ const { transcriptions } = useTranscriptionStore.getState();const withoutDuplicate = transcriptions.filter((existing) => existing.id !== item.id);- transcriptions = [item, ...withoutDuplicate].slice(0, currentLimit);- emit();+ useTranscriptionStore.setState({+ transcriptions: [item, ...withoutDuplicate].slice(0, currentLimit),+ });}export function removeTranscription(id: number) {- if (!id) return;+ if (id == null) return;+ const { transcriptions } = useTranscriptionStore.getState();const next = transcriptions.filter((item) => item.id !== id);if (next.length === transcriptions.length) return;- transcriptions = next;- emit();+ useTranscriptionStore.setState({ transcriptions: next });}export function clearTranscriptions() {- if (transcriptions.length === 0) return;- transcriptions = [];- emit();+ if (useTranscriptionStore.getState().transcriptions.length === 0) return;+ useTranscriptionStore.setState({ transcriptions: [] });}export function useTranscriptions() {- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+ return useTranscriptionStore((state) => state.transcriptions);}diff --git a/src/types/electron.ts b/src/types/electron.tsindex f6572dfa1..3c052d921 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -7,6 +7,42 @@ export interface TranscriptionItem {created_at: string;}+export interface NoteItem {+ id: number;+ title: string;+ content: string;+ enhanced_content: string | null;+ enhancement_prompt: string | null;+ enhanced_at_content_hash: string | null;+ note_type: "personal" | "meeting" | "upload";+ source_file: string | null;+ audio_duration_seconds: number | null;+ folder_id: number | null;+ created_at: string;+ updated_at: string;+}++export interface FolderItem {+ id: number;+ name: string;+ is_default: number;+ sort_order: number;+ created_at: string;+}++export interface ActionItem {+ id: number;+ name: string;+ description: string;+ prompt: string;+ icon: string;+ is_builtin: number;+ sort_order: number;+ translation_key: string | null;+ created_at: string;+ updated_at: string;+}+export interface WhisperCheckResult {installed: boolean;working: boolean;@@ -169,6 +205,15 @@ export interface PasteToolsResult {recommendedInstall?: string;}+export interface ReferralItem {+ id: string;+ email: string;+ name: string | null;+ status: "pending" | "completed" | "rewarded";+ created_at: string;+ first_payment_at: string | null;+}+declare global {interface Window {electronAPI: {@@ -190,6 +235,92 @@ declare global {getDictionary: () => Promise<string[]>;setDictionary: (words: string[]) => Promise<{ success: boolean }>;+ // Note operations+ saveNote: (+ title: string,+ content: string,+ noteType?: string,+ sourceFile?: string | null,+ audioDuration?: number | null,+ folderId?: number | null+ ) => Promise<{ success: boolean; note?: NoteItem }>;+ getNote: (id: number) => Promise<NoteItem | null>;+ getNotes: (+ noteType?: string | null,+ limit?: number,+ folderId?: number | null+ ) => Promise<NoteItem[]>;+ updateNote: (+ id: number,+ updates: {+ title?: string;+ content?: string;+ enhanced_content?: string | null;+ enhancement_prompt?: string | null;+ enhanced_at_content_hash?: string | null;+ folder_id?: number | null;+ }+ ) => Promise<{ success: boolean; note?: NoteItem }>;+ deleteNote: (id: number) => Promise<{ success: boolean }>;+ exportNote: (+ noteId: number,+ format: "txt" | "md"+ ) => Promise<{ success: boolean; error?: string }>;++ // Folder operations+ getFolders: () => Promise<FolderItem[]>;+ createFolder: (+ name: string+ ) => Promise<{ success: boolean; folder?: FolderItem; error?: string }>;+ deleteFolder: (id: number) => Promise<{ success: boolean; error?: string }>;+ renameFolder: (+ id: number,+ name: string+ ) => Promise<{ success: boolean; folder?: FolderItem; error?: string }>;+ getFolderNoteCounts: () => Promise<Array<{ folder_id: number; count: number }>>;++ // Action operations+ getActions: () => Promise<ActionItem[]>;+ getAction: (id: number) => Promise<ActionItem | null>;+ createAction: (+ name: string,+ description: string,+ prompt: string,+ icon?: string+ ) => Promise<{ success: boolean; action?: ActionItem; error?: string }>;+ updateAction: (+ id: number,+ updates: {+ name?: string;+ description?: string;+ prompt?: string;+ icon?: string;+ sort_order?: number;+ }+ ) => Promise<{ success: boolean; action?: ActionItem; error?: string }>;+ deleteAction: (id: number) => Promise<{ success: boolean; id?: number; error?: string }>;+ onActionCreated?: (callback: (action: ActionItem) => void) => () => void;+ onActionUpdated?: (callback: (action: ActionItem) => void) => () => void;+ onActionDeleted?: (callback: (payload: { id: number }) => void) => () => void;++ // Audio file operations+ selectAudioFile: () => Promise<{ canceled: boolean; filePath?: string }>;+ transcribeAudioFile: (+ filePath: string,+ options?: {+ provider?: "whisper" | "nvidia";+ model?: string;+ language?: string;+ [key: string]: unknown;+ }+ ) => Promise<{ success: boolean; text?: string; error?: string }>;+ getPathForFile: (file: File) => string;++ // Note event listeners+ onNoteAdded?: (callback: (note: NoteItem) => void) => () => void;+ onNoteUpdated?: (callback: (note: NoteItem) => void) => () => void;+ onNoteDeleted?: (callback: (payload: { id: number }) => void) => () => void;+// Database event listenersonTranscriptionAdded?: (callback: (item: TranscriptionItem) => void) => () => void;onTranscriptionDeleted?: (callback: (payload: { id: number }) => void) => () => void;@@ -474,11 +605,12 @@ declare global {isTrial?: boolean;trialDaysLeft?: number | null;currentPeriodEnd?: string | null;+ billingInterval?: "monthly" | "annual" | null;resetAt?: string;error?: string;code?: string;}>;- cloudCheckout?: () => Promise<{+ cloudCheckout?: (plan?: "monthly" | "annual") => Promise<{success: boolean;url?: string;error?: string;@@ -491,6 +623,26 @@ declare global {code?: string;}>;+ // Cloud audio file transcription+ transcribeAudioFileCloud?: (filePath: string) => Promise<{+ success: boolean;+ text?: string;+ error?: string;+ code?: string;+ }>;++ // BYOK audio file transcription+ transcribeAudioFileByok?: (options: {+ filePath: string;+ apiKey: string;+ baseUrl: string;+ model: string;+ }) => Promise<{+ success: boolean;+ text?: string;+ error?: string;+ }>;+// Usage limit eventsnotifyLimitReached?: (data: { wordsUsed: number; limit: number }) => void;onLimitReached?: (@@ -534,6 +686,46 @@ declare global {callback: (data: { audioDuration?: number; text?: string }) => void) => () => void;+ // Referral stats+ getReferralStats?: () => Promise<{+ referralCode: string;+ referralLink: string;+ totalReferrals: number;+ completedReferrals: number;+ pendingReferrals: number;+ totalMonthsEarned: number;+ referrals: Array<{+ id: string;+ email: string;+ name: string;+ status: "pending" | "completed" | "rewarded";+ created_at: string;+ first_payment_at: string | null;+ words_used: number;+ }>;+ }>;++ sendReferralInvite?: (email: string) => Promise<{+ success: boolean;+ invite: {+ id: string;+ recipientEmail: string;+ status: "sent" | "failed" | "opened" | "converted";+ sentAt: string;+ };+ }>;++ getReferralInvites?: () => Promise<{+ invites: Array<{+ id: string;+ recipientEmail: string;+ status: "sent" | "failed" | "opened" | "converted";+ sentAt: string;+ openedAt?: string;+ convertedAt?: string;+ }>;+ }>;+// Deepgram StreamingdeepgramStreamingWarmup?: (options?: { sampleRate?: number; language?: string }) => Promise<{success: boolean;diff --git a/src/updater.js b/src/updater.jsindex dbabb3f77..ae98d2be8 100644--- a/src/updater.js+++ b/src/updater.js@@ -34,6 +34,15 @@ class UpdateManager {private: false,});+ // Use arch-specific update channel on macOS to prevent arm64/x64+ // from downloading mismatched artifacts. Both builds publish to the+ // same GitHub release, so without this they race on latest-mac.yml.+ // Setting channel to e.g. 'latest-arm64' makes the updater look for+ // 'latest-arm64-mac.yml' instead of the shared 'latest-mac.yml'.+ if (process.platform === "darwin") {+ autoUpdater.channel = process.arch === "arm64" ? "latest-arm64" : "latest-x64";+ }+// Disable auto-download - let user control when to downloadautoUpdater.autoDownload = false;diff --git a/src/utils/agentName.ts b/src/utils/agentName.tsindex baae26f8a..71db21dd2 100644--- a/src/utils/agentName.ts+++ b/src/utils/agentName.ts@@ -1,7 +1,7 @@import { useState } from "react";+import { getSettings, useSettingsStore } from "../stores/settingsStore";const AGENT_NAME_KEY = "agentName";-const DICTIONARY_KEY = "customDictionary";const DEFAULT_AGENT_NAME = "OpenWhispr";export const getAgentName = (): string => {@@ -9,16 +9,7 @@ export const getAgentName = (): string => {};function syncAgentNameToDictionary(newName: string, oldName?: string): void {- let dictionary: string[] = [];- try {- const raw = localStorage.getItem(DICTIONARY_KEY);- if (raw) {- const parsed = JSON.parse(raw);- if (Array.isArray(parsed)) dictionary = parsed;- }- } catch {- // ignore- }+ let dictionary = [...getSettings().customDictionary];// Remove old agent name if it changedif (oldName && oldName !== newName) {@@ -31,10 +22,7 @@ function syncAgentNameToDictionary(newName: string, oldName?: string): void {dictionary = [trimmed, ...dictionary];}- localStorage.setItem(DICTIONARY_KEY, JSON.stringify(dictionary));-- // Best-effort sync to SQLite- window.electronAPI?.setDictionary?.(dictionary).catch(() => {});+ useSettingsStore.getState().setCustomDictionary(dictionary);}export const setAgentName = (name: string): void => {diff --git a/src/utils/dateFormatting.ts b/src/utils/dateFormatting.tsnew file mode 100644index 000000000..89cbf0b72--- /dev/null+++ b/src/utils/dateFormatting.ts@@ -0,0 +1,13 @@+export function formatDateGroup(date: Date | string, t: (key: string) => string): string {+ const d = typeof date === "string" ? new Date(date) : date;+ const now = new Date();+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ const yesterday = new Date(today);+ yesterday.setDate(yesterday.getDate() - 1);+ const target = new Date(d.getFullYear(), d.getMonth(), d.getDate());++ if (target.getTime() === today.getTime()) return t("controlPanel.history.dateGroups.today");+ if (target.getTime() === yesterday.getTime())+ return t("controlPanel.history.dateGroups.yesterday");+ return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });+}diff --git a/src/utils/dictationCues.js b/src/utils/dictationCues.jsindex dfbb30255..02f19291c 100644--- a/src/utils/dictationCues.js+++ b/src/utils/dictationCues.js@@ -1,4 +1,5 @@import logger from "./logger";+import { getSettings } from "../stores/settingsStore";const START_NOTES = [523.25, 659.25];const STOP_NOTES = [587.33, 440];@@ -68,7 +69,7 @@ const scheduleTone = (context, frequency, startTime) => {oscillator.stop(stopTime + 0.01);};-const isEnabled = () => localStorage.getItem("audioCuesEnabled") !== "false";+const isEnabled = () => getSettings().audioCuesEnabled;const playCue = async (notes) => {try {diff --git a/src/utils/modelPickerStyles.ts b/src/utils/modelPickerStyles.tsindex 8e0a5beb1..c92e9f564 100644--- a/src/utils/modelPickerStyles.ts+++ b/src/utils/modelPickerStyles.ts@@ -1,4 +1,4 @@-export type ColorScheme = "purple" | "indigo" | "blue";+export type ColorScheme = "purple" | "blue";export interface ModelPickerStyles {container: string;@@ -17,33 +17,7 @@ export const MODEL_PICKER_COLORS: Record<ColorScheme, ModelPickerStyles> = {selected:"border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",default:- "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",- },- badges: {- selected:- "text-[10px] text-primary-foreground bg-primary px-1.5 py-0.5 rounded-sm font-medium",- downloaded:- "text-[10px] text-success dark:text-success bg-success/10 dark:bg-success/12 px-1.5 py-0.5 rounded-sm",- recommended:- "text-[10px] text-primary bg-primary/10 dark:bg-primary/12 px-1.5 py-0.5 rounded-sm font-medium",- },- buttons: {- download: "",- select: "border-primary/25 text-primary hover:bg-primary/8",- delete:- "text-destructive hover:text-destructive/90 hover:bg-destructive/8 border-destructive/25",- refresh: "border-primary/25 text-primary hover:bg-primary/8",- },- },- indigo: {- container:- "bg-surface-1/95 dark:bg-white/[0.03] rounded-lg overflow-hidden border border-border/60 dark:border-white/8 backdrop-blur-xl shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)",- header: "font-medium text-foreground tracking-tight",- modelCard: {- selected:- "border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",- default:- "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",+ "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-[background-color,border-color,transform,box-shadow] duration-200 ease-out",},badges: {selected:@@ -69,7 +43,7 @@ export const MODEL_PICKER_COLORS: Record<ColorScheme, ModelPickerStyles> = {selected:"border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",default:- "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",+ "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-[background-color,border-color,transform,box-shadow] duration-200 ease-out",},badges: {selected:diff --git a/src/utils/recordingErrors.ts b/src/utils/recordingErrors.tsnew file mode 100644index 000000000..48362f1ae--- /dev/null+++ b/src/utils/recordingErrors.ts@@ -0,0 +1,14 @@+import { TFunction } from "i18next";++export function getRecordingErrorTitle(+ error: { code?: string; title: string },+ t: TFunction+): string {+ return error.code === "AUTH_EXPIRED"+ ? t("hooks.audioRecording.errorTitles.sessionExpired")+ : error.code === "OFFLINE"+ ? t("hooks.audioRecording.errorTitles.offline")+ : error.code === "LIMIT_REACHED"+ ? t("hooks.audioRecording.errorTitles.dailyLimitReached")+ : error.title;+}