Explain setup save failures and accept dotenv key assignments
This commit is contained in:
parent
206f155c2c
commit
f88f6052b0
5 changed files with 80 additions and 9 deletions
|
|
@ -2,4 +2,4 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.3.0b4"
|
||||
__version__ = "0.3.0b5"
|
||||
|
|
|
|||
|
|
@ -31,6 +31,17 @@ def main() -> None:
|
|||
from voice_dictation.core.paths import AppPaths
|
||||
from voice_dictation.ui.setup_wizard import run_setup
|
||||
|
||||
if "--smoke-test" in sys.argv:
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with 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
|
||||
):
|
||||
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))
|
||||
return
|
||||
|
|
|
|||
|
|
@ -5,8 +5,11 @@ from __future__ import annotations
|
|||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
def read_api_key(root: Path) -> str:
|
||||
"""Read a saved key without logging its contents."""
|
||||
|
|
@ -18,11 +21,24 @@ def read_api_key(root: Path) -> str:
|
|||
return ""
|
||||
|
||||
|
||||
def normalize_api_key(value: str) -> str:
|
||||
"""Accept a key or one OPENAI_API_KEY assignment pasted from dotenv."""
|
||||
candidate = value.strip()
|
||||
if candidate.startswith(("OPENAI_API_KEY=", "OPENAI_API_KEY =", "export OPENAI_API_KEY=")):
|
||||
parsed = dotenv_values(stream=StringIO(candidate), interpolate=False)
|
||||
if set(parsed) != {"OPENAI_API_KEY"}:
|
||||
raise ValueError("Вставьте только строку OPENAI_API_KEY или значение ключа")
|
||||
candidate = (parsed.get("OPENAI_API_KEY") or "").strip()
|
||||
elif len(candidate) >= 2 and candidate[0] == candidate[-1] and candidate[0] in "\"'":
|
||||
candidate = candidate[1:-1].strip()
|
||||
if not candidate or any(char.isspace() for char in candidate) or "=" in candidate:
|
||||
raise ValueError("Введите ключ без пробелов и переносов строк")
|
||||
return candidate
|
||||
|
||||
|
||||
def save_api_key(root: Path, key: str) -> None:
|
||||
"""Atomically save a private credentials file (0600 on POSIX)."""
|
||||
key = key.strip()
|
||||
if not key or any(char.isspace() for char in key):
|
||||
raise ValueError("Введите ключ без пробелов и переносов строк")
|
||||
key = normalize_api_key(key)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
fd, name = tempfile.mkstemp(prefix=".credentials-", dir=root)
|
||||
temporary = Path(name)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ from voice_dictation.core.config import ConfigStore
|
|||
from voice_dictation.infrastructure.credentials import read_api_key, save_api_key
|
||||
|
||||
|
||||
def run_setup(root: Path, store: ConfigStore) -> bool:
|
||||
def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bool:
|
||||
"""Show setup before tray startup; return whether the user finished it."""
|
||||
window = ctk.CTk()
|
||||
window.title("Voice Dictation — первый запуск")
|
||||
|
|
@ -30,7 +30,7 @@ def run_setup(root: Path, store: ConfigStore) -> bool:
|
|||
value="Локально" if config.transcription_backend == "local" else "OpenAI API"
|
||||
)
|
||||
ctk.CTkOptionMenu(content, values=["Локально", "OpenAI API"], variable=backend).pack(pady=6)
|
||||
ctk.CTkLabel(content, text="OpenAI API-ключ (для локального режима не нужен):").pack()
|
||||
ctk.CTkLabel(content, text="OpenAI API-ключ или строка OPENAI_API_KEY=…:").pack()
|
||||
key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь")
|
||||
key.pack(pady=6)
|
||||
ctk.CTkLabel(
|
||||
|
|
@ -112,22 +112,45 @@ def run_setup(root: Path, store: ConfigStore) -> bool:
|
|||
)
|
||||
if "+" not in combination:
|
||||
raise ValueError("Укажите сочетание клавиш, например cmd+alt+d")
|
||||
except ValueError:
|
||||
message.configure(text="Не удалось разобрать хоткей. Попробуйте cmd+alt+d.")
|
||||
return
|
||||
try:
|
||||
if key.get().strip():
|
||||
save_api_key(root, key.get())
|
||||
except ValueError:
|
||||
message.configure(
|
||||
text="Вставьте значение ключа или одну строку OPENAI_API_KEY=… из .env."
|
||||
)
|
||||
return
|
||||
except OSError:
|
||||
message.configure(
|
||||
text="Не удалось записать ключ в папку профиля. Проверьте права доступа."
|
||||
)
|
||||
return
|
||||
if backend.get() == "OpenAI API" and not (read_api_key(root) or load_env().api_key):
|
||||
raise ValueError("Введите OpenAI API-ключ или выберите локальный режим")
|
||||
message.configure(text="Введите OpenAI API-ключ или выберите локальный режим.")
|
||||
return
|
||||
try:
|
||||
updated = store.load()
|
||||
updated.transcription_backend = "local" if backend.get() == "Локально" else "openai"
|
||||
updated.hotkey = hotkey.get().strip()
|
||||
store.save(updated)
|
||||
(root / "setup-complete").touch(mode=0o600)
|
||||
except (ValueError, OSError):
|
||||
message.configure(text="Проверьте ключ, сочетание клавиш и доступ к папке профиля.")
|
||||
message.configure(text="Не удалось записать настройки в папку профиля.")
|
||||
return
|
||||
completed = True
|
||||
window.destroy()
|
||||
|
||||
ctk.CTkButton(content, text="Сохранить и запустить диктовку", command=finish).pack(pady=8)
|
||||
refresh()
|
||||
if smoke_test:
|
||||
backend.set("OpenAI API")
|
||||
key.insert(0, "sk-test-not-a-real-key")
|
||||
hotkey.delete(0, "end")
|
||||
hotkey.insert(0, "cmd+space")
|
||||
window.after(200, finish)
|
||||
window.after(700, window.destroy)
|
||||
window.mainloop()
|
||||
return completed
|
||||
|
|
|
|||
|
|
@ -32,3 +32,24 @@ def test_invalid_key_preserves_previous(tmp_path: Path) -> None:
|
|||
def test_invalid_file_does_not_crash(tmp_path: Path) -> None:
|
||||
(tmp_path / "credentials.json").write_text("[]")
|
||||
assert read_api_key(tmp_path) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
" sk-test-not-real ",
|
||||
'"sk-test-not-real"',
|
||||
"OPENAI_API_KEY=sk-test-not-real",
|
||||
'OPENAI_API_KEY = "sk-test-not-real"',
|
||||
"export OPENAI_API_KEY=sk-test-not-real",
|
||||
],
|
||||
)
|
||||
def test_paste_from_dotenv(tmp_path: Path, value: str) -> None:
|
||||
save_api_key(tmp_path, value)
|
||||
assert read_api_key(tmp_path) == "sk-test-not-real"
|
||||
|
||||
|
||||
def test_multiple_env_values_rejected(tmp_path: Path) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test")
|
||||
assert not (tmp_path / "credentials.json").exists()
|
||||
|
|
|
|||
Loading…
Reference in a new issue