From a44d45f43117b30b6330a61c0a0fc6cb94f83554 Mon Sep 17 00:00:00 2001 From: Vickenty Zherebov Date: Tue, 20 Oct 2026 13:08:54 +0300 Subject: [PATCH] Isolate setup from tray and verify native clipboard acceptance --- src/voice_dictation/__init__.py | 2 +- src/voice_dictation/__main__.py | 42 +++++++++++++++++++--- src/voice_dictation/ui/entry_shortcuts.py | 12 ++++++- src/voice_dictation/ui/setup_acceptance.py | 33 +++++++++++++++++ src/voice_dictation/ui/setup_wizard.py | 19 +++++++--- 5 files changed, 98 insertions(+), 10 deletions(-) create mode 100644 src/voice_dictation/ui/setup_acceptance.py diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index 595d8d1..df57900 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.3.0b6" +__version__ = "0.3.0b7" diff --git a/src/voice_dictation/__main__.py b/src/voice_dictation/__main__.py index b2c9e00..98ca1c7 100644 --- a/src/voice_dictation/__main__.py +++ b/src/voice_dictation/__main__.py @@ -35,7 +35,12 @@ def main() -> None: import tempfile from pathlib import Path - with tempfile.TemporaryDirectory(prefix="voice-setup-smoke-") as directory: + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + with ( + synthetic_clipboard(), + tempfile.TemporaryDirectory(prefix="voice-setup-smoke-") as directory, + ): test_root = Path(directory) if not run_setup( test_root, ConfigStore(test_root / "config.json"), smoke_test=True @@ -43,7 +48,16 @@ def main() -> None: raise RuntimeError("Setup smoke test failed to save synthetic settings") return setup_paths = AppPaths.default().ensure_exists() - run_setup(setup_paths.root, ConfigStore(setup_paths.config_file)) + if "--startup-setup-test" in sys.argv: + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + with synthetic_clipboard(): + if not run_setup( + setup_paths.root, ConfigStore(setup_paths.config_file), smoke_test=True + ): + raise RuntimeError("Startup setup test failed") + else: + run_setup(setup_paths.root, ConfigStore(setup_paths.config_file)) return if len(sys.argv) > 1 and sys.argv[1] == "settings": @@ -98,9 +112,26 @@ def main() -> None: config.splash_enabled = False config_store.save(config) if not (paths.root / "setup-complete").exists(): - from voice_dictation.ui.setup_wizard import run_setup + import os + import subprocess - if not run_setup(paths.root, config_store): + # Tk and pystray/AppKit must not share a process on macOS. + setup_command = ( + [sys.executable, "setup"] + if getattr(sys, "frozen", False) + else [sys.executable, "-m", "voice_dictation", "setup"] + ) + if "--startup-smoke-test" in sys.argv: + setup_command.append("--startup-setup-test") + setup_env = os.environ.copy() + setup_env["VOICE_DICTATION_HOME"] = str(paths.root) + try: + setup_result = subprocess.run(setup_command, env=setup_env, check=False) + except OSError: + logger.error("Не удалось открыть мастер настройки") + lock.release() + return + if setup_result.returncode or not (paths.root / "setup-complete").exists(): lock.release() return config = config_store.load() @@ -314,6 +345,9 @@ def main() -> None: hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃") print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}") + if "--startup-smoke-test" in sys.argv: + threading.Timer(2.0, _quit).start() + try: tray.run() finally: diff --git a/src/voice_dictation/ui/entry_shortcuts.py b/src/voice_dictation/ui/entry_shortcuts.py index 083be93..1c27146 100644 --- a/src/voice_dictation/ui/entry_shortcuts.py +++ b/src/voice_dictation/ui/entry_shortcuts.py @@ -12,7 +12,17 @@ import customtkinter as ctk def paste_into(entry: ctk.CTkEntry, reader: Callable[[], str] | None = None) -> str: """Paste without exposing clipboard data, replacing the current selection.""" try: - value = (reader or entry.clipboard_get)() + if reader is not None: + value = reader() + elif sys.platform == "darwin": + from AppKit import NSPasteboard, NSPasteboardTypeString + + native_value = NSPasteboard.generalPasteboard().stringForType_(NSPasteboardTypeString) + if native_value is None: + return "break" + value = str(native_value) + else: + value = entry.clipboard_get() if entry.select_present(): entry.delete("sel.first", "sel.last") entry.insert("insert", value) diff --git a/src/voice_dictation/ui/setup_acceptance.py b/src/voice_dictation/ui/setup_acceptance.py new file mode 100644 index 0000000..344a40f --- /dev/null +++ b/src/voice_dictation/ui/setup_acceptance.py @@ -0,0 +1,33 @@ +"""Native setup acceptance helpers using synthetic clipboard content only.""" + +from __future__ import annotations + +import sys +from collections.abc import Iterator +from contextlib import contextmanager + + +@contextmanager +def synthetic_clipboard() -> Iterator[None]: + """Temporarily replace and restore every native pasteboard representation.""" + if sys.platform != "darwin": + raise RuntimeError("Native clipboard acceptance currently requires macOS") + from AppKit import NSPasteboard, NSPasteboardItem, NSPasteboardTypeString + + board = NSPasteboard.generalPasteboard() + saved = [] + for item in board.pasteboardItems() or []: + restored = NSPasteboardItem.alloc().init() + for kind in item.types(): + data = item.dataForType_(kind) + if data is not None: + restored.setData_forType_(data, kind) + saved.append(restored) + board.clearContents() + board.setString_forType_("sk-test-not-a-real-key", NSPasteboardTypeString) + try: + yield + finally: + board.clearContents() + if saved: + board.writeObjects_(saved) diff --git a/src/voice_dictation/ui/setup_wizard.py b/src/voice_dictation/ui/setup_wizard.py index 7c2aea2..c6bb977 100644 --- a/src/voice_dictation/ui/setup_wizard.py +++ b/src/voice_dictation/ui/setup_wizard.py @@ -34,9 +34,9 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo ctk.CTkLabel(content, text="OpenAI API-ключ или строка OPENAI_API_KEY=…:").pack() key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь") key.pack(pady=6) - test_reader = (lambda: "sk-test-not-a-real-key") if smoke_test else None - bind_paste(key, test_reader) - ctk.CTkButton(content, text="Вставить ключ", command=lambda: paste_into(key)).pack(pady=4) + bind_paste(key) + paste_button = ctk.CTkButton(content, text="Вставить ключ", command=lambda: paste_into(key)) + paste_button.pack(pady=4) ctk.CTkLabel( content, text="Ключ сохраняется отдельно в вашем профиле с правами 0600.\n" @@ -75,7 +75,7 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo import sounddevice as sd try: - with sd.InputStream(samplerate=16000, channels=1) as stream: + with sd.RawInputStream(samplerate=16000, channels=1, dtype="int16") as stream: stream.read(1600) status.configure(text="Микрофон: запись доступна. Аудио не сохранено и не отправлено.") except Exception: @@ -154,6 +154,11 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo backend.set("OpenAI API") def test_paste() -> None: + paste_button.invoke() + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Native clipboard button test failed before keyboard test") + key.delete(0, "end") + window.focus_force() key.focus_set() window.update() focused = window.focus_get() @@ -166,7 +171,13 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo focused.event_generate("") if key.get() != "sk-test-not-a-real-key": raise RuntimeError("Russian layout paste/selection test failed") + key.delete(0, "end") + paste_button.invoke() + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Native clipboard button test failed") finish() + if completed and read_api_key(root) != "sk-test-not-a-real-key": + raise RuntimeError("Saved key mismatch") hotkey.delete(0, "end") hotkey.insert(0, "cmd+space")