Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

fix(gnome): scope shortcut permissions and default to Ctrl+semicolon (1.4.0)

Leyangba741037a975
diff --git a/.github/workflows/gnome-shortcuts.yml b/.github/workflows/gnome-shortcuts.yml
new file mode 100644
index 0000000..cbb40e4
--- /dev/null
+++ b/.github/workflows/gnome-shortcuts.yml
@@ -0,0 +1,47 @@
+name: GNOME shortcut permissions
+on:
+ push:
+ branches: [main, fix/gnome-portal-shortcuts]
+ paths:
+ - .github/workflows/gnome-shortcuts.yml
+ - tests/gnome/**
+ - src/doubao_input/trigger/**
+ - src/doubao_input/settings.py
+ pull_request:
+ branches: [main]
+ paths:
+ - .github/workflows/gnome-shortcuts.yml
+ - tests/gnome/**
+ - src/doubao_input/trigger/**
+ - src/doubao_input/settings.py
+ workflow_dispatch:
+permissions:
+ contents: read
+concurrency:
+ group: gnome-shortcuts-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ gnome-wayland:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+ with:
+ persist-credentials: false
+ - name: Build isolated GNOME desktop image
+ run: docker build -t doubao-gnome-ci -f tests/gnome/Dockerfile .
+ - name: Reproduce and verify on GNOME Wayland
+ run: |
+ mkdir -p artifacts/gnome
+ chmod 777 artifacts/gnome
+ timeout --signal=TERM --kill-after=15s 180s docker run --rm \
+ --name doubao-gnome-ci \
+ -v "$PWD/artifacts/gnome:/evidence" doubao-gnome-ci
+ - name: Upload GNOME evidence
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
+ with:
+ name: gnome-shortcut-evidence
+ path: artifacts/gnome/
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 7e8d4ce..0961f5c 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -79,9 +79,8 @@ jobs:
.venv/bin/pip install -r packaging/runtime-requirements.txt -r requirements-dev.txt
- name: Lint, test and enforce branch coverage
run: |
- make lint
+ make check
make coverage
- make compile
git show --format= --check HEAD
- name: Upload coverage report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a2ed01..06fdb7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 1.4.0
+
+- Automatically use permission-scoped GlobalShortcuts on GNOME without a special launch command or raw keyboard read permission for the dictation trigger.
+- Default new installations on every desktop to Ctrl+semicolon. Preserve saved shortcuts on other desktops and adapt unsupported saved evdev shortcuts on GNOME.
+- Register a valid GTK application identity before binding, retry rejected authorization, consume held shortcuts, and release sessions cleanly without an evdev fallback.
+- Add real GNOME 49 Wayland CI for authorization, normal launch, hold/release and cleanup, with regression tests for backend selection and settings migration.
+
## 1.3.1
- Fixed clipboard restoration after dictation: prefer plain text when the original clipboard offers both plain text and HTML, preventing HTML markup from appearing in later text pastes. Image and file payloads retain priority; HTML-only clipboards still use HTML. Added Wayland and X11 regression coverage.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 987b859..a9daec3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -79,9 +79,9 @@ For marketplace preparation, use `make marketplace-check` with Gitleaks on PATH
and follow [the publishing checklist](packaging/MARKETPLACE.md). Reports and local
review drafts belong in ignored `artifacts/` and `docs/`, not in release payloads.
-The current public version is `1.3.1`. Keep `pyproject.toml`, `manifest.json` and
+The current public version is `1.4.0`. Keep `pyproject.toml`, `manifest.json` and
`src/doubao_input/product.py` aligned; `python packaging/version_check.py` verifies
-them. A pushed tag such as `v1.3.1` runs all checks and secret scanning, builds app
+them. A pushed tag such as `v1.4.0` runs all checks and secret scanning, builds app
and plugin archives for every supported Python version, creates `SHA256SUMS`, and
publishes the GitHub Release. `workflow_dispatch` performs a non-publishing build.
# Bounded desktop tests
diff --git a/README.md b/README.md
index 6736a1f..33e75de 100644
--- a/README.md
+++ b/README.md
@@ -189,7 +189,9 @@ app with no automatic clipboard fallback. Check for partial input before retryin
## Gestures
-Default key: **Fn**. Change it to Ctrl, Shift, Alt, Meta, F8, F9, or Disabled.
+New installations default to **Ctrl+;** on every desktop. GNOME uses the desktop
+portal; other desktops use evdev. Existing saved shortcuts are retained, except
+that GNOME adapts unsupported saved evdev shortcuts (including Fn and modifier-only keys) to Ctrl+;.
Modifier keys are logical choices: either the left or right physical key works.
Your keyboard must report Fn as a Linux key; otherwise choose another key.
@@ -283,7 +285,44 @@ The update check sends a standard HTTPS request to GitHub at most once per day;
GitHub receives the usual connection metadata. The cached release tag and check
time contain no account, transcript or device identifier.
-Keyboard access and `/dev/uinput` permissions are required. Do not run the app as root.
+The default evdev trigger needs keyboard-device access. Adding your account to the
+`input` group grants other processes running with that group access to keyboard
+input too, including sensitive keystrokes; it is not an app-specific permission.
+Do not run the app as root.
+
+### Permission-scoped shortcuts on GNOME
+
+On GNOME, launch Doubao Say normally from its icon or existing command. It
+selects the GlobalShortcuts portal automatically and requests **Ctrl+;** on a
+fresh installation on every desktop. Unsupported saved evdev shortcuts, including Fn and modifier-only keys, also become Ctrl+; on GNOME;
+portal-supported shortcuts and Disabled are preserved. No environment variable or
+manual shortcut selection is needed. Approve the desktop's shortcut dialog.
+Other desktops retain their existing evdev behavior. For explicit troubleshooting
+only, `DOUBAO_SAY_TRIGGER_BACKEND=portal` or `evdev` overrides automatic selection.
+Portal mode installs its `md.lifeos.DoubaoSay.desktop` identity launcher under the
+XDG applications directory and registers that ID before requesting authorization.
+Approve the shortcut in the desktop's GlobalShortcuts dialog. The desktop may
+change the requested shortcut; its dialog is authoritative. This mode receives
+only activation/deactivation of the authorized dictation action, without opening
+`/dev/input` or requiring membership in `input`. Hold-to-talk, tap-to-toggle and
+double-tap use the existing gesture timing. Denial, timeout or a missing portal
+stops the listener without silently falling back to evdev. Restart the app to
+retry authorization.
+
+Portal mode does not support Fn/modifier-only shortcuts or raw key recording;
+supported keys are semicolon, F8, F9, Space, Return or Tab with optional Ctrl/Shift/Alt/Meta.
+Global Esc cancellation is not
+registered in this mode, so use the control center or tray's Cancel action.
+Vibekey is a separate, optional device listener and retains its own permissions.
+Input delivery is separate: `/dev/uinput` access may still be needed for injected
+shortcuts/paste. This change removes broad **keyboard reading** from the dictation
+trigger, not every device permission from the app. It does not remove existing group
+memberships or change system permissions.
+
+The backend requires an implementation of `org.freedesktop.portal.GlobalShortcuts`.
+GNOME backend availability varies by version. Full GNOME application support
+(including overlay and text delivery) is not established by this trigger feature.
+To explicitly retain raw keyboard behavior on GNOME, set the override to `evdev`.
Vibekey support is optional and off by default. When enabled in Settings, its three
transmitter buttons map to recording, Enter and cancel. Turning the dial right or
left sends Down or Up by default, and pressing it sends Meta+Backspace. All six
@@ -435,7 +474,7 @@ validate package metadata and scan for secrets. The current whole-package branch
coverage floor is 55%; desktop UI, WebKit and real-device paths remain included
in the denominator.
-The current release version is **1.3.1**. A `v1.3.1` tag must match every embedded
+The current release version is **1.4.0**. A `v1.4.0` tag must match every embedded
version before CI can publish. Tag releases rebuild both offline app and Omarchy
plugin archives for Python 3.11–3.14 and attach SHA-256 checksums. A manually started
release workflow builds artifacts for inspection but does not publish them. Real
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 1766390..6a085b9 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -146,7 +146,7 @@ Esc 可停止后续输入,但不能撤回已输入的文字;焦点变化时
## 按键操作
-默认触发键为 **Fn**,可改为 Ctrl、Shift、Alt、Meta、F8、F9 或禁用。
+新安装在所有桌面统一默认使用 **Ctrl+;**。GNOME 通过桌面 Portal 授权,其他桌面使用 evdev;其他桌面的已有快捷键保留;GNOME 中 Portal 不支持的旧配置(包括 Fn、单独修饰键和部分自定义按键)会自动适配为 Ctrl+;。
修饰键不区分左右,实际按任意一侧都能触发。
如果键盘没有向 Linux 上报 Fn 按键,请选择其他键。
@@ -213,7 +213,19 @@ OpenAI 兼容接口,并适用该接口运营方的数据留存、训练及隐
更新检查最多每天向 GitHub 发起一次标准 HTTPS 请求,GitHub 会收到常规连接元数据;
本地只缓存检查时间和版本标签,不包含账号、转写文字或设备标识。
-需要读取键盘设备及写入 `/dev/uinput` 的权限。不要以 root 身份运行软件。
+默认 evdev 触发器需要读取键盘设备。将账户加入 `input` 组后,使用该组权限运行的其他进程也能读取键盘输入,包括敏感按键;这不是只授予本软件的权限。不要以 root 身份运行软件。
+
+### GNOME 的快捷键授权
+
+在 GNOME 中直接点击图标或使用原来的命令启动即可,软件会自动使用 GlobalShortcuts Portal。
+所有桌面的新安装统一默认使用 **Ctrl+;**;GNOME 中 Portal 不支持的旧快捷键(包括 Fn、单独修饰键和部分自定义按键)也会自动适配为 Ctrl+;,Portal 支持的已保存快捷键和禁用状态保留。
+不需要设置环境变量或手动选择快捷键,只需在桌面的授权窗口中确认。其他桌面保留原有 evdev 行为。
+仅在排查问题时,可用 `DOUBAO_SAY_TRIGGER_BACKEND=portal` 或 `evdev` 手动指定后端。
+Portal 模式会在 XDG 应用目录生成 `md.lifeos.DoubaoSay.desktop` 启动器,并在申请授权前注册这个应用 ID。桌面可能调整所请求的快捷键,以授权对话框为准。此模式只接收已授权语音快捷键的按下和松开通知,不打开 `/dev/input`,触发器不要求加入 `input` 组。长按说话、单击开关、双击沿用现有时间规则。拒绝、超时或缺少 portal 时停止监听,不自动回退到 evdev;重新启动可再次申请授权。
+
+Portal 模式支持分号、F8、F9、空格、回车或 Tab,可搭配 Ctrl/Shift/Alt/Meta;不支持 Fn、单独修饰键或原始按键录制。此模式不注册全局 Esc 取消,请使用控制中心或托盘的取消操作。Vibekey 是独立的可选设备监听,仍需它自己的权限。文本输入与触发分开:注入快捷键、粘贴等操作仍可能需要 `/dev/uinput` 写权限。本次消除的是语音触发器的全局键盘读取要求,不是软件的全部设备权限;不会自动移除已有的用户组成员资格或更改系统权限。
+
+桌面须提供 `org.freedesktop.portal.GlobalShortcuts`。GNOME 后端是否可用取决于版本;此触发功能不代表已完成 GNOME 整个应用(浮层、文本输入等)的兼容验证。在 GNOME 中需要明确使用原始键盘模式时,可将后端变量设为 `evdev`。
Vibekey 支持默认关闭,可在设置中启用;三个发射器按键分别用于录音、回车确认和取消。
旋钮右转、左转、按下默认分别发送下方向键、上方向键和 Meta+Backspace;这三个旋钮动作
以及前三个按键都可以保留默认功能或重新录制任意键盘快捷键。关闭 Vibekey 支持时,
@@ -341,7 +353,7 @@ timeout --kill-after=5s 50s env PYTHONPATH=src python3 tests/manual/x11.py --run
GTK 测试、代码检查、编译、包元数据校验和密钥扫描。覆盖率按整个源码包的分支覆盖率
计算,当前真实门槛为 55%;GTK 界面、WebKit 和实体设备路径没有从分母中排除。
-当前发布版本为 **1.3.1**。只有 `v1.3.1` 标签与所有内置版本完全一致时,CI 才能发布。
+当前发布版本为 **1.4.0**。只有 `v1.4.0` 标签与所有内置版本完全一致时,CI 才能发布。
标签发布会为 Python 3.11–3.14 分别构建独立应用与 Omarchy 插件离线包,并附带 SHA-256
校验文件。手动启动发布工作流只构建供检查的产物,不会公开发布。真实登录、麦克风、
全局按键及桌面行为仍需按人工验收清单检查。
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index ba8dab3..b554042 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,23 +1,40 @@
-# Doubao Say 1.3.1
+# Doubao Say 1.4.0
-豆包说 1.3.1 修复听写结束后的剪贴板恢复问题,并更新桌面自动化验收和测试报告。
+## Permission-scoped shortcuts on GNOME
-## 剪贴板恢复修复
+Doubao Say now selects the GNOME GlobalShortcuts portal automatically on normal
+launch. Authorize the dictation shortcut in the desktop dialog; no special launch
+command or input-group membership is needed for this trigger. Hold-to-talk uses
+both activation and deactivation events. Rejected authorization can be retried;
+there is no silent fallback to raw keyboard reading.
-从浏览器等应用复制内容时,剪贴板可能同时提供纯文本和 HTML。旧版在听写结束后优先恢复 HTML,可能导致下一次向文本框粘贴时出现 HTML 标签。新版优先恢复纯文本,并补充 Wayland 和 X11 回归测试。
+New installations on every desktop default to **Ctrl+;**. Existing shortcuts are
+preserved on other desktops. On GNOME, saved shortcuts supported by the portal
+and Disabled are retained; unsupported saved evdev shortcuts (including Fn,
+modifier-only keys and unsupported custom keys) become Ctrl+;. You can edit the shortcut in GNOME's permission dialog. Other desktops
+retain evdev and their existing shortcut editing and recording behavior.
-图片和文件列表仍保留原有优先级;仅提供 HTML 的剪贴板仍按 HTML 恢复。
+## Verification and scope
-## 桌面验收与报告
+A new GitHub Actions acceptance test runs real GNOME 49 / Mutter Wayland and the
+GNOME portal as a non-root user without input-group membership. It checks normal
+launch detection, the real Cancel/Add permission flow, hold/release, shortcut
+consumption and cleanup. Unit, compatibility and release checks also run in CI.
-Midscene 升级至 1.13.3,调整引导、麦克风、文字润色和取消听写等流程的自动化操作。测试报告保留历史截图及未关联截图的自定义步骤,并在历史报告下载遇到临时错误时重试。
+This verifies the dictation trigger, not complete GNOME support for overlays,
+audio or text delivery. Text injection and optional Vibekey devices retain their
+own permissions. Portal mode does not support Fn, modifier-only shortcuts or raw
+shortcut recording; use the desktop dialog to customize the authorized shortcut.
-本版继续支持豆包账号识别、火山引擎 Volcengine Seed ASR 2.0 和 Deepgram Nova-3 英语识别。
+Doubao web-account recognition, Volcengine Seed ASR 2.0 and Deepgram Nova-3 remain
+available. This release also includes prompt and English interface refinements
+already merged since 1.3.1.
-## 获取与升级
+## Download and upgrade
-本 Release 提供适配 Python 3.11–3.14 的独立应用与 Omarchy 插件压缩包,并附有 `SHA256SUMS`。按 CPU 架构和 Python 版本选择对应文件,运行包内 `./install.sh`;设置与登录信息会保留。完整步骤见[安装指南](https://doubao-say.lifeos.md/zh/guide/install)。
+Choose the app or Omarchy plugin archive matching your Python 3.11–3.14 runtime,
+verify SHA256SUMS, and run its ./install.sh. Settings and sign-in data are retained.
+Git-installed plugins update through omarchy plugin update md.lifeos.doubao-say.
-Git 安装的 Omarchy 插件需先禁用,再执行 `omarchy plugin update md.lifeos.doubao-say`,按安装指南完成检查后重新启用。市场审核状态以插件市场公布的提交快照为准。
-
-[完整变更](https://github.com/quanru/doubao-say/compare/v1.3.0...v1.3.1)
+[Installation guide](https://doubao-say.lifeos.md/guide/install) ·
+[Full changes](https://github.com/quanru/doubao-say/compare/v1.3.1...v1.4.0)
diff --git a/SECURITY.md b/SECURITY.md
index ce16527..47a5662 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -1,8 +1,9 @@
# Security and privacy
The default backend uses an unofficial Doubao web protocol; the optional backend
-uses the official Volcengine Seed ASR API with a user-supplied key. The app also
-requests broad keyboard device access for global triggers. Use a normal user,
+uses the official Volcengine Seed ASR API with a user-supplied key. On GNOME the app requests a specific GlobalShortcuts action through the desktop
+portal. Other desktops use evdev, which needs broad keyboard device read access.
+Vibekey and virtual-keyboard text delivery have separate device permissions. Use a normal user,
never root. Review input
group membership and `/dev/uinput` permissions before installation.
diff --git a/install.sh b/install.sh
index 0f07cf0..19a1ae1 100755
--- a/install.sh
+++ b/install.sh
@@ -140,7 +140,8 @@ fi
if ! id -nG | tr ' ' '\n' | grep -qx input; then
printf '%s\n' \
- 'ACTION REQUIRED: your account is not in the input group.' \
+ 'OPTIONAL DEVICE SETUP: evdev triggers or virtual-keyboard paste may need input-group access.' \
+ 'GNOME Portal shortcuts do not require raw keyboard access.' \
"Run: sudo usermod -aG input $(id -un)" \
'Then log out and back in. This is intentionally not changed without your approval.'
fi
diff --git a/manifest.json b/manifest.json
index a2e1348..733624e 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"id": "md.lifeos.doubao-say",
"name": "Doubao Say",
- "version": "1.3.1",
+ "version": "1.4.0",
"author": "quanru and contributors",
"description": "Doubao Say turns speech into polished text with live captions and configurable tap or hold triggers on Wayland.",
"kinds": [
diff --git a/packaging/INSTALL.md b/packaging/INSTALL.md
index 6f8f8d0..60cf532 100644
--- a/packaging/INSTALL.md
+++ b/packaging/INSTALL.md
@@ -1,4 +1,4 @@
-# Doubao Say 1.3.1
+# Doubao Say 1.4.0
[Website](https://doubao-say.lifeos.md/) · [简体中文安装指南](https://doubao-say.lifeos.md/zh/guide/install)
@@ -43,7 +43,10 @@ may be stored by a clipboard manager. Direct typing through optional `wtype`
remains a Hyprland/Wayland feature; choose Clipboard paste on native X11.
Other Wayland compositors do not gain automatic input from this X11 support.
-Your user needs read access to keyboard events and write access to `/dev/uinput`.
+GNOME automatically uses permission-scoped GlobalShortcuts for the dictation
+trigger; it does not need raw keyboard read access. Other desktops use evdev
+and need read access to keyboard events. Input delivery may still require write
+access to `/dev/uinput`.
On this Omarchy setup, membership in `input` provides these permissions. If absent,
run `sudo usermod -aG input "$USER"` and log out/in. Never run the application as root.
Review this broad keyboard access before enabling it. Other Linux distributions
@@ -121,9 +124,10 @@ matching archive again; do not run install.py from the managed installation tree
Open the launcher and either sign in to Doubao or select the Volcengine official
API backend in Settings and add/test your speech API key. Then focus a text field
-and press Fn.
+and press Ctrl+;.
Tap to start/stop; hold to talk/release to finish; double-tap sends Enter.
-Choose another key in Settings if your keyboard does not expose Fn.
+Choose another shortcut in Settings, or use the edit button in the GNOME shortcut
+authorization dialog. Fn and raw shortcut recording remain evdev-only.
Double-tap can submit a message or execute a terminal command.
The control center checks the latest stable GitHub Release at most daily. A newer
diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh
index 152daff..f293c1a 100755
--- a/packaging/build-deb.sh
+++ b/packaging/build-deb.sh
@@ -7,7 +7,7 @@
# python3-installer
#
# Usage:
-# ./packaging/build-deb.sh # builds ../doubao-say_1.3.1-1_all.deb
+# ./packaging/build-deb.sh # builds ../doubao-say_1.4.0-1_all.deb
# ./packaging/build-deb.sh --install # also installs it locally
set -e
diff --git a/packaging/runtime-requirements.txt b/packaging/runtime-requirements.txt
index 1290485..46896f2 100644
--- a/packaging/runtime-requirements.txt
+++ b/packaging/runtime-requirements.txt
@@ -1,4 +1,4 @@
-# Complete Python dependency set tested for the 1.3.1 release.
+# Complete Python dependency set tested for the 1.4.0 release.
websockets==17.1
sounddevice==0.5.6
evdev==2.0.0
diff --git a/pyproject.toml b/pyproject.toml
index 5c389dc..e5ee070 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "doubao-say"
-version = "1.3.1"
+version = "1.4.0"
description = "Global push-to-hold voice input for Linux/Wayland, backed by Doubao ASR"
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/doubao_input/app.py b/src/doubao_input/app.py
index 5fa3ae1..c15640d 100644
--- a/src/doubao_input/app.py
+++ b/src/doubao_input/app.py
@@ -102,7 +102,7 @@ class DoubaoInputApp(Gtk.Application):
self.settings = Settings.load()
except (ValueError, TypeError, OSError):
logger.exception("Invalid settings; using defaults without overwriting the file")
- self.settings = Settings()
+ self.settings = Settings.desktop_defaults()
set_language(self.settings.language)
@property
diff --git a/src/doubao_input/product.py b/src/doubao_input/product.py
index 431b865..7162fe1 100644
--- a/src/doubao_input/product.py
+++ b/src/doubao_input/product.py
@@ -1,5 +1,5 @@
"""Single runtime source for Doubao Say release identity."""
-VERSION = "1.3.1"
+VERSION = "1.4.0"
REPOSITORY_URL = "https://github.com/quanru/doubao-say"
LATEST_RELEASE_API = "https://api.github.com/repos/quanru/doubao-say/releases/latest"
diff --git a/src/doubao_input/settings.py b/src/doubao_input/settings.py
index 2f07007..d4c2570 100644
--- a/src/doubao_input/settings.py
+++ b/src/doubao_input/settings.py
@@ -7,6 +7,7 @@ import sys
import tempfile
from urllib.parse import urlsplit
from doubao_input.i18n import LANGUAGES, tr
+from doubao_input.trigger.backend import trigger_backend
from doubao_input.recognition_providers import RECOGNITION_PROVIDER_IDS
KEY_CHOICES = {"Disabled": 0, "Fn": 464, "Ctrl": 29, "Shift": 42,
@@ -209,8 +210,8 @@ WAVEFORM_STYLES = ("bars", "waves", "ripples", "basketball")
class Settings:
version: int = 1
language: str = "en"
- doubao_key: int = 464
- doubao_modifiers: tuple[int, ...] = ()
+ doubao_key: int = 39
+ doubao_modifiers: tuple[int, ...] = (29,)
hold_ms: int = 350
double_ms: int = 300
double_enter: bool = True
@@ -308,11 +309,15 @@ class Settings:
or type(self.vibekey_enabled) is not bool):
raise ValueError(tr("Switch settings must be boolean", "开关设置必须为布尔值"))
+ @classmethod
+ def desktop_defaults(cls):
+ return cls()
+
@classmethod
def load(cls):
path = config_dir() / "doubao-say" / "settings.json"
if not path.exists():
- return cls()
+ return cls.desktop_defaults()
values = json.loads(path.read_text())
# Removed experimental restoration setting; accept old files once and
# omit the field on their next save.
@@ -338,6 +343,9 @@ class Settings:
# instead of discarding the entire file and falling back to defaults.
known = {item.name for item in fields(cls)}
values = {key: value for key, value in values.items() if key in known}
+ # Older key-only settings implied no modifiers. Preserve those choices.
+ if "doubao_key" in values and "doubao_modifiers" not in values:
+ values["doubao_modifiers"] = ()
defaults = cls()
for prefix in ("doubao", "vibekey_record", "vibekey_enter",
"vibekey_cancel", "vibekey_clockwise",
@@ -352,6 +360,15 @@ class Settings:
canonical_shortcut(saved_key, saved_modifiers))
values[key_field] = key
values[modifiers_field] = modifiers
+ # Retained evdev shortcuts may not be supported by the portal (including
+ # Fn and modifier-only presets). Migrate in memory before startup so an
+ # unsupported old binding cannot prevent the application from opening.
+ if trigger_backend() == "portal" and values["doubao_key"] != 0:
+ from doubao_input.trigger.portal import preferred_trigger
+ try:
+ preferred_trigger(values["doubao_key"], values["doubao_modifiers"])
+ except ValueError:
+ values.update(doubao_key=39, doubao_modifiers=(29,))
data = cls(**values)
data.validate()
return data
@@ -390,11 +407,13 @@ def desktop_entry(background=False):
"Exec=" + " ".join(map(quote, args)) + "\nIcon=" + str(Path(__file__).parent / "ui/bunspeak.svg") + "\n")
-def install_desktop():
+def install_desktop(*, portal=False):
data = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))
- path = data / "applications" / "doubao-say.desktop"
+ # GNOME GlobalShortcuts requires a valid reverse-DNS application ID.
+ name = "md.lifeos.DoubaoSay.desktop" if portal else "doubao-say.desktop"
+ path = data / "applications" / name
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(desktop_entry())
+ path.write_text(desktop_entry() + ("NoDisplay=true\n" if portal else ""))
return path
diff --git a/src/doubao_input/trigger/backend.py b/src/doubao_input/trigger/backend.py
new file mode 100644
index 0000000..31c1ad4
--- /dev/null
+++ b/src/doubao_input/trigger/backend.py
@@ -0,0 +1,13 @@
+"""Choose a desktop trigger without requiring a custom launch command."""
+import os
+
+
+def trigger_backend():
+ override = os.environ.get("DOUBAO_SAY_TRIGGER_BACKEND", "auto")
+ if override not in ("auto", "evdev", "portal"):
+ raise ValueError("DOUBAO_SAY_TRIGGER_BACKEND must be auto, evdev or portal")
+ if override != "auto":
+ return override
+ desktops = os.environ.get("XDG_CURRENT_DESKTOP", "").lower().split(":")
+ session = os.environ.get("XDG_SESSION_DESKTOP", "").lower()
+ return "portal" if "gnome" in desktops or session == "gnome" else "evdev"
diff --git a/src/doubao_input/trigger/controller.py b/src/doubao_input/trigger/controller.py
index caa393c..44489fa 100644
--- a/src/doubao_input/trigger/controller.py
+++ b/src/doubao_input/trigger/controller.py
@@ -49,7 +49,7 @@ class TriggerController:
settings = replace(settings, doubao_key=key, doubao_modifiers=modifiers)
fields = ("doubao_key", "doubao_modifiers", "hold_ms", "double_ms", "double_enter",
"vibekey_enabled")
- if (self._reader and self._listener_capture == self.capturing and self._settings
+ if (self._reader and self._reader.is_running() and self._listener_capture == self.capturing and self._settings
and all(getattr(settings, field) == getattr(self._settings, field) for field in fields)):
self._settings = replace(settings)
return self._available
@@ -65,7 +65,8 @@ class TriggerController:
on_aux_error=lambda message: self._error(message)
if generation == self._generation else None,
on_error=lambda message: self._device_error(message) if generation == self._generation else None,
- key_codes=keys, vibekey_enabled=settings.vibekey_enabled)
+ key_codes=keys, vibekey_enabled=settings.vibekey_enabled,
+ shortcut=(settings.doubao_key, settings.doubao_modifiers), capturing=self.capturing)
try:
started = candidate.start()
if strict and not started:
diff --git a/src/doubao_input/trigger/escape_guard.py b/src/doubao_input/trigger/escape_guard.py
index a833568..dc51d96 100644
--- a/src/doubao_input/trigger/escape_guard.py
+++ b/src/doubao_input/trigger/escape_guard.py
@@ -7,11 +7,13 @@ import json
import os
import subprocess
import time
+from doubao_input.trigger.backend import trigger_backend
class EscapeGuard:
def __init__(self, error=lambda message: None):
- self.enabled = bool(os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"))
+ self.enabled = bool(os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")) and (
+ trigger_backend() != "portal")
self.active = self.held = False
self._renewed = 0
self._name = f"doubao_escape_{os.getpid()}"
diff --git a/src/doubao_input/trigger/portal.py b/src/doubao_input/trigger/portal.py
new file mode 100644
index 0000000..55897cc
--- /dev/null
+++ b/src/doubao_input/trigger/portal.py
@@ -0,0 +1,233 @@
+"""Opt-in, permission-scoped XDG GlobalShortcuts trigger (no input devices)."""
+import uuid
+from doubao_input.i18n import tr
+
+DESTINATION = 'org.freedesktop.portal.Desktop'
+PATH = '/org/freedesktop/portal/desktop'
+INTERFACE = 'org.freedesktop.portal.GlobalShortcuts'
+
+
+def preferred_trigger(key, modifiers):
+ # XDG shortcut identifiers are XKB keysyms, not evdev key codes.
+ symbols = {39: 'semicolon', 66: 'F8', 67: 'F9', 57: 'space', 28: 'Return', 15: 'Tab'}
+ names = {29: 'CTRL', 42: 'SHIFT', 56: 'ALT', 125: 'LOGO'}
+ if key not in symbols or any(code not in names for code in modifiers):
+ raise ValueError(tr('Portal mode needs semicolon, F8, F9, Space, Return or Tab, optionally with modifiers. Choose a preset shortcut.',
+ 'Portal 模式请使用 分号、F8、F9、空格、回车或 Tab,可搭配修饰键;请先选择预设快捷键。'))
+ return '+'.join([*(names[code] for code in modifiers), symbols[key]])
+
+
+class PortalTrigger:
+ def __init__(self, on_press, on_release, on_error=None, on_key=None,
+ key_codes=None, *, shortcut=None, capturing=False,
+ transport_factory=None):
+ self._press, self._release, self._error, self._key = on_press, on_release, on_error, on_key
+ keys = set(key_codes or ()) - {1}
+ self._shortcut = shortcut
+ if self._shortcut is None and len(keys) == 1:
+ self._shortcut = (next(iter(keys)), ())
+ self._capturing = capturing
+ self._factory = transport_factory or GioPortal
+ self._transport = None
+ self._session = None
+ self._running = self._bound = self._down = False
+
+ def start(self):
+ if self._capturing:
+ raise ValueError(tr('Raw key recording is unavailable in portal mode. Choose a preset shortcut and approve it in the desktop dialog.',
+ 'Portal 模式不读取原始按键;请选择预设快捷键,并在桌面对话框中授权。'))
+ if self._shortcut and self._shortcut[0] == 0:
+ return True
+ if not self._shortcut:
+ raise ValueError(tr('Select a preset shortcut for portal mode.', '请为 Portal 模式选择预设快捷键。'))
+ trigger = preferred_trigger(*self._shortcut)
+ self._transport = self._factory(self._signal, self._fail)
+ self._running = True
+ self._preferred = trigger
+ try:
+ self._transport.request('CreateSession', {}, self._created)
+ except Exception:
+ self.stop()
+ raise
+ return True # Authorization is asynchronous; denial reports through on_error.
+
+ def _created(self, response, results):
+ if not self._running:
+ return
+ if response != 0 or not results.get('session_handle'):
+ self._fail('GlobalShortcuts session was not authorized.')
+ return
+ self._session = results['session_handle']
+ self._transport.request('BindShortcuts', {
+ 'session': self._session, 'trigger': self._preferred,
+ }, self._binding)
+
+ def _binding(self, response, results):
+ if not self._running:
+ return
+ if response != 0 or not any(item[0] == 'dictate' for item in results.get('shortcuts', ())):
+ self._fail(tr('The desktop did not authorize the dictation shortcut. No raw keyboard fallback was started.',
+ '桌面未授权语音快捷键,未回退到原始键盘读取。'))
+ return
+ self._bound = True
+
+ def _signal(self, name, values):
+ if not self._running or not values or values[0] != self._session:
+ return
+ if name == 'Closed':
+ self._fail(tr('The desktop closed the shortcut session.', '桌面关闭了快捷键会话。'))
+ return
+ if not self._bound or name not in ('Activated', 'Deactivated') or values[1] != 'dictate':
+ return
+ pressed = name == 'Activated'
+ if pressed == self._down:
+ return
+ self._down = pressed
+ key, modifiers = self._shortcut
+ if self._key:
+ for code in ((*modifiers, key) if pressed else (key, *reversed(modifiers))):
+ self._key(code, pressed)
+ else:
+ (self._press if pressed else self._release)()
+
+ def _fail(self, message):
+ self.stop()
+ if self._error:
+ self._error(message)
+
+ def stop(self):
+ self._running = self._bound = self._down = False
+ if self._transport:
+ self._transport.close(self._session)
+ self._transport = None
+ self._session = None
+
+ def is_running(self):
+ return self._running
+
+
+class GioPortal:
+ """Async D-Bus requests on GTK's GLib context, with bounded pending requests."""
+ def __init__(self, signal, error):
+ from gi.repository import Gio, GLib
+ from doubao_input.settings import install_desktop
+ install_desktop(portal=True)
+ self._gio, self._glib = Gio, GLib
+ # Registration must precede every other portal call on this peer. GTK
+ # can already have used its shared connection, so own a private peer.
+ address = Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION, None)
+ self._bus = Gio.DBusConnection.new_for_address_sync(address,
+ Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
+ Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)
+ self._registered = False
+ self._signal, self._error = signal, error
+ self._closed = False
+ self._requests = {}
+ self._subscriptions = []
+ self._session_paths = set()
+ for name in ('Activated', 'Deactivated'):
+ self._subscriptions.append(self._bus.signal_subscribe(
+ DESTINATION, INTERFACE, name, PATH, None, Gio.DBusSignalFlags.NONE,
+ lambda conn, sender, path, interface, name, params, *unused: signal(name, params.unpack())))
+ self._subscriptions.append(self._bus.signal_subscribe(
+ DESTINATION, 'org.freedesktop.portal.Session', 'Closed', None, None,
+ Gio.DBusSignalFlags.NONE,
+ lambda conn, sender, path, interface, name, params, *unused: signal(name, (path,))))
+
+ def owner_changed(conn, sender, path, interface, name, params, *unused):
+ if not params.unpack()[2]:
+ error(tr('The desktop shortcut service disconnected.', '桌面快捷键服务已断开。'))
+ self._subscriptions.append(self._bus.signal_subscribe(
+ 'org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged',
+ '/org/freedesktop/DBus', DESTINATION, Gio.DBusSignalFlags.NONE, owner_changed))
+
+ def request(self, method, options, callback):
+ G, V = self._glib, self._glib.Variant
+ if not self._registered:
+ def registered(conn, result, *unused):
+ if self._closed:
+ return
+ try:
+ conn.call_finish(result)
+ self._registered = True
+ self.request(method, options, callback)
+ except Exception as exc:
+ self._error(tr('Could not register Doubao Say with the desktop portal: ',
+ '无法向桌面 Portal 注册 Doubao Say:') + str(exc))
+ self._bus.call(DESTINATION, PATH, 'org.freedesktop.host.portal.Registry',
+ 'Register', V('(sa{sv})', ('md.lifeos.DoubaoSay', {})), None,
+ self._gio.DBusCallFlags.NONE, 10000, None, registered)
+ return
+ token = 'doubao_' + uuid.uuid4().hex
+ sender = self._bus.get_unique_name()[1:].replace('.', '_')
+ path = f'/org/freedesktop/portal/desktop/request/{sender}/{token}'
+ opts = {'handle_token': V('s', token)}
+ if method == 'CreateSession':
+ session_token = 'doubao_' + uuid.uuid4().hex
+ opts['session_handle_token'] = V('s', session_token)
+ self._session_paths.add(f'/org/freedesktop/portal/desktop/session/{sender}/{session_token}')
+ params = V('(a{sv})', (opts,))
+ else:
+ params = V('(oa(sa{sv})sa{sv})', (options['session'], [('dictate', {
+ 'description': V('s', tr('Dictate with Doubao Say', '使用 Doubao Say 语音输入')),
+ 'preferred_trigger': V('s', options['trigger']),
+ })], '', opts))
+
+ def response(conn, sender, object_path, interface, name, value, *unused):
+ self._clear_request(path)
+ if not self._closed:
+ try:
+ callback(*value.unpack())
+ except Exception as exc:
+ self._error(f'GlobalShortcuts: {exc}')
+
+ subscription = self._bus.signal_subscribe(DESTINATION,
+ 'org.freedesktop.portal.Request', 'Response', path, None,
+ self._gio.DBusSignalFlags.NONE, response)
+
+ def timeout():
+ if path in self._requests:
+ self._error(tr('Shortcut authorization timed out.', '快捷键授权超时。'))
+ return False
+
+ timer = G.timeout_add(120000, timeout)
+ self._requests[path] = subscription, timer
+
+ def called(conn, result, *unused):
+ try:
+ handle = conn.call_finish(result).unpack()[0]
+ if handle != path and not self._closed:
+ raise RuntimeError('Portal returned an unexpected request path.')
+ except Exception as exc:
+ if not self._closed:
+ self._error(f'GlobalShortcuts: {exc}')
+
+ self._bus.call(DESTINATION, PATH, INTERFACE, method, params, G.VariantType.new('(o)'),
+ self._gio.DBusCallFlags.NONE, 10000, None, called)
+
+ def _clear_request(self, path):
+ value = self._requests.pop(path, None)
+ if value:
+ self._bus.signal_unsubscribe(value[0])
+ self._glib.source_remove(value[1])
+
+ def close(self, session):
+ if self._closed:
+ return
+ self._closed = True
+ for path in list(self._requests):
+ self._bus.call(DESTINATION, path, 'org.freedesktop.portal.Request', 'Close',
+ None, None, self._gio.DBusCallFlags.NONE, 1000, None, None)
+ self._clear_request(path)
+ for subscription in self._subscriptions:
+ self._bus.signal_unsubscribe(subscription)
+ for path in self._session_paths | ({session} if session else set()):
+ self._bus.call(DESTINATION, path, 'org.freedesktop.portal.Session', 'Close',
+ None, None, self._gio.DBusCallFlags.NONE, 1000, None, None)
+
+ def flushed(conn, result, *unused):
+ try:
+ conn.flush_finish(result)
+ finally:
+ conn.close(None, None, None)
+ self._bus.flush(None, flushed)
diff --git a/src/doubao_input/trigger/reader.py b/src/doubao_input/trigger/reader.py
index 799d992..a29762a 100644
--- a/src/doubao_input/trigger/reader.py
+++ b/src/doubao_input/trigger/reader.py
@@ -1,4 +1,6 @@
"""Combined ordinary-keyboard and optional dedicated-device trigger reader."""
+from doubao_input.trigger.backend import trigger_backend
+from doubao_input.trigger.portal import PortalTrigger
from doubao_input.trigger.au05 import Au05Listener
from doubao_input.trigger.evdev_ptt import EvdevPtt
@@ -6,9 +8,14 @@ from doubao_input.trigger.evdev_ptt import EvdevPtt
class TriggerReader:
def __init__(self, on_press, on_release, on_error=None, on_key=None,
key_codes=None, on_aux=None, on_aux_error=None,
- vibekey_enabled=False):
- self._keyboard = EvdevPtt(on_press, on_release, on_error=on_error,
- on_key=on_key, key_codes=key_codes)
+ vibekey_enabled=False, shortcut=None, capturing=False):
+ backend = trigger_backend()
+ if backend == "portal":
+ self._keyboard = PortalTrigger(on_press, on_release, on_error=on_error,
+ on_key=on_key, key_codes=key_codes, shortcut=shortcut, capturing=capturing)
+ else:
+ self._keyboard = EvdevPtt(on_press, on_release, on_error=on_error,
+ on_key=on_key, key_codes=key_codes)
self._vibekey = (Au05Listener(on_aux or (lambda action, pressed: None),
on_error=on_aux_error)
if vibekey_enabled else None)
diff --git a/tests/README.md b/tests/README.md
index 929aefb..b1729e4 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -79,3 +79,22 @@ for underlying logic. Synthetic onboarding does not verify real credentials,
microphone capture, live ASR, system clipboard paste, or delivery into an
unrelated application; those require separate acceptance. The synthetic runtime
target does exercise the real Delivery state machine against its own GTK field.
+
+## GlobalShortcuts protocol acceptance
+
+On a Linux host with PyGObject, run the bounded, isolated protocol test:
+
+```sh
+DOUBAO_PORTAL_ISOLATED_TEST=1 PYTHONPATH=src timeout --signal=TERM --kill-after=3s 10s \
+ dbus-run-session -- .venv/bin/python tests/manual/portal_protocol.py
+```
+
+It uses the real Gio/D-Bus transport and a synthetic portal on a private session
+bus. It checks binding, hold/release through the gesture controller, rejection,
+and session cleanup while prohibiting construction of the raw input reader.
+It does not verify a compositor's permission dialog, physical shortcuts, GNOME
+compatibility, microphone capture or text delivery. Never run its fake portal
+on the user's existing session bus.
+
+For real GNOME Wayland permission-dialog and shortcut acceptance, see
+[tests/gnome/README.md](gnome/README.md) and the GNOME shortcut permissions workflow.
diff --git a/tests/contracts/test_release.py b/tests/contracts/test_release.py
index 05b1729..491978e 100644
--- a/tests/contracts/test_release.py
+++ b/tests/contracts/test_release.py
@@ -49,7 +49,7 @@ class ReleaseTest(unittest.TestCase):
notes = (ROOT / "RELEASE_NOTES.md").read_text()
self.assertIn("--notes-file RELEASE_NOTES.md", workflow)
self.assertNotIn("--generate-notes", workflow)
- for expected in ("Doubao Say 1.3.1", "Volcengine Seed ASR 2.0", "Deepgram Nova-3"):
+ for expected in ("Doubao Say 1.4.0", "Volcengine Seed ASR 2.0", "Deepgram Nova-3"):
self.assertIn(expected, notes)
def test_both_archives_exclude_ignored_source_files(self):
diff --git a/tests/contracts/test_version_check.py b/tests/contracts/test_version_check.py
index a656789..df56fa6 100644
--- a/tests/contracts/test_version_check.py
+++ b/tests/contracts/test_version_check.py
@@ -11,13 +11,13 @@ SPEC.loader.exec_module(VERSION_CHECK)
class VersionCheckTests(unittest.TestCase):
def test_sources_are_aligned_at_current_release(self):
- self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.3.1")
+ self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.4.0")
def test_exact_release_tag_is_accepted(self):
- self.assertEqual(VERSION_CHECK.validate("v1.3.1", ROOT), "1.3.1")
+ self.assertEqual(VERSION_CHECK.validate("v1.4.0", ROOT), "1.4.0")
def test_wrong_release_tag_is_rejected(self):
- with self.assertRaisesRegex(ValueError, "must be 'v1.3.1'"):
+ with self.assertRaisesRegex(ValueError, "must be 'v1.4.0'"):
VERSION_CHECK.validate("v1.1.0", ROOT)
diff --git a/tests/gnome/Dockerfile b/tests/gnome/Dockerfile
new file mode 100644
index 0000000..7d595c1
--- /dev/null
+++ b/tests/gnome/Dockerfile
@@ -0,0 +1,16 @@
+FROM fedora:43
+RUN dnf -y install gnome-shell gnome-control-center xdg-desktop-portal \
+ xdg-desktop-portal-gnome xdg-desktop-portal-gtk dbus-daemon \
+ python3-gobject python3-cairo python3-evdev mesa-dri-drivers \
+ mesa-libEGL mesa-libGL glib2 glibc-langpack-en procps-ng \
+ adwaita-icon-theme util-linux && dnf clean all
+RUN useradd --create-home --uid 1000 gnome-ci
+COPY src /workspace/src
+COPY tests/gnome /workspace/tests/gnome
+RUN mkdir -p /tmp/gnome-runtime && chown gnome-ci /tmp/gnome-runtime && chmod 700 /tmp/gnome-runtime
+ENV HOME=/home/gnome-ci XDG_RUNTIME_DIR=/tmp/gnome-runtime \
+ XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=GNOME \
+ XDG_SESSION_DESKTOP=gnome LIBGL_ALWAYS_SOFTWARE=1 \
+ GSK_RENDERER=cairo LANG=en_US.UTF-8 PYTHONPATH=/workspace/src
+WORKDIR /workspace
+CMD ["bash", "tests/gnome/launch-container.sh"]
diff --git a/tests/gnome/README.md b/tests/gnome/README.md
new file mode 100644
index 0000000..e7f29c4
--- /dev/null
+++ b/tests/gnome/README.md
@@ -0,0 +1,34 @@
+# Real GNOME shortcut acceptance
+
+Run the **GNOME shortcut permissions** GitHub Actions workflow on the branch to
+build Fedora 43 with GNOME Shell/Mutter 49 and the real GNOME GlobalShortcuts
+portal. It uses normal desktop detection and Settings.load(), with no trigger
+backend environment override or manually selected shortcut. The test runs as uid 1000 without membership in `input`. No portal
+implementation or GNOME permission response is mocked.
+
+Locally on a Linux Docker host:
+
+```sh
+docker build -t doubao-gnome-ci -f tests/gnome/Dockerfile .
+mkdir -p artifacts/gnome
+chmod 777 artifacts/gnome
+timeout --signal=TERM --kill-after=15s 180s docker run --rm \
+ -v "$PWD/artifacts/gnome:/evidence" doubao-gnome-ci
+```
+
+The root-owned, unreadable `/dev/input/event0` file is a **permission fixture**,
+not a physical input device. It reproduces evdev permission denial. The after
+case sends keyboard events through Mutter's virtual input device: GNOME presents
+the actual permission dialog, grants the shortcut, consumes it while bound, and
+releases it when the application closes the session. The test first cancels the
+dialog and retries the same settings before granting permission.
+
+Only this disposable, private compositor uses `--unsafe-mode` so the test can
+send compositor events and capture screenshots via Shell D-Bus. Never enable it
+on a personal desktop. No host input devices, credentials, microphone or cloud
+ASR are used. This verifies the production trigger/controller integration, not
+complete GNOME support for overlays, audio or text injection.
+
+Artifacts contain package versions, session and shell diagnostics, screenshots
+before and after the fix, both permission dialogs, and `result.json` with the
+observed start/stop sequence. A missing or unsuccessful result is a failed test.
diff --git a/tests/gnome/acceptance.py b/tests/gnome/acceptance.py
new file mode 100644
index 0000000..252d5f5
--- /dev/null
+++ b/tests/gnome/acceptance.py
@@ -0,0 +1,163 @@
+"""Real GNOME portal/UI acceptance; compositor key events, no synthetic portal."""
+import json
+import os
+from pathlib import Path
+import time
+import gi
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gio, GLib, Gtk
+from doubao_input.settings import Settings
+from doubao_input.trigger.controller import TriggerController
+from doubao_input.trigger.reader import TriggerReader
+from doubao_input.trigger.evdev_ptt import EvdevPtt
+
+out = Path('/evidence')
+bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+context = GLib.MainContext.default()
+events, errors, key_events = [], [], []
+
+def pump():
+ for _ in range(20):
+ if not context.pending():
+ break
+ context.iteration(False)
+
+def wait_for(predicate, description, timeout=15):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ pump()
+ if predicate():
+ return
+ time.sleep(.02)
+ raise AssertionError(f'Timed out: {description}; errors={errors}; events={events}')
+
+def shell(code):
+ reply = bus.call_sync('org.gnome.Shell', '/org/gnome/Shell', 'org.gnome.Shell',
+ 'Eval', GLib.Variant('(s)', (code,)), GLib.VariantType.new('(bs)'),
+ Gio.DBusCallFlags.NONE, 5000, None).unpack()
+ assert reply[0], reply
+ return reply[1]
+
+def key(value, pressed):
+ shell('global.doubaoCIKeyboard.notify_keyval(imports.gi.GLib.get_monotonic_time(), '
+ f'{value}, imports.gi.Clutter.KeyState.{"PRESSED" if pressed else "RELEASED"}); true')
+ pump()
+
+def tap(value):
+ key(value, True)
+ key(value, False)
+
+def screenshot(name):
+ # Window actors can be registered before their first compositor frame.
+ deadline = time.monotonic() + 1.0
+ while time.monotonic() < deadline:
+ pump()
+ time.sleep(.01)
+ result = bus.call_sync('org.gnome.Shell.Screenshot', '/org/gnome/Shell/Screenshot',
+ 'org.gnome.Shell.Screenshot', 'Screenshot',
+ GLib.Variant('(bbs)', (False, False, str(out / name))), None,
+ Gio.DBusCallFlags.NONE, 10000, None).unpack()
+ assert result[0] and (out / name).is_file(), result
+
+def portal_dialog_visible():
+ titles = shell('JSON.stringify(global.get_window_actors().filter(a=>a.visible).map(a=>a.meta_window.get_title()))')
+ return 'Add Keyboard Shortcuts' in titles
+
+application = Gtk.Application(application_id='md.lifeos.DoubaoSay')
+assert application.register(None)
+window = Gtk.ApplicationWindow(application=application, title='Doubao Say shortcut acceptance')
+window.set_default_size(600, 280)
+box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
+status = Gtk.Label(label='Before: evdev cannot read keyboard devices without broad access')
+entry = Gtk.Entry(placeholder_text='Unrelated focused input target')
+box.append(status)
+box.append(entry)
+window.set_child(box)
+keys = Gtk.EventControllerKey()
+keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
+keys.connect('key-pressed', lambda _, value, code, state: key_events.append(value) or False)
+window.add_controller(keys)
+window.present()
+entry.grab_focus()
+shell('import("resource:///org/gnome/shell/ui/main.js").then(m => m.overview.hide()); global.doubaoCIKeyboard = '
+ 'global.stage.context.get_backend().get_default_seat().create_virtual_device(imports.gi.Clutter.InputDeviceType.KEYBOARD_DEVICE); true')
+wait_for(lambda: window.get_mapped(), 'GTK window mapped')
+
+# The permission fixture is not a physical keyboard: it reproduces the denied
+# device ACL. GNOME events below come from Mutter's real virtual keyboard.
+assert os.geteuid() != 0
+try:
+ os.open('/dev/input/event0', os.O_RDONLY)
+except PermissionError:
+ pass
+else:
+ raise AssertionError('The isolated user unexpectedly has raw keyboard access')
+raw = EvdevPtt(lambda: events.append('raw-start'), lambda: events.append('raw-stop'), key_codes={66})
+try:
+ assert not raw.start(), 'evdev unexpectedly available'
+finally:
+ raw.stop()
+screenshot('01-before.png')
+
+control = TriggerController(TriggerReader, GLib.timeout_add, GLib.source_remove,
+ start=lambda: (events.append('start'), status.set_label('After: hold-to-talk started through GNOME')),
+ stop=lambda: (events.append('stop'), status.set_label('After: releasing shortcut stopped hold-to-talk')),
+ toggle=lambda: events.append('toggle'), enter=lambda: events.append('enter'),
+ cancel_input=lambda: events.append('cancel'), debug_edge=lambda *a: False,
+ error=lambda message: errors.append(message))
+assert 'DOUBAO_SAY_TRIGGER_BACKEND' not in os.environ
+settings = Settings.load()
+assert (settings.doubao_key, settings.doubao_modifiers) == (39, (29,))
+try:
+ control.configure(settings)
+ wait_for(portal_dialog_visible, 'GNOME shortcut permission dialog')
+ screenshot('02-permission-deny.png')
+ tap(0xff1b) # Escape -> actual Cancel/window-close UI action.
+ wait_for(lambda: len(errors) == 1, 'authorization rejection')
+ assert not control._reader.is_running()
+ assert not events, events
+ errors.clear()
+ # A failed reader must be replaceable even when settings have not changed.
+ control.configure(settings)
+ wait_for(portal_dialog_visible, 'GNOME shortcut permission dialog again')
+ screenshot('03-permission-allow.png')
+ key(0xffe9, True) # Alt+A -> the actual Add button mnemonic.
+ tap(ord('a'))
+ key(0xffe9, False)
+ wait_for(lambda: control._reader._keyboard._bound, 'GNOME accepted shortcut')
+ window.present()
+ entry.grab_focus()
+ wait_for(lambda: not portal_dialog_visible(), 'permission dialog closed')
+ key_events.clear()
+ key(0xffe3, True) # Control_L
+ key(0x3b, True) # semicolon
+ wait_for(lambda: events == ['start'], 'hold starts recording')
+ screenshot('04-hold.png')
+ key(0x3b, False)
+ key(0xffe3, False)
+ wait_for(lambda: events == ['start', 'stop'], 'release stops recording')
+ assert 0x3b not in key_events, f'semicolon leaked to focused target: {key_events}'
+ assert not errors, errors
+ screenshot('05-after.png')
+ control.close()
+ key(0xffe3, True)
+ tap(0x3b)
+ key(0xffe3, False)
+ wait_for(lambda: 0x3b in key_events, 'shortcut released after shutdown')
+ assert events == ['start', 'stop'], events
+ (out / 'result.json').write_text(json.dumps({
+ 'passed': True, 'raw_device_access': False, 'events': events,
+ 'automatic_backend': True, 'custom_launch_environment': False,
+ 'portal': 'real GNOME GlobalShortcuts', 'authorization': ['cancel', 'add'],
+ 'held_shortcut_consumed': True, 'shortcut_released_after_close': True,
+ 'scope': 'real GNOME/GTK trigger integration; no microphone, ASR or text injection',
+ }, indent=2))
+ print('PASS: real GNOME permission dialog, hold/release, consumption and cleanup')
+except Exception as exc:
+ screenshot('failure.png')
+ (out / 'failure.txt').write_text(str(exc) + '\n' + shell(
+ 'JSON.stringify(global.get_window_actors().filter(a=>a.visible).map(a=>a.meta_window.get_title()))'))
+ raise
+finally:
+ control.close()
+ window.destroy()
diff --git a/tests/gnome/launch-container.sh b/tests/gnome/launch-container.sh
new file mode 100644
index 0000000..3796763
--- /dev/null
+++ b/tests/gnome/launch-container.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+# GNOME Shell needs a system bus even with a headless, unprivileged compositor.
+# Only this disposable container gets the bus; the test itself runs as uid 1000.
+# Package installation can leave an empty seats directory even though systemd
+# is not PID 1. Let GNOME use its supported non-systemd session implementation.
+rmdir /run/systemd/seats 2>/dev/null || true
+# Docker mounts /dev at runtime, hiding files created during image build.
+mkdir -p /dev/input
+touch /dev/input/event0
+chmod 600 /dev/input/event0
+mkdir -p /run/dbus
+dbus-daemon --system --fork --nopidfile
+exec runuser -u gnome-ci -- dbus-run-session -- bash tests/gnome/run-session.sh
diff --git a/tests/gnome/run-session.sh b/tests/gnome/run-session.sh
new file mode 100755
index 0000000..0ccbd92
--- /dev/null
+++ b/tests/gnome/run-session.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exec > >(tee /evidence/session.txt) 2>&1
+trap 'kill "${shell_pid:-}" 2>/dev/null || true' EXIT
+rpm -q gnome-shell mutter xdg-desktop-portal xdg-desktop-portal-gnome gnome-control-center > /evidence/versions.txt
+id >> /evidence/versions.txt
+gsettings set org.gnome.desktop.interface enable-animations false
+gsettings set org.gnome.desktop.session idle-delay 0
+gsettings set org.gnome.desktop.screensaver lock-enabled false
+gsettings set org.gnome.shell welcome-dialog-last-shown-version '99.0'
+mkdir -p "$HOME/.config/xdg-desktop-portal" "$HOME/.local/share/applications"
+cat > "$HOME/.config/xdg-desktop-portal/portals.conf" <<'EOF'
+[preferred]
+default=gnome;gtk;
+org.freedesktop.impl.portal.GlobalShortcuts=gnome
+EOF
+gnome-shell --headless --wayland --unsafe-mode --virtual-monitor=1280x800 > /evidence/gnome-shell.txt 2>&1 &
+shell_pid=$!
+for attempt in {1..60}; do
+ if gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell \
+ --method org.gnome.Shell.Eval 'true' > /evidence/shell-ready.txt 2>&1; then
+ break
+ fi
+ kill -0 "$shell_pid"
+ sleep 1
+done
+# GNOME exports WAYLAND_DISPLAY to the activation environment, but shell children
+# cannot change this script's environment. Discover the private compositor socket.
+for socket in "$XDG_RUNTIME_DIR"/wayland-*; do
+ if [[ -S "$socket" ]]; then export WAYLAND_DISPLAY="${socket##*/}"; break; fi
+done
+: "${WAYLAND_DISPLAY:?GNOME did not create a Wayland socket}"
+dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE
+python3 tests/gnome/acceptance.py
diff --git a/tests/manual/portal_protocol.py b/tests/manual/portal_protocol.py
new file mode 100644
index 0000000..86daad9
--- /dev/null
+++ b/tests/manual/portal_protocol.py
@@ -0,0 +1,125 @@
+"""Bounded protocol check; run under dbus-run-session, never on the user's bus.
+
+Uses a synthetic portal over real Gio/D-Bus. No microphone or keyboard input.
+"""
+import os
+import tempfile
+from unittest.mock import Mock, patch
+from gi.repository import Gio, GLib
+from doubao_input.settings import Settings
+from doubao_input.trigger.controller import TriggerController
+from doubao_input.trigger.reader import TriggerReader
+from doubao_input.trigger.portal import DESTINATION, PATH, INTERFACE
+
+if not os.environ.get('DOUBAO_PORTAL_ISOLATED_TEST'):
+ raise SystemExit('Run with DOUBAO_PORTAL_ISOLATED_TEST=1 dbus-run-session -- ...')
+
+bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus',
+ 'RequestName', GLib.Variant('(su)', (DESTINATION, 0)),
+ GLib.VariantType.new('(u)'), Gio.DBusCallFlags.NONE, 1000, None)
+xml = '''<node><interface name="org.freedesktop.portal.GlobalShortcuts">
+<method name="CreateSession"><arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
+<method name="BindShortcuts"><arg type="o" direction="in"/><arg type="a(sa{sv})" direction="in"/>
+<arg type="s" direction="in"/><arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
+</interface><interface name="org.freedesktop.host.portal.Registry">
+<method name="Register"><arg type="s" direction="in"/><arg type="a{sv}" direction="in"/></method>
+</interface></node>'''
+session_xml = '<node><interface name="org.freedesktop.portal.Session"><method name="Close"/></interface></node>'
+sessions, closed, triggers = [], [], []
+denied = False
+
+def respond(sender, path, response, results):
+ bus.emit_signal(sender, path, 'org.freedesktop.portal.Request', 'Response',
+ GLib.Variant('(ua{sv})', (response, results)))
+ return False
+
+def close_session(conn, sender, path, interface, method, params, invocation):
+ closed.append(path)
+ invocation.return_value(None)
+
+def method(conn, sender, path, interface, name, params, invocation):
+ if name == 'Register':
+ assert params.unpack()[0] == 'md.lifeos.DoubaoSay'
+ invocation.return_value(None)
+ return
+ values = params.unpack()
+ opts = values[0] if name == 'CreateSession' else values[3]
+ prefix = sender[1:].replace('.', '_')
+ request = '/org/freedesktop/portal/desktop/request/' + prefix + '/' + opts['handle_token']
+ invocation.return_value(GLib.Variant('(o)', (request,)))
+ if name == 'CreateSession':
+ session = '/org/freedesktop/portal/desktop/session/' + prefix + '/' + opts['session_handle_token']
+ sessions.append(session)
+ bus.register_object(session, Gio.DBusNodeInfo.new_for_xml(session_xml).interfaces[0],
+ close_session, None, None)
+ results = {'session_handle': GLib.Variant('s', session)}
+ else:
+ assert values[1][0][0] == 'dictate'
+ triggers.append(values[1][0][1]['preferred_trigger'])
+ results = {'shortcuts': GLib.Variant('a(sa{sv})', [] if denied else [('dictate', {
+ 'trigger_description': GLib.Variant('s', 'Ctrl+F8'),
+ })])}
+ GLib.idle_add(respond, sender, request, 1 if denied and name == "BindShortcuts" else 0, results)
+
+for interface in Gio.DBusNodeInfo.new_for_xml(xml).interfaces:
+ bus.register_object(PATH, interface, method, None, None)
+loop = GLib.MainLoop()
+start, stop, error = Mock(), Mock(), Mock()
+control = TriggerController(TriggerReader, GLib.timeout_add, GLib.source_remove,
+ start=start, stop=stop, toggle=Mock(), enter=Mock(), cancel_input=Mock(),
+ debug_edge=lambda *a: False, error=error)
+failures = []
+completed = False
+
+def activate(pressed):
+ bus.emit_signal(None, PATH, INTERFACE, 'Activated' if pressed else 'Deactivated',
+ GLib.Variant('(osta{sv})', (sessions[-1], 'dictate', 0, {})))
+ return False
+
+def check():
+ try:
+ assert start.call_count == 1, start.call_args_list
+ assert stop.call_count == 1, stop.call_args_list
+ error.assert_not_called()
+ assert triggers == ['CTRL+F8'], triggers
+ control.close()
+ global denied
+ denied = True
+ control.configure(Settings(doubao_key=67))
+ except Exception as exc:
+ failures.append(repr(exc))
+ loop.quit()
+ return False
+
+def done():
+ try:
+ error.assert_called_once()
+ assert len(closed) == 2, closed
+ assert triggers == ['CTRL+F8', 'F9'], triggers
+ except Exception as exc:
+ failures.append(repr(exc))
+ global completed
+ completed = True
+ loop.quit()
+ return False
+
+# The transport must work even when raw device access is forbidden.
+with tempfile.TemporaryDirectory(prefix='doubao-portal-protocol-') as data_home, \
+ patch.dict(os.environ, {'DOUBAO_SAY_TRIGGER_BACKEND': 'portal', 'XDG_DATA_HOME': data_home}), \
+ patch('doubao_input.trigger.reader.EvdevPtt', side_effect=AssertionError('Raw input accessed')):
+ try:
+ control.configure(Settings(doubao_key=66, doubao_modifiers=(29,)))
+ GLib.timeout_add(200, lambda: activate(True))
+ GLib.timeout_add(650, lambda: activate(False))
+ GLib.timeout_add(800, check)
+ GLib.timeout_add(1200, done)
+ GLib.timeout_add(5000, loop.quit)
+ loop.run()
+ finally:
+ control.close()
+if not completed:
+ failures.append("Protocol check did not complete before its deadline")
+if failures:
+ raise SystemExit('; '.join(failures))
+print('PASS: real D-Bus binding, hold/release, denial and session cleanup; no raw reader')
diff --git a/tests/unit/test_portal_trigger.py b/tests/unit/test_portal_trigger.py
new file mode 100644
index 0000000..2ffd286
--- /dev/null
+++ b/tests/unit/test_portal_trigger.py
@@ -0,0 +1,120 @@
+import os
+import json
+from pathlib import Path
+import tempfile
+from unittest import TestCase
+from unittest.mock import Mock, patch
+from doubao_input.trigger.reader import TriggerReader
+from doubao_input.trigger.backend import trigger_backend
+from doubao_input.settings import Settings
+
+
+class PortalSelectionTest(TestCase):
+ def test_desktop_detection_and_explicit_overrides(self):
+ cases = [({}, "evdev"), ({"XDG_CURRENT_DESKTOP": "GNOME"}, "portal"),
+ ({"XDG_CURRENT_DESKTOP": "ubuntu:GNOME"}, "portal"),
+ ({"XDG_SESSION_DESKTOP": "gnome"}, "portal"),
+ ({"XDG_CURRENT_DESKTOP": "Hyprland"}, "evdev"),
+ ({"XDG_CURRENT_DESKTOP": "GNOME", "DOUBAO_SAY_TRIGGER_BACKEND": "evdev"}, "evdev"),
+ ({"XDG_CURRENT_DESKTOP": "KDE", "DOUBAO_SAY_TRIGGER_BACKEND": "portal"}, "portal")]
+ for environment, expected in cases:
+ with self.subTest(environment=environment), patch.dict(os.environ, environment, clear=True):
+ self.assertEqual(trigger_backend(), expected)
+
+ @patch.dict(os.environ, {"XDG_CURRENT_DESKTOP": "GNOME"}, clear=True)
+ @patch('doubao_input.trigger.reader.EvdevPtt')
+ def test_normal_gnome_launch_never_constructs_raw_reader(self, raw):
+ reader = TriggerReader(Mock(), Mock(), shortcut=(66, (29,)))
+ self.assertIsInstance(reader._keyboard, PortalTrigger)
+ raw.assert_not_called()
+
+ def test_normal_gnome_launch_defaults_and_legacy_fn_migration(self):
+ with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {
+ "XDG_CURRENT_DESKTOP": "GNOME", "XDG_CONFIG_HOME": root}, clear=True):
+ self.assertEqual((Settings.load().doubao_key, Settings.load().doubao_modifiers), (39, (29,)))
+ path = Path(root) / "doubao-say/settings.json"
+ path.parent.mkdir()
+ legacy = '{"doubao_key": 464, "doubao_modifiers": []}'
+ path.write_text(legacy)
+ settings = Settings.load()
+ self.assertEqual((settings.doubao_key, settings.doubao_modifiers), (39, (29,)))
+ self.assertEqual(path.read_text(), legacy)
+ for key, modifiers in ((29, ()), (42, ()), (56, ()), (125, ()),
+ (30, (29,)), (464, (29,))):
+ saved = json.dumps({"doubao_key": key, "doubao_modifiers": modifiers})
+ path.write_text(saved)
+ settings = Settings.load()
+ self.assertEqual((settings.doubao_key, settings.doubao_modifiers), (39, (29,)))
+ self.assertEqual(path.read_text(), saved)
+ for key in (0, 67):
+ path.write_text(json.dumps({"doubao_key": key, "doubao_modifiers": []}))
+ settings = Settings.load()
+ self.assertEqual((settings.doubao_key, settings.doubao_modifiers), (key, ()))
+
+ @patch.dict(os.environ, {'DOUBAO_SAY_TRIGGER_BACKEND': 'portal'})
+ @patch('doubao_input.trigger.reader.EvdevPtt')
+ def test_portal_mode_never_constructs_raw_keyboard_reader(self, raw):
+ TriggerReader(Mock(), Mock(), key_codes={1, 66})
+ raw.assert_not_called()
+
+from doubao_input.trigger.portal import PortalTrigger, preferred_trigger
+
+
+class PortalEdgesTest(TestCase):
+ def setUp(self):
+ self.transport = Mock()
+ self.edge, self.error = Mock(), Mock()
+ self.reader = PortalTrigger(Mock(), Mock(), on_key=self.edge, on_error=self.error,
+ shortcut=(66, (29,)), transport_factory=lambda signal, error: self.transport)
+ self.reader.start()
+ self.reader._created(0, {'session_handle': '/session/ours'})
+ self.reader._binding(0, {'shortcuts': [('dictate', {})]})
+
+ def test_hold_edges_filter_other_sessions_and_duplicate_signals(self):
+ self.reader._signal('Activated', ('/session/other', 'dictate', 0, {}))
+ self.reader._signal('Activated', ('/session/ours', 'other', 0, {}))
+ self.edge.assert_not_called()
+ for name in ['Activated', 'Activated', 'Deactivated', 'Deactivated']:
+ self.reader._signal(name, ('/session/ours', 'dictate', 0, {}))
+ self.assertEqual(self.edge.call_args_list,
+ [((29, True),), ((66, True),), ((66, False),), ((29, False),)])
+
+ def test_denial_closes_without_raw_fallback(self):
+ self.reader._binding(1, {})
+ self.assertFalse(self.reader.is_running())
+ self.transport.close.assert_called_once_with('/session/ours')
+ self.error.assert_called_once()
+ self.reader._signal('Activated', ('/session/ours', 'dictate', 0, {}))
+ self.edge.assert_not_called()
+
+ def test_empty_binding_is_not_reported_ready(self):
+ self.reader._binding(0, {'shortcuts': []})
+ self.assertFalse(self.reader.is_running())
+ self.error.assert_called_once()
+
+ def test_closed_session_reports_error_to_release_controller_gesture(self):
+ self.reader._signal('Activated', ('/session/ours', 'dictate', 0, {}))
+ self.reader._signal('Closed', ('/session/ours',))
+ self.error.assert_called_once()
+ self.assertFalse(self.reader.is_running())
+
+ def test_stop_ignores_late_signal_and_is_idempotent(self):
+ self.reader.stop()
+ self.reader.stop()
+ self.transport.close.assert_called_once()
+ self.reader._signal('Activated', ('/session/ours', 'dictate', 0, {}))
+ self.edge.assert_not_called()
+
+ def test_unsupported_raw_capture_does_not_open_transport(self):
+ factory = Mock()
+ reader = PortalTrigger(Mock(), Mock(), shortcut=(66, ()), capturing=True,
+ transport_factory=factory)
+ with self.assertRaisesRegex(ValueError, 'Raw key recording'):
+ reader.start()
+ factory.assert_not_called()
+
+ def test_supported_xdg_syntax_and_unsupported_fn(self):
+ self.assertEqual(preferred_trigger(66, (29, 42)), 'CTRL+SHIFT+F8')
+ self.assertEqual(preferred_trigger(39, (29,)), 'CTRL+semicolon')
+ with self.assertRaises(ValueError):
+ preferred_trigger(464, ())
diff --git a/tests/unit/test_product.py b/tests/unit/test_product.py
index a7fe2f8..fe683fd 100644
--- a/tests/unit/test_product.py
+++ b/tests/unit/test_product.py
@@ -51,7 +51,7 @@ class ProductTest(TestCase):
self.assertNotIn("private-device-identifier", data)
self.assertNotIn("cookies", data)
self.assertNotIn("transcript", data)
- self.assertEqual(json.loads(data)["product_version"], "1.3.1")
+ self.assertEqual(json.loads(data)["product_version"], "1.4.0")
self.assertEqual(json.loads(data)["recognition_provider"], "volcengine")
self.assertEqual(json.loads(data)["recent_stages"], [
{"stage": "first_result", "after_ms": 125}])
diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py
index 9fbc3ce..c60a91d 100644
--- a/tests/unit/test_settings.py
+++ b/tests/unit/test_settings.py
@@ -4,7 +4,7 @@ import json
from pathlib import Path
import tempfile
from unittest.mock import patch
-from doubao_input.settings import Settings, desktop_entry, trigger_shortcut_display
+from doubao_input.settings import Settings, desktop_entry, install_desktop, trigger_shortcut_display
from doubao_input.i18n import tr, set_language
from doubao_input.settings import (DEFAULT_POLISH_PROMPT_EN, DEFAULT_POLISH_PROMPT_ZH,
FORMATTING_POLISH_PROMPT, PREVIOUS_POLISH_PROMPT_ZH,
@@ -187,6 +187,17 @@ class SettingsTest(unittest.TestCase):
with self.subTest(values=values), self.assertRaises(ValueError):
Settings(**values).validate()
+ def test_portal_identity_launcher_preserves_existing_install_entry(self):
+ with tempfile.TemporaryDirectory() as root, patch.dict("os.environ", {"XDG_DATA_HOME": root}):
+ legacy = Path(root) / "applications/doubao-say.desktop"
+ legacy.parent.mkdir()
+ legacy.write_text("Existing managed launcher")
+ registered = install_desktop(portal=True)
+ self.assertEqual(registered.name, "md.lifeos.DoubaoSay.desktop")
+ self.assertIn("Name=Doubao Say", registered.read_text())
+ self.assertIn("NoDisplay=true", registered.read_text())
+ self.assertEqual(legacy.read_text(), "Existing managed launcher")
+
def test_launcher(self):
self.assertIn("--background", desktop_entry(True))
self.assertNotIn("--background", desktop_entry(False))
diff --git a/tests/unit/test_trigger_controller.py b/tests/unit/test_trigger_controller.py
index 67033ee..0f86f6a 100644
--- a/tests/unit/test_trigger_controller.py
+++ b/tests/unit/test_trigger_controller.py
@@ -28,7 +28,7 @@ class TriggerControllerTest(TestCase):
toggle=self.toggle, enter=self.enter, cancel_input=self.cancel,
debug_edge=Mock(return_value=False), error=self.error, shortcut=self.shortcut,
is_recording=lambda: self.recording_active)
- self.settings = Settings(doubao_key=100)
+ self.settings = Settings(doubao_key=100, doubao_modifiers=())
self.control.configure(self.settings)
def edge(self, code, pressed):
@@ -314,3 +314,10 @@ class TriggerControllerTest(TestCase):
self.start.assert_not_called()
self.enter.assert_not_called()
self.cancel.assert_not_called()
+
+ def test_stopped_reader_is_recreated_with_unchanged_settings(self):
+ previous = self.readers[-1]
+ previous.is_running.return_value = False
+ self.control.configure(self.settings)
+ self.assertIsNot(self.readers[-1], previous)
+ previous.stop.assert_called_once()
diff --git a/tests/unit/test_updates.py b/tests/unit/test_updates.py
index f1a78d0..95a3dd9 100644
--- a/tests/unit/test_updates.py
+++ b/tests/unit/test_updates.py
@@ -26,9 +26,9 @@ class UpdateTest(TestCase):
self.assertFalse(newer_release("1.1.9", "1.3.0"))
def test_only_new_stable_release_produces_allowlisted_url(self):
- self.assertEqual(release_info({"tag_name": "v1.4.0"}),
- UpdateInfo("1.4.0", "https://github.com/quanru/doubao-say/releases/tag/v1.4.0"))
- self.assertIsNone(release_info({"tag_name": "v1.4.0", "prerelease": True}))
+ self.assertEqual(release_info({"tag_name": "v1.5.0"}),
+ UpdateInfo("1.5.0", "https://github.com/quanru/doubao-say/releases/tag/v1.5.0"))
+ self.assertIsNone(release_info({"tag_name": "v1.5.0", "prerelease": True}))
with self.assertRaises(ValueError):
release_info({"tag_name": "https://malicious.example"})
@@ -37,15 +37,15 @@ class UpdateTest(TestCase):
with tempfile.TemporaryDirectory() as root, patch.dict(
os.environ, {"XDG_CONFIG_HOME": root}), patch(
"doubao_input.updates.request.urlopen",
- return_value=Response({"tag_name": "v1.4.0"})):
+ return_value=Response({"tag_name": "v1.5.0"})):
checker = UpdateChecker(callbacks.append, found.append, clock=lambda: 1000)
checker._fetch()
self.assertEqual(found, [])
callbacks.pop()()
- self.assertEqual(found[0].version, "1.4.0")
+ self.assertEqual(found[0].version, "1.5.0")
cache = json.loads(checker.cache_path().read_text())
self.assertEqual(cache["checked_at"], 1000)
- self.assertEqual(cache["current_version"], "1.3.1")
+ self.assertEqual(cache["current_version"], "1.4.0")
self.assertEqual(checker.cache_path().stat().st_mode & 0o777, 0o600)
def test_fresh_cache_avoids_network_and_repeats_notification(self):
@@ -55,19 +55,19 @@ class UpdateTest(TestCase):
checker = UpdateChecker(callbacks.append, found.append, clock=lambda: 1000)
checker.cache_path().parent.mkdir(parents=True)
checker.cache_path().write_text(json.dumps({
- "checked_at": 999, "tag_name": "v1.4.0",
- "current_version": "1.3.1",
+ "checked_at": 999, "tag_name": "v1.5.0",
+ "current_version": "1.4.0",
"draft": False, "prerelease": False}))
with patch.object(checker, "_fetch") as fetch:
checker.check()
fetch.assert_not_called()
callbacks.pop()()
- self.assertEqual(found[0].version, "1.4.0")
+ self.assertEqual(found[0].version, "1.5.0")
def test_close_suppresses_queued_notification(self):
callbacks, found = [], []
checker = UpdateChecker(callbacks.append, found.append)
- checker._deliver(UpdateInfo("1.4.0", "https://example.test"))
+ checker._deliver(UpdateInfo("1.5.0", "https://example.test"))
checker.close()
callbacks.pop()()
self.assertEqual(found, [])
@@ -81,7 +81,7 @@ class UpdateTest(TestCase):
checker._fetch()
cache = json.loads(checker.cache_path().read_text())
self.assertEqual(cache["checked_at"], 1000)
- self.assertEqual(cache["tag_name"], "1.3.1")
+ self.assertEqual(cache["tag_name"], "1.4.0")
def test_offline_check_preserves_previous_update(self):
found = []
@@ -90,9 +90,9 @@ class UpdateTest(TestCase):
"doubao_input.updates.request.urlopen", side_effect=URLError("offline")):
checker = UpdateChecker(lambda callback: callback(), found.append,
clock=lambda: 100000)
- checker._save_cache("v1.4.0")
+ checker._save_cache("v1.5.0")
checker._fetch()
- self.assertEqual(found[0].version, "1.4.0")
+ self.assertEqual(found[0].version, "1.5.0")
def test_cache_from_another_installed_version_is_ignored(self):
callbacks, found = [], []