Doubao-powered voice input for Linux, Wayland and Omarchy
feat(input): add optional clipboard-free direct typing
quanrud305e9c2c0fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a678b4a..6e5458a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## 1.0.0 — release candidate+- Add an optional direct typing mode using wtype without touching the clipboard; clipboard paste remains the default.- Added one `install.sh` entry point for source checkouts and release archives, with explicit Arch/Omarchy dependency detection, confirmation and read-only checks.- Replaced the recording overlay's large update arrow with a compact red status dot.- Update caches are scoped to the installed application version, preventing stale development-version notifications after an upgrade, downgrade or version reset.diff --git a/README.md b/README.mdindex 4862352..114d246 100644--- a/README.md+++ b/README.md@@ -62,6 +62,22 @@ endpoint errors also safely fall back to it.The API key is stored separately with owner-only permissions and never appears indiagnostics. Use **Test endpoint** before enabling.+### Text input method++Settings → Input → **Text input method** defaults to **Clipboard paste**,+including for existing installations. Choose **Direct typing** to keep the+clipboard unchanged. Install `wtype` separately; this mode requires a compatible+Wayland virtual-keyboard implementation and has been tested on Hyprland.++Direct typing sends characters gradually (about 8 seconds for 1,760 characters+in our local test). Newlines and tabs act as Enter and Tab keys and can submit+messages, execute terminal commands or move focus. Keep the target focused and+avoid typing at the same time. Escape cancels remaining input; text already+entered cannot be withdrawn. Focus changes stop further input on a best-effort+basis. If direct typing fails or `wtype` is unavailable, the result stays in the+app with no automatic clipboard fallback. Check for partial input before retrying.++## GesturesDefault key: **Fn**. Change it to Ctrl, Shift, Alt, Meta, F8, F9, or Disabled.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 75b213c..0d97667 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -47,6 +47,19 @@ System 读取桌面会话的语言偏好,中文区域使用简体中文,其API Key 通过仅限当前用户读取的独立文件保存,不进入诊断信息。建议开启前先点击“测试接口”。+### 文字输入方式++设置 → 输入 → **文字输入方式**,默认使用**剪贴板粘贴**,已有配置也保持此默认值。+可选择**直接输入**以保持剪贴板不变。此模式需要另行安装 `wtype`,并使用支持+Wayland 虚拟键盘的桌面,已在 Hyprland 验证。++直接输入会逐字发送,本机测试 1,760 字约需 8 秒。换行和制表符相当于回车和 Tab,+可能发送消息、执行终端命令或切换焦点。输入期间请保持目标窗口聚焦并避免同时打字。+Esc 可停止后续输入,但不能撤回已输入的文字;焦点变化时也会尽力停止输入。+若直接输入失败或未安装 `wtype`,识别结果保留在应用中,不会自动转为剪贴板粘贴。+重试前请检查是否已有部分文字输入。++## 按键操作默认触发键为 **Fn**,可改为 Ctrl、Shift、Alt、Meta、F8、F9 或禁用。diff --git a/src/doubao_input/app.py b/src/doubao_input/app.pyindex c9a7ad6..f74267a 100644--- a/src/doubao_input/app.py+++ b/src/doubao_input/app.py@@ -177,7 +177,8 @@ class DoubaoInputApp(Gtk.Application):self._overlay = Overlay(self.app_state)self._injector = Injector()self._delivery = Delivery(GLib.timeout_add, focused_target,- lambda text, target, cancelled: self._injector.inject(text, expected_target=target, cancelled=cancelled),+ lambda text, target, cancelled: self._injector.inject(text, expected_target=target, cancelled=cancelled,+ method=self.settings.input_method),lambda target, cancelled: self._injector.send_enter(expected_target=target, cancelled=cancelled),self._delivery_changed, InputWorker(GLib.idle_add))self._polisher = PolishManager(GLib.idle_add)@@ -441,10 +442,10 @@ class DoubaoInputApp(Gtk.Application):def _submit_transcript(self, text, target, send_enter=False, *, original=None):self.recent.keep(text)- self._control.set_result(self.recent.text, tr("Ready to paste", "准备粘贴"))+ self._control.set_result(self.recent.text, tr("Ready to input", "准备输入"))self._overlay.set_status(- tr("Polished · Pasting…", "润色完成 · 正在粘贴…") if original- else tr("Pasting…", "正在粘贴…"))+ tr("Polished · Sending text…", "润色完成 · 正在输入…") if original+ else tr("Sending text…", "正在输入…"))# Never hide/restore an arbitrary foreground settings window to force input.# A missing or changed target keeps the text in recovery instead.if not self._delivery.submit(text, target, send_enter):@@ -501,12 +502,12 @@ class DoubaoInputApp(Gtk.Application):def _delivery_changed(self, status):self.recent.status = statusmessages = {- "pending": tr("Pasting…", "正在粘贴…"),- "attempted": tr("Paste sent. If text is missing, copy or retry below.", "已发送粘贴操作;若未出现文字,可在下方复制或重试。"),+ "pending": tr("Sending text…", "正在输入…"),+ "attempted": tr("Input sent. If text is missing, copy or retry below.", "已发送输入操作;若未出现文字,可在下方复制或重试。"),"target_changed": tr("Target changed or unavailable. Text kept; choose a target and retry.", "目标窗口已变化或无法确认。文字已保留,请选择目标后重试。"),- "failed": tr("Paste failed. Your text is kept here.", "粘贴失败,文字已保留。"),- "enter_skipped": tr("Paste attempted; Enter skipped because the target changed or input failed.", "已尝试粘贴;因目标变化或输入失败,未发送回车。"),- "cancelled": tr("Pending input cancelled.", "已取消待发送的输入。"),+ "failed": tr("Input failed. Your text is kept here; some may already have been entered. For direct typing, check wtype and desktop support.", "输入失败,文字已保留;可能已有部分文字输入。使用直接输入时,请检查 wtype 和桌面支持。"),+ "enter_skipped": tr("Input attempted; Enter skipped because the target changed or input failed.", "已尝试输入;因目标变化或输入失败,未发送回车。"),+ "cancelled": tr("Input cancelled. Text already entered cannot be withdrawn.", "已取消输入,已输入的文字无法撤回。"),}self._control.set_result(self.recent.text, messages.get(status, status))self._control.set_feedback(messages.get(status, status))diff --git a/src/doubao_input/inject/direct.py b/src/doubao_input/inject/direct.pynew file mode 100644index 0000000..b053388--- /dev/null+++ b/src/doubao_input/inject/direct.py@@ -0,0 +1,48 @@+"""Cancellable Unicode input through Wayland's virtual keyboard (no clipboard)."""+import logging+import subprocess+import time++from doubao_input.inject.target import focused_target++logger = logging.getLogger(__name__)+++def type_text(text, expected_target, cancelled):+ """Never retry: a failed process may already have delivered some characters."""+ def allowed():+ return (not cancelled() and expected_target+ and focused_target() == expected_target and not cancelled())++ if not text or not allowed():+ return False+ process = None+ try:+ # Keep transcripts out of argv, logs and temporary files. communicate()+ # handles partial pipe writes; subsequent calls resume after a timeout.+ process = subprocess.Popen(["wtype", "-"], stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ pending = text.encode("utf-8")+ deadline = time.monotonic() + max(5, len(text) * 0.03 + 2)+ while allowed() and time.monotonic() < deadline:+ try:+ process.communicate(input=pending, timeout=0.03)+ return process.returncode == 0 and allowed()+ except subprocess.TimeoutExpired:+ pending = None+ return False+ except (OSError, ValueError):+ # Error details from helpers can contain input; never log them.+ logger.warning("Direct input unavailable or failed; text retained")+ return False+ finally:+ if process is not None:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=0.3)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ if process.stdin:+ process.stdin.close()diff --git a/src/doubao_input/inject/injector.py b/src/doubao_input/inject/injector.pyindex 060dfd5..2de7ecb 100644--- a/src/doubao_input/inject/injector.py+++ b/src/doubao_input/inject/injector.py@@ -1,17 +1,4 @@-"""Text injection: copy-to-clipboard + simulate Ctrl+V via uinput.--The only reliable way to "paste" into a native Wayland app on GNOME-(Mutter does not implement the virtual-keyboard protocol that wtype-needs) is to write text to the clipboard and then synthesize a-Ctrl+V keypress via a /dev/uinput virtual keyboard.--CJK text cannot be typed key-by-key through a virtual keyboard, so-the clipboard path is mandatory for Chinese.--The uinput device is opened lazily on first inject() and kept alive-for the process lifetime to avoid the per-injection cost of creating-and destroying a kernel device.-"""+"""Clipboard paste via uinput, or optional direct Unicode input via wtype."""from __future__ import annotationsimport logging@@ -24,6 +11,7 @@ from typing import Optionalfrom doubao_input.doubao.host_tools import command_candidatesfrom doubao_input.inject.target import focused_target+from doubao_input.inject.direct import type_textlogger = logging.getLogger(__name__)@@ -74,8 +62,13 @@ class Injector:# ---- public ----- def inject(self, text: str, use_shift: bool | None = None, *, expected_target=None, cancelled=lambda: False) -> bool:- """Copy text to clipboard then synthesize Ctrl+V (or Ctrl+Shift+V)."""+ def inject(self, text: str, use_shift: bool | None = None, *, expected_target=None, cancelled=lambda: False, method="clipboard") -> bool:+ """Deliver using the selected method; direct input never falls back to paste."""+ if method == "direct":+ with self._lock:+ return type_text(text, expected_target, cancelled)+ if method != "clipboard":+ return Falseif not text or cancelled():return Falseif expected_target and focused_target() != expected_target:diff --git a/src/doubao_input/settings.py b/src/doubao_input/settings.pyindex bdc3928..4ba5d06 100644--- a/src/doubao_input/settings.py+++ b/src/doubao_input/settings.py@@ -153,6 +153,8 @@ def write_atomic(path, data, mode=0o600):temporary.unlink(missing_ok=True)+INPUT_METHODS = ("clipboard", "direct")+WAVEFORM_STYLES = ("bars", "waves", "ripples", "basketball")@@ -165,6 +167,7 @@ class Settings:hold_ms: int = 350double_ms: int = 300double_enter: bool = True+ input_method: str = "clipboard"autostart: bool = Falsemicrophone: str = ""reduced_motion: bool = False@@ -177,6 +180,8 @@ class Settings:onboarding_complete: bool = Falsedef validate(self):+ if self.input_method not in INPUT_METHODS:+ raise ValueError(tr("Unsupported input method", "不支持的输入方式"))if self.waveform_style not in WAVEFORM_STYLES:raise ValueError(tr("Unsupported waveform style", "不支持的波纹样式"))if self.language not in LANGUAGES:diff --git a/src/doubao_input/ui/settings_window.py b/src/doubao_input/ui/settings_window.pyindex 74948d5..9344fda 100644--- a/src/doubao_input/ui/settings_window.py+++ b/src/doubao_input/ui/settings_window.py@@ -6,7 +6,7 @@ from doubao_input.i18n import LANGUAGES, trfrom doubao_input.doubao.devices import microphonesfrom doubao_input.diagnostics import reportfrom doubao_input.product import VERSION-from doubao_input.settings import WAVEFORM_STYLES+from doubao_input.settings import INPUT_METHODS, WAVEFORM_STYLESfrom doubao_input.ui.style import apply_window_style@@ -69,6 +69,17 @@ class SettingsWindow:Gtk.Switch(active=settings.autostart))section(tr("Input", "输入"))+ self.input_method = Gtk.DropDown.new_from_strings([+ tr("Clipboard paste (default)", "剪贴板粘贴(默认)"),+ tr("Direct typing", "直接输入"),+ ])+ self.input_method.set_selected(INPUT_METHODS.index(settings.input_method))+ row(tr("Text input method", "文字输入方式"), self.input_method)+ self.direct_hint = Gtk.Label(xalign=0, wrap=True, label=tr(+ "Direct typing keeps the clipboard unchanged and requires wtype and a compatible Wayland desktop (tested on Hyprland). Long text takes longer. Newlines and tabs act as Enter and Tab keys and may submit messages or move focus. Failure keeps your text without falling back to paste; some characters may already have been typed.",+ "直接输入不会改动剪贴板,需要安装 wtype 并使用兼容的 Wayland 桌面(已在 Hyprland 验证)。长文本输入较慢;换行和制表符相当于回车和 Tab,可能发送消息或切换焦点。失败时保留文字,不自动转为粘贴;可能已有部分文字输入。"))+ self.direct_hint.set_visible(settings.input_method == "direct")+ box.append(self.direct_hint)def use_key(key, modifiers=()):if apply_key:apply_key(key, modifiers)@@ -174,6 +185,7 @@ class SettingsWindow:self.language.connect("notify::selected", self._language_changed)self.autostart.connect("notify::active", self._changed)+ self.input_method.connect("notify::selected", self._changed)self.enter.connect("notify::active", self._changed)self.hold.connect("value-changed", self._changed)self.double.connect("value-changed", self._changed)@@ -189,6 +201,7 @@ class SettingsWindow:hold_ms=self.hold.get_value_as_int(),double_ms=self.double.get_value_as_int(),double_enter=self.enter.get_active(),+ input_method=INPUT_METHODS[self.input_method.get_selected()],autostart=self.autostart.get_active(),microphone=self.sources[self.microphone.get_selected()][0],reduced_motion=self.motion.get_active(),@@ -200,6 +213,7 @@ class SettingsWindow:self.language.set_selected(LANGUAGES.index(self._settings.language))self.autostart.set_active(self._settings.autostart)self.enter.set_active(self._settings.double_enter)+ self.input_method.set_selected(INPUT_METHODS.index(self._settings.input_method))self.hold.set_value(self._settings.hold_ms)self.double.set_value(self._settings.double_ms)self.microphone.set_selected(@@ -231,6 +245,7 @@ class SettingsWindow:def _changed(self, *_):self._save_current()+ self.direct_hint.set_visible(self._settings.input_method == "direct")def _language_changed(self, *_):previous = self._settings.languagediff --git a/tests/manual_direct_input.py b/tests/manual_direct_input.pynew file mode 100644index 0000000..ca726b3--- /dev/null+++ b/tests/manual_direct_input.py@@ -0,0 +1,116 @@+"""Opt-in live wtype/GTK acceptance; no microphone, network or clipboard writes.++Run with a 35-second process timeout and avoid typing or changing focus.+Only the temporary test windows receive input. User settings are not changed.+"""+import hashlib+import json+import os+from pathlib import Path+import subprocess+from threading import Event, Thread++import gi+gi.require_version('Gtk', '4.0')+from gi.repository import Gtk, GLib++from manual_safety import hard_deadline+from doubao_input.inject.injector import Injector+from doubao_input.inject.target import focused_target+++def clipboard_snapshot():+ snapshot = {}+ for name, flags in [('clipboard', []), ('primary', ['--primary'])]:+ types = subprocess.run(['wl-paste', *flags, '--list-types'], capture_output=True, timeout=2)+ snapshot[name] = {}+ for mime in sorted(types.stdout.decode().splitlines()):+ data = subprocess.run(['wl-paste', *flags, '--no-newline', '--type', mime],+ capture_output=True, timeout=2)+ snapshot[name][mime] = (data.returncode, hashlib.sha256(data.stdout).hexdigest())+ return snapshot+++def main():+ Gtk.init()+ original_target = focused_target()+ before = clipboard_snapshot()+ window = Gtk.Window(title='Doubao Say — direct input acceptance')+ editor = Gtk.TextView()+ window.set_child(editor)+ window.set_default_size(640, 320)+ other = Gtk.Window(title='Doubao Say — focus change acceptance')+ other.set_child(Gtk.TextView())+ injector = Injector()+ cancel = Event()+ loop = GLib.MainLoop()+ results = []+ cases = [('unicode', '你好,直接输入!Hello 🙂 ∇ e\u0301\n第二行。'),+ ('long', '中文 English 123。' * 100),+ ('cancel', '取消输入测试。' * 400),+ ('focus_change', '焦点变化测试。' * 400)]+ workers = []++ def begin():+ name, text = cases[len(results)]+ active = json.loads(subprocess.check_output(['hyprctl', 'activewindow', '-j'], timeout=2))+ assert active.get('pid') == os.getpid(), 'Test window must be focused'+ target = focused_target()+ assert target, 'Test requires a known Hyprland target'+ buffer = editor.get_buffer()+ buffer.set_text('')+ cancel.clear()+ def inject():+ result = injector.inject(text, method='direct', expected_target=target,+ cancelled=cancel.is_set)+ GLib.idle_add(collect, name, text, result)+ worker = Thread(target=inject, daemon=True)+ workers.append(worker)+ worker.start()+ if name == 'cancel':+ GLib.timeout_add(180, lambda: cancel.set() or False)+ elif name == 'focus_change':+ GLib.timeout_add(180, lambda: other.present() or False)+ return False++ def collect(name, expected, result):+ buffer = editor.get_buffer()+ received = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), True)+ passed = (result and received == expected) if name in ('unicode', 'long') else (+ not result and 0 < len(received) < len(expected) and expected.startswith(received))+ results.append({'case': name, 'passed': passed, 'received_characters': len(received)})+ if len(results) == len(cases):+ loop.quit()+ else:+ GLib.timeout_add(200, begin)+ return False++ try:+ window.present()+ editor.grab_focus()+ GLib.timeout_add(800, begin)+ GLib.timeout_add(25000, lambda: loop.quit() or False)+ loop.run()+ finally:+ cancel.set()+ for worker in workers:+ worker.join(timeout=2)+ injector.close()+ other.set_visible(False)+ window.set_visible(False)+ if original_target:+ subprocess.run(['hyprctl', 'dispatch', 'focuswindow', 'address:'+original_target],+ capture_output=True, timeout=2)+ unchanged = clipboard_snapshot() == before+ report = {'cases': results, 'clipboard_unchanged': unchanged}+ output = Path('artifacts/direct-input-acceptance.json')+ output.parent.mkdir(exist_ok=True)+ output.write_text(json.dumps(report, ensure_ascii=False, indent=2))+ print(json.dumps(report), flush=True)+ assert len(results) == len(cases) and all(row['passed'] for row in results)+ assert unchanged+++if __name__ == '__main__':+ with hard_deadline():+ main()diff --git a/tests/manual_refactor_smoke.py b/tests/manual_refactor_smoke.pyindex 16705e4..ab17100 100644--- a/tests/manual_refactor_smoke.py+++ b/tests/manual_refactor_smoke.py@@ -15,7 +15,7 @@ gi.require_version("Gtk", "4.0")from gi.repository import GLib, Gtkfrom doubao_input.app import DoubaoInputAppfrom doubao_input.i18n import set_language-from doubao_input.settings import Settings, WAVEFORM_STYLES+from doubao_input.settings import Settings, INPUT_METHODS, WAVEFORM_STYLESfrom doubao_input.ui.settings_window import SettingsWindow@@ -57,6 +57,19 @@ def main():assert app.settings.waveform_style == styleassert app._overlay.waveform_style == styleassert Settings.load().waveform_style == style+ for index, method in enumerate(INPUT_METHODS):+ window.input_method.set_selected(index)+ assert window.direct_hint.get_visible() == (method == "direct")+ assert app.settings.input_method == method+ assert Settings.load().input_method == method+ app._delivery.paste("routing probe", "fake-target", lambda: False)+ assert injector.return_value.inject.call_args.kwargs["method"] == method+ # Saving while busy must restore the selection and saved preference.+ with patch.object(app, "_busy", return_value=True):+ window.input_method.set_selected(0)+ assert window.input_method.get_selected() == 1+ assert Settings.load().input_method == "direct"+ injector.return_value.inject.reset_mock()picker = window.trigger_pickerpreset = 29 if app.settings.doubao_key != 29 else 56preset_index = [entry[1] for entry in picker.entries].index(preset)diff --git a/tests/test_direct_input.py b/tests/test_direct_input.pynew file mode 100644index 0000000..29b7191--- /dev/null+++ b/tests/test_direct_input.py@@ -0,0 +1,101 @@+"""No real keyboard events: exercise routing and helper lifecycle with fake processes."""+import subprocess+from threading import Event+from unittest import TestCase+from unittest.mock import Mock, patch++from doubao_input.inject.direct import type_text+from doubao_input.inject.injector import Injector+++class DirectInputTest(TestCase):+ def setUp(self):+ self.process = Mock(returncode=0)+ self.process.poll.return_value = 0+ self.spawn = self.enterContext(patch(+ 'doubao_input.inject.direct.subprocess.Popen', return_value=self.process))+ self.focus = self.enterContext(patch(+ 'doubao_input.inject.direct.focused_target', return_value='target'))+ self.clipboard = self.enterContext(patch.object(Injector, '_copy_to_clipboard'))+ self.paste = self.enterContext(patch.object(Injector, '_simulate_paste'))+ self.addCleanup(self.clipboard.assert_not_called)+ self.addCleanup(self.paste.assert_not_called)++ def inject(self, text='你好 🙂\n第二行', **kwargs):+ return Injector().inject(text, method='direct', expected_target='target', **kwargs)++ def test_direct_unicode_uses_stdin_not_argv_or_clipboard(self):+ text = '你好 🙂\n第二行 --not-an-option'+ self.assertTrue(self.inject(text))+ self.assertEqual(self.spawn.call_args.args, (['wtype', '-'],))+ self.process.communicate.assert_called_once_with(input=text.encode(), timeout=0.03)+ self.process.stdin.close.assert_called_once()++ def test_missing_helper_and_nonzero_exit_never_fall_back(self):+ self.spawn.side_effect = FileNotFoundError()+ self.assertFalse(self.inject())+ self.spawn.side_effect = None+ self.process.returncode = 1+ self.assertFalse(self.inject())+ self.assertEqual(self.spawn.call_count, 2)++ def test_refuses_unknown_or_changed_target_and_precancelled_input(self):+ self.assertFalse(type_text('text', None, lambda: False))+ self.focus.return_value = 'other'+ self.assertFalse(self.inject())+ self.focus.return_value = 'target'+ self.assertFalse(self.inject(cancelled=lambda: True))+ self.spawn.assert_not_called()++ def test_timeout_resumes_stdin_without_repeating_text(self):+ self.process.communicate.side_effect = [subprocess.TimeoutExpired('wtype', .03), (None, None)]+ self.assertTrue(self.inject())+ self.assertIsNone(self.process.communicate.call_args_list[1].kwargs['input'])+ self.spawn.assert_called_once()++ def test_cancel_during_input_stops_and_reaps_helper(self):+ cancel = Event()+ def communicate(**_):+ cancel.set()+ raise subprocess.TimeoutExpired('wtype', .03)+ self.process.communicate.side_effect = communicate+ self.process.poll.return_value = None+ self.assertFalse(self.inject(cancelled=cancel.is_set))+ self.process.terminate.assert_called_once()+ self.process.wait.assert_called_once_with(timeout=.3)++ def test_focus_loss_during_input_stops_helper(self):+ def communicate(**_):+ self.focus.return_value = 'other'+ raise subprocess.TimeoutExpired('wtype', .03)+ self.process.communicate.side_effect = communicate+ self.process.poll.return_value = None+ self.assertFalse(self.inject())+ self.process.terminate.assert_called_once()++ def test_hung_helper_is_killed_and_reaped(self):+ self.process.poll.return_value = None+ self.process.wait.side_effect = [subprocess.TimeoutExpired('wtype', .3), 0]+ with patch('doubao_input.inject.direct.time.monotonic', side_effect=[0, 10]):+ self.assertFalse(self.inject())+ self.process.terminate.assert_called_once()+ self.process.kill.assert_called_once()+ self.assertEqual(self.process.wait.call_count, 2)+ self.process.stdin.close.assert_called_once()++ def test_unknown_method_does_not_send_input(self):+ self.assertFalse(Injector().inject('text', method='unknown'))+ self.spawn.assert_not_called()+++class ClipboardDefaultTest(TestCase):+ def test_existing_callers_still_use_clipboard(self):+ injector = Injector()+ with patch.object(injector, '_copy_to_clipboard', return_value=True) as copy, \+ patch.object(injector, '_simulate_paste', return_value=True) as paste, \+ patch('doubao_input.inject.injector.type_text') as direct, \+ patch('doubao_input.inject.injector.time.sleep'):+ self.assertTrue(injector.inject('你好', use_shift=False))+ copy.assert_called_once_with('你好')+ paste.assert_called_once()+ direct.assert_not_called()diff --git a/tests/test_settings.py b/tests/test_settings.pyindex 4b44fcc..ecbb689 100644--- a/tests/test_settings.py+++ b/tests/test_settings.py@@ -29,6 +29,21 @@ class SettingsTest(unittest.TestCase):migrated = Settings.load()self.assertEqual(migrated.polish_prompt_zh, custom)self.assertEqual(migrated.polish_prompt_en, custom)+ def test_input_method_defaults_and_roundtrip(self):+ with tempfile.TemporaryDirectory() as root, patch.dict("os.environ", {"XDG_CONFIG_HOME": root}):+ self.assertEqual(Settings.load().input_method, "clipboard")+ path = Path(root) / "doubao-say/settings.json"+ path.parent.mkdir()+ path.write_text('{"language": "zh_CN"}')+ self.assertEqual(Settings.load().input_method, "clipboard")+ value = Settings.load()+ value.input_method = "direct"+ value.save()+ self.assertEqual(Settings.load(), value)+ for invalid in ("unknown", None, True):+ with self.subTest(invalid=invalid), self.assertRaises(ValueError):+ Settings(input_method=invalid).validate()+def test_defaults(self):Settings().validate()